Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -13,337 +13,305 @@ app.logger = logging.getLogger("CodeSearchAPI")
|
|
13 |
|
14 |
# 预定义代码片段
|
15 |
CODE_SNIPPETS = [
|
16 |
-
"
|
17 |
-
"
|
18 |
-
"import
|
19 |
-
"
|
20 |
-
"
|
21 |
-
"
|
22 |
-
"import
|
23 |
-
"
|
24 |
-
"
|
25 |
-
"
|
26 |
-
"
|
27 |
-
"
|
28 |
-
"
|
29 |
-
"
|
30 |
-
"
|
31 |
-
"
|
32 |
-
"
|
33 |
-
"
|
34 |
-
"
|
35 |
-
"
|
36 |
-
"
|
37 |
-
"
|
38 |
-
"
|
39 |
-
"
|
40 |
-
"
|
41 |
-
"
|
42 |
-
"
|
43 |
-
"
|
44 |
-
"
|
45 |
-
"
|
46 |
-
"
|
47 |
-
"
|
48 |
-
"
|
49 |
-
"
|
50 |
-
"
|
51 |
-
"
|
52 |
-
"
|
53 |
-
"
|
54 |
-
"
|
55 |
-
"
|
56 |
-
"
|
57 |
-
"
|
58 |
-
"
|
59 |
-
"
|
60 |
-
"
|
61 |
-
"
|
62 |
-
"
|
63 |
-
"import
|
64 |
-
"import
|
65 |
-
"import
|
66 |
-
"import
|
67 |
-
"import
|
68 |
-
"import
|
69 |
-
"import
|
70 |
-
"import
|
71 |
-
"import
|
72 |
-
"import
|
73 |
-
"import
|
74 |
-
"
|
75 |
-
"
|
76 |
-
"import
|
77 |
-
"import
|
78 |
-
"import
|
79 |
-
"import
|
80 |
-
"import
|
81 |
-
"
|
82 |
-
"
|
83 |
-
"
|
84 |
-
"
|
85 |
-
"
|
86 |
-
"
|
87 |
-
"
|
88 |
-
"
|
89 |
-
"
|
90 |
-
"
|
91 |
-
"
|
92 |
-
"
|
93 |
-
"import
|
94 |
-
"import
|
95 |
-
"
|
96 |
-
"
|
97 |
-
"
|
98 |
-
"
|
99 |
-
"
|
100 |
-
"
|
101 |
-
"import
|
102 |
-
"import
|
103 |
-
"import
|
104 |
-
"class MyClass
|
105 |
-
"
|
106 |
-
"class MyClass
|
107 |
-
"class MyClass
|
108 |
-
"class ChildClass
|
109 |
-
"class ChildClass
|
110 |
-
"class MyClass
|
111 |
-
"class MyClass
|
112 |
-
"
|
113 |
-
"
|
114 |
-
"
|
115 |
-
"
|
116 |
-
"""
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
"
|
121 |
-
|
122 |
-
"""
|
123 |
-
|
124 |
-
|
125 |
-
"
|
126 |
-
"
|
127 |
-
"
|
128 |
-
"
|
129 |
-
"
|
130 |
-
"
|
131 |
-
"
|
132 |
-
"
|
133 |
-
"
|
134 |
-
"
|
135 |
-
"{
|
136 |
-
"{
|
137 |
-
"
|
138 |
-
"
|
139 |
-
"
|
140 |
-
"
|
141 |
-
"""
|
142 |
-
|
143 |
-
|
144 |
-
"
|
145 |
-
"
|
146 |
-
"
|
147 |
-
"
|
148 |
-
"for
|
149 |
-
"
|
150 |
-
"
|
151 |
-
"
|
152 |
-
"
|
153 |
-
"
|
154 |
-
"
|
155 |
-
"
|
156 |
-
"
|
157 |
-
"
|
158 |
-
"
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
"
|
165 |
-
|
166 |
-
|
167 |
-
"
|
168 |
-
|
169 |
-
"
|
170 |
-
"
|
171 |
-
"
|
172 |
-
"
|
173 |
-
"
|
174 |
-
"
|
175 |
-
"
|
176 |
-
"
|
177 |
-
"
|
178 |
-
"
|
179 |
-
"
|
180 |
-
"
|
181 |
-
"
|
182 |
-
"
|
183 |
-
"
|
184 |
-
"
|
185 |
-
"
|
186 |
-
"
|
187 |
-
"
|
188 |
-
"
|
189 |
-
"
|
190 |
-
"
|
191 |
-
"
|
192 |
-
"
|
193 |
-
"
|
194 |
-
"
|
195 |
-
"
|
196 |
-
"
|
197 |
-
"
|
198 |
-
"
|
199 |
-
"
|
200 |
-
"
|
201 |
-
"
|
202 |
-
"
|
203 |
-
"
|
204 |
-
"
|
205 |
-
"
|
206 |
-
"
|
207 |
-
"
|
208 |
-
"
|
209 |
-
"
|
210 |
-
"
|
211 |
-
"
|
212 |
-
"
|
213 |
-
"
|
214 |
-
"
|
215 |
-
"
|
216 |
-
"
|
217 |
-
"
|
218 |
-
"
|
219 |
-
"
|
220 |
-
"
|
221 |
-
"
|
222 |
-
"
|
223 |
-
"
|
224 |
-
"
|
225 |
-
"
|
226 |
-
"
|
227 |
-
"
|
228 |
-
"
|
229 |
-
"
|
230 |
-
"
|
231 |
-
"
|
232 |
-
"
|
233 |
-
"
|
234 |
-
"
|
235 |
-
"
|
236 |
-
"
|
237 |
-
"
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
"
|
245 |
-
"
|
246 |
-
"
|
247 |
-
"
|
248 |
-
"
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
"
|
255 |
-
"
|
256 |
-
"
|
257 |
-
"
|
258 |
-
"
|
259 |
-
"
|
260 |
-
"
|
261 |
-
"
|
262 |
-
"
|
263 |
-
"
|
264 |
-
"
|
265 |
-
"
|
266 |
-
"
|
267 |
-
"
|
268 |
-
"
|
269 |
-
"
|
270 |
-
"
|
271 |
-
"
|
272 |
-
"
|
273 |
-
"
|
274 |
-
"
|
275 |
-
"
|
276 |
-
"
|
277 |
-
"
|
278 |
-
"
|
279 |
-
"
|
280 |
-
"
|
281 |
-
"
|
282 |
-
"
|
283 |
-
"
|
284 |
-
"
|
285 |
-
"
|
286 |
-
"
|
287 |
-
"
|
288 |
-
"
|
289 |
-
"
|
290 |
-
"
|
291 |
-
"
|
292 |
-
"
|
293 |
-
"
|
294 |
-
"
|
295 |
-
"
|
296 |
-
"
|
297 |
-
"
|
298 |
-
"
|
299 |
-
"
|
300 |
-
"
|
301 |
-
"
|
302 |
-
"
|
303 |
-
"
|
304 |
-
"
|
305 |
-
"
|
306 |
-
"
|
307 |
-
"
|
308 |
-
"
|
309 |
-
"
|
310 |
-
"""
|
311 |
-
"
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
"def close_db(conn): conn.close()",
|
316 |
-
"def create_table(conn, name, columns): conn.execute(f'CREATE TABLE {name} ({columns})')",
|
317 |
-
"def drop_table(conn, name): conn.execute(f'DROP TABLE {name}')",
|
318 |
-
"def table_exists(conn, name): return conn.execute(f\"SELECT name FROM sqlite_master WHERE type='table' AND name='{name}'\").fetchone()",
|
319 |
-
"def list_tables(conn): return conn.execute(\"SELECT name FROM sqlite_master WHERE type='table'\").fetchall()",
|
320 |
-
"""from sqlalchemy import Column, Integer, String
|
321 |
-
class User(Base):
|
322 |
-
__tablename__ = 'users'
|
323 |
-
id = Column(Integer, primary_key=True)
|
324 |
-
name = Column(String)""",
|
325 |
-
"session.add(User(name='John'))",
|
326 |
-
"session.query(User).filter_by(name='John')",
|
327 |
-
"session.query(User).filter_by(name='John').delete()",
|
328 |
-
"session.query(User).filter_by(name='John').update({'name': 'Bob'})",
|
329 |
-
"Base = declarative_base()",
|
330 |
-
"class Admin(User): pass",
|
331 |
-
"id = Column(Integer, primary_key=True)",
|
332 |
-
"name = Column(String, unique=True)",
|
333 |
-
"name = Column(String, default='Unknown')",
|
334 |
-
"import csv; def export_csv(data, path): open(path, 'w').write('\\n'.join([','.join(map(str, row)) for row in data]))",
|
335 |
-
"import pandas as pd; pd.DataFrame(data).to_excel(path)",
|
336 |
-
"import json; json.dump(data, open(path, 'w'))",
|
337 |
-
"pd.read_excel(path).values.tolist()",
|
338 |
-
"pd.concat([pd.read_excel(f) for f in files])",
|
339 |
-
"with pd.ExcelWriter(path, mode='a') as writer: df.to_excel(writer, sheet_name='New')",
|
340 |
-
"from openpyxl.styles import copy; copy.copy(style)",
|
341 |
-
"from openpyxl.styles import PatternFill; cell.fill = PatternFill(start_color='FFFF00', fill_type='solid')",
|
342 |
-
"from openpyxl.styles import Font; cell.font = Font(bold=True)",
|
343 |
-
"sheet['A1'].value",
|
344 |
-
"sheet['A1'] = value",
|
345 |
-
"from PIL import Image; Image.open(path).size",
|
346 |
-
"from PIL import Image; Image.open(path).resize((w, h))"
|
347 |
|
348 |
]
|
349 |
|
|
|
13 |
|
14 |
# 预定义代码片段
|
15 |
CODE_SNIPPETS = [
|
16 |
+
"System.out.println(\"Hello, World!\");",
|
17 |
+
"public static int sum(int a, int b) { return a + b; }",
|
18 |
+
"import java.util.Random; public static int generateRandomNumber() { return new Random().nextInt(); }",
|
19 |
+
"public static boolean isEven(int number) { return number % 2 == 0; }",
|
20 |
+
"public static int stringLength(String str) { return str.length(); }",
|
21 |
+
"import java.time.LocalDate; public static LocalDate getCurrentDate() { return LocalDate.now(); }",
|
22 |
+
"import java.io.File; public static boolean fileExists(String path) { return new File(path).exists(); }",
|
23 |
+
"import java.nio.file.Files; import java.nio.file.Paths; public static String readFileContent(String path) throws Exception { return new String(Files.readAllBytes(Paths.get(path))); }",
|
24 |
+
"import java.nio.file.Files; import java.nio.file.Paths; public static void writeToFile(String path, String content) throws Exception { Files.write(Paths.get(path), content.getBytes()); }",
|
25 |
+
"import java.time.LocalTime; public static LocalTime getCurrentTime() { return LocalTime.now(); }",
|
26 |
+
"public static String toUpperCase(String str) { return str.toUpperCase(); }",
|
27 |
+
"public static String toLowerCase(String str) { return str.toLowerCase(); }",
|
28 |
+
"public static String reverseString(String str) { return new StringBuilder(str).reverse().toString(); }",
|
29 |
+
"public static int countListElements(List<?> list) { return list.size(); }",
|
30 |
+
"public static int findMax(List<Integer> list) { return Collections.max(list); }",
|
31 |
+
"public static int findMin(List<Integer> list) { return Collections.min(list); }",
|
32 |
+
"public static List<Integer> sortList(List<Integer> list) { Collections.sort(list); return list; }",
|
33 |
+
"public static List<?> mergeLists(List<?> list1, List<?> list2) { List<Object> mergedList = new ArrayList<>(list1); mergedList.addAll(list2); return mergedList; }",
|
34 |
+
"public static void removeElement(List<?> list, Object element) { list.remove(element); }",
|
35 |
+
"public static boolean isListEmpty(List<?> list) { return list.isEmpty(); }",
|
36 |
+
"public static int countCharOccurrences(String str, char ch) { return (int) str.chars().filter(c -> c == ch).count(); }",
|
37 |
+
"public static boolean containsSubstring(String str, String sub) { return str.contains(sub); }",
|
38 |
+
"public static String numberToString(int number) { return Integer.toString(number); }",
|
39 |
+
"public static int stringToNumber(String str) { return Integer.parseInt(str); }",
|
40 |
+
"public static boolean isNumeric(String str) { return str.matches(\"\\\\d+\"); }",
|
41 |
+
"public static int getElementIndex(List<?> list, Object element) { return list.indexOf(element); }",
|
42 |
+
"public static void clearList(List<?> list) { list.clear(); }",
|
43 |
+
"public static void reverseList(List<?> list) { Collections.reverse(list); }",
|
44 |
+
"public static List<?> removeDuplicates(List<?> list) { return new ArrayList<>(new HashSet<>(list)); }",
|
45 |
+
"public static boolean isInList(List<?> list, Object element) { return list.contains(element); }",
|
46 |
+
"public static Map<Object, Object> createDictionary() { return new HashMap<>(); }",
|
47 |
+
"public static void addToDictionary(Map<Object, Object> dict, Object key, Object value) { dict.put(key, value); }",
|
48 |
+
"public static void removeFromDictionary(Map<Object, Object> dict, Object key) { dict.remove(key); }",
|
49 |
+
"public static Set<Object> getDictionaryKeys(Map<Object, Object> dict) { return dict.keySet(); }",
|
50 |
+
"public static Collection<Object> getDictionaryValues(Map<Object, Object> dict) { return dict.values(); }",
|
51 |
+
"public static Map<Object, Object> mergeDictionaries(Map<Object, Object> dict1, Map<Object, Object> dict2) { Map<Object, Object> mergedDict = new HashMap<>(dict1); mergedDict.putAll(dict2); return mergedDict; }",
|
52 |
+
"public static boolean isDictionaryEmpty(Map<Object, Object> dict) { return dict.isEmpty(); }",
|
53 |
+
"public static Object getDictionaryValue(Map<Object, Object> dict, Object key) { return dict.get(key); }",
|
54 |
+
"public static boolean keyExistsInDictionary(Map<Object, Object> dict, Object key) { return dict.containsKey(key); }",
|
55 |
+
"public static void clearDictionary(Map<Object, Object> dict) { dict.clear(); }",
|
56 |
+
"import java.io.BufferedReader; import java.io.FileReader; public static int countFileLines(String path) throws Exception { return (int) new BufferedReader(new FileReader(path)).lines().count(); }",
|
57 |
+
"import java.nio.file.Files; import java.nio.file.Paths; public static void writeListToFile(String path, List<?> list) throws Exception { Files.write(Paths.get(path), list.toString().getBytes()); }",
|
58 |
+
"import java.nio.file.Files; import java.nio.file.Paths; public static List<String> readListFromFile(String path) throws Exception { return Files.readAllLines(Paths.get(path)); }",
|
59 |
+
"import java.io.BufferedReader; import java.io.FileReader; public static int countFileWords(String path) throws Exception { return new BufferedReader(new FileReader(path)).lines().mapToInt(line -> line.split(\"\\\\s+\").length).sum(); }",
|
60 |
+
"public static boolean isLeapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); }",
|
61 |
+
"import java.time.format.DateTimeFormatter; public static String formatTime(LocalTime time, String pattern) { return time.format(DateTimeFormatter.ofPattern(pattern)); }",
|
62 |
+
"import java.time.LocalDate; import java.time.temporal.ChronoUnit; public static long daysBetween(LocalDate date1, LocalDate date2) { return ChronoUnit.DAYS.between(date1, date2); }",
|
63 |
+
"import java.nio.file.Paths; public static String getCurrentWorkingDirectory() { return Paths.get(\"\").toAbsolutePath().toString(); }",
|
64 |
+
"import java.io.File; public static List<String> listFilesInDirectory(String path) { return Arrays.asList(new File(path).list()); }",
|
65 |
+
"import java.nio.file.Files; import java.nio.file.Paths; public static void createDirectory(String path) throws Exception { Files.createDirectory(Paths.get(path)); }",
|
66 |
+
"import java.nio.file.Files; import java.nio.file.Paths; public static void deleteDirectory(String path) throws Exception { Files.delete(Paths.get(path)); }",
|
67 |
+
"import java.nio.file.Files; import java.nio.file.Paths; public static boolean isFile(String path) { return Files.isRegularFile(Paths.get(path)); }",
|
68 |
+
"import java.nio.file.Files; import java.nio.file.Paths; public static boolean isDirectory(String path) { return Files.isDirectory(Paths.get(path)); }",
|
69 |
+
"import java.nio.file.Files; import java.nio.file.Paths; public static long getFileSize(String path) throws Exception { return Files.size(Paths.get(path)); }",
|
70 |
+
"import java.nio.file.Files; import java.nio.file.Paths; public static void renameFile(String oldPath, String newPath) throws Exception { Files.move(Paths.get(oldPath), Paths.get(newPath)); }",
|
71 |
+
"import java.nio.file.Files; import java.nio.file.Paths; public static void copyFile(String sourcePath, String destinationPath) throws Exception { Files.copy(Paths.get(sourcePath), Paths.get(destinationPath)); }",
|
72 |
+
"import java.nio.file.Files; import java.nio.file.Paths; public static void moveFile(String sourcePath, String destinationPath) throws Exception { Files.move(Paths.get(sourcePath), Paths.get(destinationPath)); }",
|
73 |
+
"import java.nio.file.Files; import java.nio.file.Paths; public static void deleteFile(String path) throws Exception { Files.delete(Paths.get(path)); }",
|
74 |
+
"public static String getEnvVariable(String name) { return System.getenv(name); }",
|
75 |
+
"public static void setEnvVariable(String name, String value) { System.setProperty(name, value); }",
|
76 |
+
"import java.awt.Desktop; import java.net.URI; public static void openWebLink(String url) throws Exception { Desktop.getDesktop().browse(new URI(url)); }",
|
77 |
+
"import java.net.HttpURLConnection; import java.net.URL; public static String sendGetRequest(String url) throws Exception { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod(\"GET\"); return new String(connection.getInputStream().readAllBytes()); }",
|
78 |
+
"import com.google.gson.JsonParser; public static Object parseJson(String json) { return JsonParser.parseString(json); }",
|
79 |
+
"import com.google.gson.Gson; import java.nio.file.Files; import java.nio.file.Paths; public static void writeJsonToFile(String path, Object obj) throws Exception { Files.write(Paths.get(path), new Gson().toJson(obj).getBytes()); }",
|
80 |
+
"import com.google.gson.Gson; import java.nio.file.Files; import java.nio.file.Paths; public static Object readJsonFromFile(String path) throws Exception { return new Gson().fromJson(new String(Files.readAllBytes(Paths.get(path))), Object.class); }",
|
81 |
+
"public static String listToString(List<?> list) { return list.toString(); }",
|
82 |
+
"public static List<String> stringToList(String str) { return Arrays.asList(str.split(\",\")); }",
|
83 |
+
"public static String joinWithComma(List<?> list) { return String.join(\",\", list.stream().map(Object::toString).toArray(String[]::new)); }",
|
84 |
+
"public static String joinWithNewline(List<?> list) { return String.join(\"\\n\", list.stream().map(Object::toString).toArray(String[]::new)); }",
|
85 |
+
"public static String[] splitBySpace(String str) { return str.split(\"\\\\s+\"); }",
|
86 |
+
"public static String[] splitByDelimiter(String str, String delimiter) { return str.split(delimiter); }",
|
87 |
+
"public static String[] splitIntoChars(String str) { return str.split(\"\"); }",
|
88 |
+
"public static String replaceInString(String str, String target, String replacement) { return str.replace(target, replacement); }",
|
89 |
+
"public static String removeSpaces(String str) { return str.replaceAll(\"\\\\s\", \"\"); }",
|
90 |
+
"public static String removePunctuation(String str) { return str.replaceAll(\"[^a-zA-Z0-9]\", \"\"); }",
|
91 |
+
"public static boolean isStringEmpty(String str) { return str.isEmpty(); }",
|
92 |
+
"public static boolean isPalindrome(String str) { return str.equals(new StringBuilder(str).reverse().toString()); }",
|
93 |
+
"import com.opencsv.CSVWriter; import java.io.FileWriter; public static void writeToCsv(String path, List<String[]> data) throws Exception { CSVWriter writer = new CSVWriter(new FileWriter(path)); writer.writeAll(data); writer.close(); }",
|
94 |
+
"import com.opencsv.CSVReader; import java.io.FileReader; public static List<String[]> readFromCsv(String path) throws Exception { CSVReader reader = new CSVReader(new FileReader(path)); return reader.readAll(); }",
|
95 |
+
"import com.opencsv.CSVReader; import java.io.FileReader; public static int countCsvLines(String path) throws Exception { return readFromCsv(path).size(); }",
|
96 |
+
"public static void shuffleList(List<?> list) { Collections.shuffle(list); }",
|
97 |
+
"public static Object getRandomElement(List<?> list) { return list.get(new Random().nextInt(list.size())); }",
|
98 |
+
"public static List<?> getRandomElements(List<?> list, int count) { Collections.shuffle(list); return list.subList(0, count); }",
|
99 |
+
"public static int rollDice() { return new Random().nextInt(6) + 1; }",
|
100 |
+
"public static String flipCoin() { return new Random().nextBoolean() ? \"Heads\" : \"Tails\"; }",
|
101 |
+
"import java.util.Random; public static String generateRandomPassword(int length) { String chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"; StringBuilder password = new StringBuilder(); for (int i = 0; i < length; i++) { password.append(chars.charAt(new Random().nextInt(chars.length()))); } return password.toString(); }",
|
102 |
+
"import java.util.Random; public static String generateRandomColor() { Random random = new Random(); return String.format(\"#%06x\", random.nextInt(0xFFFFFF + 1)); }",
|
103 |
+
"import java.util.UUID; public static String generateUniqueId() { return UUID.randomUUID().toString(); }",
|
104 |
+
"public class MyClass {}",
|
105 |
+
"MyClass myObject = new MyClass();",
|
106 |
+
"public class MyClass { public void myMethod() {} }",
|
107 |
+
"public class MyClass { public String myAttribute; }",
|
108 |
+
"public class ChildClass extends MyClass {}",
|
109 |
+
"public class ChildClass extends MyClass { @Override public void myMethod() {} }",
|
110 |
+
"public class MyClass { public static void myClassMethod() {} }",
|
111 |
+
"public class MyClass { public static void myStaticMethod() {} }",
|
112 |
+
"public static boolean isInstanceOf(Object obj, Class<?> clazz) { return clazz.isInstance(obj); }",
|
113 |
+
"public static Object getAttribute(Object obj, String attribute) throws Exception { return obj.getClass().getDeclaredField(attribute).get(obj); }",
|
114 |
+
"public static void setAttribute(Object obj, String attribute, Object value) throws Exception { obj.getClass().getDeclaredField(attribute).set(obj, value); }",
|
115 |
+
"public static void deleteAttribute(Object obj, String attribute) throws Exception { obj.getClass().getDeclaredField(attribute).set(obj, null); }"
|
116 |
+
"try { int result = 10 / 0; } catch (Exception e) { System.out.println(\"Exception caught\"); }",
|
117 |
+
"class CustomException extends Exception { public CustomException(String message) { super(message); } }",
|
118 |
+
"try { int result = 10 / 0; } catch (Exception e) { System.out.println(e.getMessage()); }",
|
119 |
+
"import java.util.logging.Logger; Logger logger = Logger.getLogger(MyClass.class.getName()); logger.severe(\"Error occurred\");",
|
120 |
+
"long startTime = System.currentTimeMillis();",
|
121 |
+
"long endTime = System.currentTimeMillis(); long elapsedTime = endTime - startTime;",
|
122 |
+
"for (int i = 0; i <= 100; i++) { System.out.print(\"\\rProgress: \" + i + \"%\"); Thread.sleep(50); }",
|
123 |
+
"Thread.sleep(1000);",
|
124 |
+
"Runnable r = () -> System.out.println(\"Lambda expression\"); r.run();",
|
125 |
+
"List<Integer> numbers = Arrays.asList(1, 2, 3); List<Integer> squares = numbers.stream().map(x -> x * x).collect(Collectors.toList());",
|
126 |
+
"List<Integer> numbers = Arrays.asList(1, 2, 3); List<Integer> evens = numbers.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());",
|
127 |
+
"import java.util.stream.Collectors; List<Integer> numbers = Arrays.asList(1, 2, 3); int sum = numbers.stream().reduce(0, Integer::sum);",
|
128 |
+
"List<Integer> squares = IntStream.range(0, 10).map(x -> x * x).boxed().collect(Collectors.toList());",
|
129 |
+
"Map<String, Integer> map = IntStream.range(0, 10).boxed().collect(Collectors.toMap(i -> \"key\" + i, i -> i));",
|
130 |
+
"Set<Integer> set = IntStream.range(0, 10).boxed().collect(Collectors.toSet());",
|
131 |
+
"Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3)); Set<Integer> set2 = new HashSet<>(Arrays.asList(2, 3, 4)); set1.retainAll(set2);",
|
132 |
+
"Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3)); Set<Integer> set2 = new HashSet<>(Arrays.asList(2, 3, 4)); set1.addAll(set2);",
|
133 |
+
"Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3)); Set<Integer> set2 = new HashSet<>(Arrays.asList(2, 3, 4)); set1.removeAll(set2);",
|
134 |
+
"List<Integer> list = Arrays.asList(1, null, 2, null); list.removeIf(Objects::isNull);",
|
135 |
+
"try (BufferedReader br = new BufferedReader(new FileReader(\"file.txt\"))) { br.readLine(); } catch (IOException e) { System.out.println(\"File cannot be opened\"); }",
|
136 |
+
"if (variable instanceof Integer) { System.out.println(\"Variable is an Integer\"); }",
|
137 |
+
"boolean bool = Boolean.parseBoolean(\"true\");",
|
138 |
+
"if (condition) { System.out.println(\"Condition is true\"); }",
|
139 |
+
"while (condition) { System.out.println(\"Looping\"); }",
|
140 |
+
"for (int i : list) { System.out.println(i); }",
|
141 |
+
"for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + \": \" + entry.getValue()); }",
|
142 |
+
"for (char c : str.toCharArray()) { System.out.println(c); }",
|
143 |
+
"for (int i = 0; i < 10; i++) { if (i == 5) break; System.out.println(i); }",
|
144 |
+
"for (int i = 0; i < 10; i++) { if (i == 5) continue; System.out.println(i); }",
|
145 |
+
"public void myFunction() { System.out.println(\"Function executed\"); }",
|
146 |
+
"public void myFunction(String param = \"default\") { System.out.println(param); }",
|
147 |
+
"public int[] returnMultipleValues() { return new int[]{1, 2}; }",
|
148 |
+
"public void myFunction(int... numbers) { for (int num : numbers) System.out.println(num); }",
|
149 |
+
"public void myFunction(Map<String, Object> kwargs) { System.out.println(kwargs); }",
|
150 |
+
"long startTime = System.nanoTime(); myFunction(); long endTime = System.nanoTime(); long duration = (endTime - startTime);",
|
151 |
+
"public static <T> Function<T, T> memoize(Function<T, T> function) { return new Function<T, T>() { private final Map<T, T> cache = new HashMap<>(); public T apply(T input) { return cache.computeIfAbsent(input, function); } }; }",
|
152 |
+
"public class MyGenerator implements Iterator<Integer> { private int current = 0; public boolean hasNext() { return current < 10; } public Integer next() { return current++; } }",
|
153 |
+
"public class MyGenerator { public Iterator<Integer> iterator() { return new Iterator<Integer>() { private int current = 0; public boolean hasNext() { return current < 10; } public Integer next() { return current++; } }; } }",
|
154 |
+
"MyGenerator generator = new MyGenerator(); while (generator.hasNext()) { System.out.println(generator.next()); }",
|
155 |
+
"for (int i = 0; i < list.size(); i++) { System.out.println(i + \": \" + list.get(i)); }",
|
156 |
+
"List<Integer> list1 = Arrays.asList(1, 2, 3); List<Integer> list2 = Arrays.asList(4, 5, 6); List<Integer> zipped = IntStream.range(0, Math.min(list1.size(), list2.size())).mapToObj(i -> list1.get(i) + list2.get(i)).collect(Collectors.toList());",
|
157 |
+
"List<String> keys = Arrays.asList(\"a\", \"b\"); List<Integer> values = Arrays.asList(1, 2); Map<String, Integer> map = IntStream.range(0, keys.size()).boxed().collect(Collectors.toMap(keys::get, values::get));",
|
158 |
+
"boolean areEqual = list1.equals(list2);",
|
159 |
+
"boolean areEqual = map1.equals(map2);",
|
160 |
+
"boolean areEqual = set1.equals(set2);",
|
161 |
+
"Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 2, 3));",
|
162 |
+
"set.clear();",
|
163 |
+
"boolean isEmpty = set.isEmpty();",
|
164 |
+
"set.add(4);",
|
165 |
+
"set.remove(3);",
|
166 |
+
"boolean contains = set.contains(2);",
|
167 |
+
"int size = set.size();",
|
168 |
+
"boolean hasIntersection = !Collections.disjoint(set1, set2);",
|
169 |
+
"boolean isSubset = new HashSet<>(list1).containsAll(list2);",
|
170 |
+
"boolean isSubstring = str.contains(sub);",
|
171 |
+
"char firstChar = str.charAt(0);",
|
172 |
+
"char lastChar = str.charAt(str.length() - 1);",
|
173 |
+
"boolean isTextFile = Files.probeContentType(Paths.get(\"file.txt\")).startsWith(\"text\");",
|
174 |
+
"boolean isImageFile = Files.probeContentType(Paths.get(\"file.jpg\")).startsWith(\"image\");",
|
175 |
+
"double rounded = Math.round(3.14159);",
|
176 |
+
"double ceil = Math.ceil(3.14159);",
|
177 |
+
"double floor = Math.floor(3.14159);",
|
178 |
+
"double formatted = Double.parseDouble(String.format(\"%.2f\", 3.14159));",
|
179 |
+
"String randomString = new Random().ints(48, 122).filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)).limit(10).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();",
|
180 |
+
"boolean pathExists = Files.exists(Paths.get(\"path\"));",
|
181 |
+
"Files.walk(Paths.get(\"path\")).forEach(System.out::println);",
|
182 |
+
"String extension = FilenameUtils.getExtension(\"file.txt\");",
|
183 |
+
"String fileName = FilenameUtils.getName(\"path/to/file.txt\");",
|
184 |
+
"String fullPath = Paths.get(\"path/to/file.txt\").toAbsolutePath().toString();",
|
185 |
+
"String version = System.getProperty(\"java.version\");",
|
186 |
+
"String os = System.getProperty(\"os.name\");",
|
187 |
+
"int cores = Runtime.getRuntime().availableProcessors();",
|
188 |
+
"long memory = Runtime.getRuntime().totalMemory();",
|
189 |
+
"File[] roots = File.listRoots(); for (File root : roots) { System.out.println(root.getUsableSpace()); }",
|
190 |
+
"String ip = InetAddress.getLocalHost().getHostAddress();",
|
191 |
+
"boolean isConnected = InetAddress.getByName(\"www.google.com\").isReachable(5000);",
|
192 |
+
"URL url = new URL(\"http://example.com/file.txt\"); Files.copy(url.openStream(), Paths.get(\"file.txt\"));",
|
193 |
+
"String response = new HttpPost(\"http://example.com/upload\").execute().returnContent().asString();",
|
194 |
+
"String response = new HttpPost(\"http://example.com\").execute().returnContent().asString();",
|
195 |
+
"String response = new HttpPost(\"http://example.com\").addParameter(\"key\", \"value\").execute().returnContent().asString();",
|
196 |
+
"String response = new HttpPost(\"http://example.com\").addHeader(\"key\", \"value\").execute().returnContent().asString();",
|
197 |
+
"Document doc = Jsoup.connect(\"http://example.com\").get();",
|
198 |
+
"String title = doc.title();",
|
199 |
+
"Elements links = doc.select(\"a[href]\");",
|
200 |
+
"Elements images = doc.select(\"img[src]\"); for (Element img : images) { URL imgUrl = new URL(img.attr(\"src\")); Files.copy(imgUrl.openStream(), Paths.get(imgUrl.getFile())); }",
|
201 |
+
"Map<String, Integer> wordCount = new HashMap<>(); for (String word : doc.text().split(\"\\\\s+\")) { wordCount.put(word, wordCount.getOrDefault(word, 0) + 1); }",
|
202 |
+
"String response = new HttpPost(\"http://example.com/login\").addParameter(\"username\", \"user\").addParameter(\"password\", \"pass\").execute().returnContent().asString();",
|
203 |
+
"String text = Jsoup.parse(html).text();",
|
204 |
+
"Pattern emailPattern = Pattern.compile(\"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,}\"); Matcher matcher = emailPattern.matcher(text); while (matcher.find()) { System.out.println(matcher.group()); }",
|
205 |
+
"Pattern phonePattern = Pattern.compile(\"\\\\+?\\\\d{10,13}\"); Matcher matcher = phonePattern.matcher(text); while (matcher.find()) { System.out.println(matcher.group()); }",
|
206 |
+
"Pattern numberPattern = Pattern.compile(\"\\\\d+\"); Matcher matcher = numberPattern.matcher(text); while (matcher.find()) { System.out.println(matcher.group()); }",
|
207 |
+
"String replaced = text.replaceAll(\"pattern\", \"replacement\");",
|
208 |
+
"boolean matches = text.matches(\"pattern\");",
|
209 |
+
"String stripped = Jsoup.parse(html).text();",
|
210 |
+
"String encoded = StringEscapeUtils.escapeHtml4(html);",
|
211 |
+
"String decoded = StringEscapeUtils.unescapeHtml4(html);",
|
212 |
+
"JFrame frame = new JFrame(\"Simple GUI\"); frame.setSize(300, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true);"
|
213 |
+
"JButton button = new JButton(\"Click Me\"); frame.add(button);",
|
214 |
+
"button.addActionListener(e -> System.out.println(\"Button clicked\"));",
|
215 |
+
"JOptionPane.showMessageDialog(frame, \"This is a message\");",
|
216 |
+
"JTextField textField = new JTextField(); String input = textField.getText();",
|
217 |
+
"frame.setTitle(\"New Title\");",
|
218 |
+
"frame.setSize(400, 300);",
|
219 |
+
"frame.setLocationRelativeTo(null);",
|
220 |
+
"JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu(\"File\"); menuBar.add(menu); frame.setJMenuBar(menuBar);",
|
221 |
+
"JComboBox<String> comboBox = new JComboBox<>(new String[]{\"Option 1\", \"Option 2\"}); frame.add(comboBox);",
|
222 |
+
"JRadioButton radioButton = new JRadioButton(\"Select Me\"); frame.add(radioButton);",
|
223 |
+
"JCheckBox checkBox = new JCheckBox(\"Check Me\"); frame.add(checkBox);",
|
224 |
+
"JLabel label = new JLabel(new ImageIcon(\"image.jpg\")); frame.add(label);",
|
225 |
+
"Clip clip = AudioSystem.getClip(); clip.open(AudioSystem.getAudioInputStream(new File(\"audio.wav\"))); clip.start();",
|
226 |
+
"Player player = Manager.createRealizedPlayer(new File(\"video.mp4\").toURI().toURL()); player.start();",
|
227 |
+
"long currentTime = player.getTimeNanoseconds();",
|
228 |
+
"Robot robot = new Robot(); BufferedImage screenShot = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));",
|
229 |
+
"ScreenRecorder screenRecorder = new ScreenRecorder(new ScreenRecorderParameters()); screenRecorder.start(); Thread.sleep(5000); screenRecorder.stop();",
|
230 |
+
"PointerInfo pointerInfo = MouseInfo.getPointerInfo(); Point point = pointerInfo.getLocation();",
|
231 |
+
"robot.keyPress(KeyEvent.VK_A); robot.keyRelease(KeyEvent.VK_A);",
|
232 |
+
"robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);",
|
233 |
+
"long timestamp = System.currentTimeMillis();",
|
234 |
+
"Date date = new Date(timestamp);",
|
235 |
+
"long timestamp = date.getTime();",
|
236 |
+
"int dayOfWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);",
|
237 |
+
"int daysInMonth = Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH);",
|
238 |
+
"Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_YEAR, 1); Date firstDay = cal.getTime();",
|
239 |
+
"Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_YEAR, cal.getActualMaximum(Calendar.DAY_OF_YEAR)); Date lastDay = cal.getTime();",
|
240 |
+
"Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, 1); Date firstDay = cal.getTime();",
|
241 |
+
"Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); Date lastDay = cal.getTime();",
|
242 |
+
"int dayOfWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK); boolean isWeekday = dayOfWeek != Calendar.SATURDAY && dayOfWeek != Calendar.SUNDAY;",
|
243 |
+
"int dayOfWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK); boolean isWeekend = dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY;",
|
244 |
+
"int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);",
|
245 |
+
"int minute = Calendar.getInstance().get(Calendar.MINUTE);",
|
246 |
+
"int second = Calendar.getInstance().get(Calendar.SECOND);",
|
247 |
+
"Thread.sleep(1000);",
|
248 |
+
"long millis = System.currentTimeMillis();",
|
249 |
+
"SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\"); String formattedDate = sdf.format(new Date());",
|
250 |
+
"SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\"); Date date = sdf.parse(\"2023-10-01 12:00:00\");",
|
251 |
+
"Thread thread = new Thread(() -> System.out.println(\"Thread running\")); thread.start();",
|
252 |
+
"Thread.sleep(1000);",
|
253 |
+
"ExecutorService executor = Executors.newFixedThreadPool(2); executor.submit(() -> System.out.println(\"Task 1\")); executor.submit(() -> System.out.println(\"Task 2\"));",
|
254 |
+
"String threadName = Thread.currentThread().getName();",
|
255 |
+
"thread.setDaemon(true);",
|
256 |
+
"ReentrantLock lock = new ReentrantLock(); lock.lock(); try { System.out.println(\"Locked\"); } finally { lock.unlock(); }",
|
257 |
+
"Process process = Runtime.getRuntime().exec(\"notepad.exe\");",
|
258 |
+
"long pid = process.pid();",
|
259 |
+
"boolean isAlive = process.isAlive();",
|
260 |
+
"ExecutorService executor = Executors.newFixedThreadPool(2); executor.submit(() -> System.out.println(\"Task 1\")); executor.submit(() -> System.out.println(\"Task 2\"));",
|
261 |
+
"BlockingQueue<String> queue = new LinkedBlockingQueue<>(); queue.put(\"Message\"); String message = queue.take();",
|
262 |
+
"PipedInputStream in = new PipedInputStream(); PipedOutputStream out = new PipedOutputStream(in); out.write(\"Message\".getBytes());",
|
263 |
+
"Thread.sleep(1000);",
|
264 |
+
"Process process = Runtime.getRuntime().exec(\"ls\"); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); }",
|
265 |
+
"int exitCode = process.waitFor();",
|
266 |
+
"boolean success = exitCode == 0;",
|
267 |
+
"String scriptPath = new File(\"\").getAbsolutePath();",
|
268 |
+
"String[] args = new String[]{\"arg1\", \"arg2\"};",
|
269 |
+
"ArgumentParser parser = ArgumentParser(); parser.addArgument(\"--arg\"); Namespace ns = parser.parseArgs(args);",
|
270 |
+
"parser.printHelp();",
|
271 |
+
"ModuleFinder finder = ModuleFinder.ofSystem(); Set<ModuleReference> modules = finder.findAll();",
|
272 |
+
"Process process = Runtime.getRuntime().exec(\"pip install package\");",
|
273 |
+
"Process process = Runtime.getRuntime().exec(\"pip uninstall package\");",
|
274 |
+
"String version = Package.getPackage(\"package\").getImplementationVersion();",
|
275 |
+
"Process process = Runtime.getRuntime().exec(\"python -m venv venv\");",
|
276 |
+
"Process process = Runtime.getRuntime().exec(\"pip list\");",
|
277 |
+
"Process process = Runtime.getRuntime().exec(\"pip install --upgrade package\");",
|
278 |
+
"Connection conn = DriverManager.getConnection(\"jdbc:sqlite:sample.db\");",
|
279 |
+
"Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(\"SELECT * FROM table\");",
|
280 |
+
"stmt.executeUpdate(\"INSERT INTO table (column) VALUES ('value')\");",
|
281 |
+
"stmt.executeUpdate(\"DELETE FROM table WHERE id = 1\");",
|
282 |
+
"stmt.executeUpdate(\"UPDATE table SET column = 'new_value' WHERE id = 1\");",
|
283 |
+
"while (rs.next()) { System.out.println(rs.getString(\"column\")); }",
|
284 |
+
"PreparedStatement pstmt = conn.prepareStatement(\"SELECT * FROM table WHERE id = ?\"); pstmt.setInt(1, 1); ResultSet rs = pstmt.executeQuery();",
|
285 |
+
"conn.close();",
|
286 |
+
"stmt.executeUpdate(\"CREATE TABLE table (id INT, name TEXT)\");",
|
287 |
+
"stmt.executeUpdate(\"DROP TABLE table\");",
|
288 |
+
"DatabaseMetaData meta = conn.getMetaData(); ResultSet rs = meta.getTables(null, null, \"table\", null); boolean exists = rs.next();",
|
289 |
+
"ResultSet rs = meta.getTables(null, null, \"%\", null); while (rs.next()) { System.out.println(rs.getString(\"TABLE_NAME\")); }",
|
290 |
+
"EntityManager em = Persistence.createEntityManagerFactory(\"pu\").createEntityManager(); em.getTransaction().begin(); em.persist(entity); em.getTransaction().commit();",
|
291 |
+
"EntityManager em = Persistence.createEntityManagerFactory(\"pu\").createEntityManager(); Query query = em.createQuery(\"SELECT e FROM Entity e\"); List<Entity> entities = query.getResultList();",
|
292 |
+
"EntityManager em = Persistence.createEntityManagerFactory(\"pu\").createEntityManager(); em.getTransaction().begin(); em.remove(entity); em.getTransaction().commit();",
|
293 |
+
"EntityManager em = Persistence.createEntityManagerFactory(\"pu\").createEntityManager(); em.getTransaction().begin(); em.merge(entity); em.getTransaction().commit();",
|
294 |
+
"@Entity public class Entity { @Id @GeneratedValue private Long id; private String name; }",
|
295 |
+
"@Entity public class ChildEntity extends ParentEntity { private String childField; }",
|
296 |
+
"@Id @GeneratedValue private Long id;",
|
297 |
+
"@Column(unique = true) private String uniqueField;",
|
298 |
+
"@Column(columnDefinition = \"varchar(255) default 'default_value'\") private String field;",
|
299 |
+
"CSVWriter writer = new CSVWriter(new FileWriter(\"data.csv\")); writer.writeAll(data); writer.close();",
|
300 |
+
"Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet(\"Sheet1\"); FileOutputStream fileOut = new FileOutputStream(\"workbook.xlsx\"); workbook.write(fileOut); fileOut.close();",
|
301 |
+
"ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(new File(\"data.json\"), data);",
|
302 |
+
"Workbook workbook = WorkbookFactory.create(new File(\"workbook.xlsx\")); Sheet sheet = workbook.getSheetAt(0);",
|
303 |
+
"Workbook workbook1 = WorkbookFactory.create(new File(\"workbook1.xlsx\")); Workbook workbook2 = WorkbookFactory.create(new File(\"workbook2.xlsx\")); Sheet sheet1 = workbook1.getSheetAt(0); Sheet sheet2 = workbook2.getSheetAt(0); Sheet newSheet = workbook1.createSheet(\"Merged\");",
|
304 |
+
"Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet(\"New Sheet\");",
|
305 |
+
"CellStyle style = workbook.createCellStyle(); style.cloneStyleFrom(cell.getCellStyle());",
|
306 |
+
"CellStyle style = workbook.createCellStyle(); style.setFillForegroundColor(IndexedColors.RED.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND);",
|
307 |
+
"Font font = workbook.createFont(); font.setBold(true); CellStyle style = workbook.createCellStyle(); style.setFont(font);",
|
308 |
+
"Row row = sheet.getRow(0); Cell cell = row.getCell(0); String cellValue = cell.getStringCellValue();",
|
309 |
+
"Row row = sheet.createRow(0); Cell cell = row.createCell(0); cell.setCellValue(\"New Value\");",
|
310 |
+
"BufferedImage img = ImageIO.read(new File(\"image.jpg\")); int width = img.getWidth(); int height = img.getHeight();",
|
311 |
+
"BufferedImage resizedImg = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g = resizedImg.createGraphics(); g.drawImage(img, 0, 0, newWidth, newHeight, null); g.dispose();"
|
312 |
+
|
313 |
+
|
314 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
315 |
|
316 |
]
|
317 |
|