Skip to content

Commit 59d1ad8

Browse files
committed
start work to count blocks
1 parent 1205101 commit 59d1ad8

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*!
2+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3+
* SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
import assert from 'assert'
7+
import { Messenger } from '../../codewhispererChat/controllers/chat/messenger/messenger'
8+
import { CWCTelemetryHelper } from '../../codewhispererChat/controllers/chat/telemetryHelper'
9+
import { performanceTest } from '../../shared/performance/performance'
10+
import { AppToWebViewMessageDispatcher } from '../../codewhispererChat/view/connector/connector'
11+
12+
// 10 code blocks
13+
const longMessage =
14+
'Sure, here are some good code samples to know across different languages and concepts:1. **Python**```python# List Comprehensionsquares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]# Lambda Functionsdouble = lambda x: x * 2print(double(5)) # Output: 10```2. **JavaScript**```javascript// Arrow Functionsconst double = x => x * 2;console.log(double(5)); // Output: 10// Array Methodsconst numbers = [1, 2, 3, 4, 5];const doubledNumbers = numbers.map(num => num * 2); // [2, 4, 6, 8, 10]```3. **Java**```java// StreamsList<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);List<Integer> doubledNumbers = numbers.stream() .map(n -> n * 2) .collect(Collectors.toList());// doubledNumbers = [2, 4, 6, 8, 10]```4. **C#**```csharp// LINQvar numbers = new List<int> { 1, 2, 3, 4, 5 };var doubledNumbers = numbers.Select(n => n * 2); // { 2, 4, 6, 8, 10 }```5. **Ruby**```ruby# Block Syntaxdoubled_numbers = [1, 2, 3, 4, 5].map { |n| n * 2 } # [2, 4, 6, 8, 10]```6. **SQL**```sql-- SubqueriesSELECT name, (SELECT COUNT(*) FROM orders WHERE orders.customer_id = customers.id) AS order_countFROM customers;```7. **Regular Expressions**```javascript// JavaScriptconst pattern = /\\b\\w*@\\w*\\.\\w{2,}\\b/g;// emailAddresses = ["[email protected]", "[email protected]"]```8. **Recursion**```python# Pythondef factorial(n): if n == 0: return 1 else: return n * factorial(n-1)print(factorial(5)) # Output: 120```9. **Multithreading**```java// Javapublic class MyRunnable implements Runnable { public void run() { // Code to be executed in a separate thread }}Thread myThread = new Thread(new MyRunnable());myThread.start();```10. **Error Handling**```javascript// JavaScripttry { // Code that might throw an error} catch (error) { console.error(error.message);} finally { // Code that will always execute}```These are just a few examples of good code samples to know across different languages and concepts. They cover topics like functional programming, data manipulation, regular expressions, recursion, concurrency, and error handling.'
15+
// 5 code blocks
16+
const mediumMessage =
17+
'Certainly! Here are 5 more code examples covering different concepts and languages:1. **Python Decorators**```pythondef timer(func): import time def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f"{func.__name__} ran in {end - start:.2f} seconds") return result return wrapper@timerdef slow_function(): import time time.sleep(2)slow_function() # Output: slow_function ran in 2.00 seconds```2. **JavaScript Promises and Async/Await**```javascriptfunction fetchData() { return new Promise((resolve, reject) => { setTimeout(() => resolve("Data fetched"), 2000); });}async function getData() { try { console.log("Fetching data..."); const result = await fetchData(); console.log(result); } catch (error) { console.error("Error:", error); }}getData();// Output:// Fetching data...// Data fetched (after 2 seconds)```3. **C++ Templates**```cpp#include <iostream>#include <vector>template<typename T>T sum(const std::vector<T>& vec) { T total = 0; for (const auto& item : vec) { total += item; } return total;}int main() { std::vector<int> intVec = {1, 2, 3, 4, 5}; std::vector<double> doubleVec = {1.1, 2.2, 3.3, 4.4, 5.5}; std::cout << "Sum of integers: " << sum(intVec) << std::endl; std::cout << "Sum of doubles: " << sum(doubleVec) << std::endl; return 0;}```4. **Go Goroutines and Channels**```gopackage mainimport ( "fmt" "time")func worker(id int, jobs <-chan int, results chan<- int) { for j := range jobs { fmt.Println("worker", id, "started job", j) time.Sleep(time.Second) fmt.Println("worker", id, "finished job", j) results <- j * 2 }}func main() { jobs := make(chan int, 100) results := make(chan int, 100) for w := 1; w <= 3; w++ { go worker(w, jobs, results) } for j := 1; j <= 5; j++ { jobs <- j } close(jobs) for a := 1; a <= 5; a++ { <-results }}```5. **Rust Ownership and Borrowing**```rustfn main() { let s1 = String::from("hello"); let len = calculate_length(&s1); println!("The length of \'{}\' is {}.", s1, len);}fn calculate_length(s: &String) -> usize { s.len()}```These examples showcase more advanced concepts like decorators in Python, asynchronous programming in JavaScript, templates in C++, concurrency in Go, and Rust\'s ownership system. Each of these concepts is fundamental to their respective languages and can greatly enhance your programming capabilities.'
18+
// 2 code blocks
19+
const shortMessage =
20+
"Certainly! Here are two more code examples that demonstrate useful concepts:\n\n1. **Python Context Managers**\n\nContext managers are a powerful feature in Python for resource management. They ensure that resources are properly acquired and released, even if exceptions occur.\n\n```python\nimport contextlib\n\[email protected]\ndef file_manager(filename, mode):\n try:\n f = open(filename, mode)\n yield f\n finally:\n f.close()\n\n# Using the context manager\nwith file_manager('example.txt', 'w') as file:\n file.write('Hello, World!')\n\n# The file is automatically closed after the with block, even if an exception occurs\n```\n\nThis example demonstrates how to create and use a custom context manager. It's particularly useful for managing resources like file handles, network connections, or database transactions.\n\n2. **JavaScript Closures**\n\nClosures are a fundamental concept in JavaScript that allows a function to access variables from its outer (enclosing) lexical scope even after the outer function has returned.\n\n```javascript\nfunction createCounter() {\n let count = 0;\n return function() {\n count += 1;\n return count;\n }\n}\n\nconst counter = createCounter();\nconsole.log(counter()); // Output: 1\nconsole.log(counter()); // Output: 2\nconsole.log(counter()); // Output: 3\n\nconst counter2 = createCounter();\nconsole.log(counter2()); // Output: 1\n```\n\nIn this example, the `createCounter` function returns an inner function that has access to the `count` variable in its closure. Each time you call `createCounter()`, it creates a new closure with its own `count` variable. This is a powerful pattern for creating private state in JavaScript.\n\nThese examples demonstrate important programming concepts that are widely used in real-world applications. Context managers in Python help with resource management, while closures in JavaScript are crucial for understanding scope and creating private state."
21+
22+
function performanceTestWrapper(label: string, message: string, expectedCount: number) {
23+
return performanceTest(
24+
{
25+
testRuns: 1,
26+
linux: {
27+
userCpuUsage: 180,
28+
systemCpuUsage: 35,
29+
heapTotal: 4,
30+
},
31+
darwin: {
32+
userCpuUsage: 180,
33+
systemCpuUsage: 35,
34+
heapTotal: 4,
35+
},
36+
win32: {
37+
userCpuUsage: 180,
38+
systemCpuUsage: 35,
39+
heapTotal: 4,
40+
},
41+
},
42+
label,
43+
function () {
44+
return {
45+
setup: async () => {
46+
const messenger = new Messenger({} as AppToWebViewMessageDispatcher, {} as CWCTelemetryHelper)
47+
return messenger
48+
},
49+
execute: async (messenger: Messenger) => {
50+
return await messenger.countTotalNumberOfCodeBlocks(message)
51+
},
52+
verify: async (_messenger: Messenger, result: number) => {
53+
assert.strictEqual(result, expectedCount)
54+
},
55+
}
56+
}
57+
)
58+
}
59+
60+
describe('countTableNumberOfCodeBlocks', function () {
61+
describe('performance tests', function () {
62+
performanceTestWrapper('short', shortMessage, 2)
63+
performanceTestWrapper('medium', mediumMessage, 5)
64+
performanceTestWrapper('long', longMessage, 10)
65+
})
66+
})

0 commit comments

Comments
 (0)