Forrest99 commited on
Commit
4d96001
·
verified ·
1 Parent(s): 81c9a50

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +299 -331
app.py CHANGED
@@ -13,337 +13,305 @@ app.logger = logging.getLogger("CodeSearchAPI")
13
 
14
  # 预定义代码片段
15
  CODE_SNIPPETS = [
16
- "print('Hello, World!')",
17
- "def add(a, b): return a + b",
18
- "import random; def generate_random(): return random.randint(1, 100)",
19
- "def is_even(n): return n % 2 == 0",
20
- "def string_length(s): return len(s)",
21
- "from datetime import date; def get_current_date(): return date.today()",
22
- "import os; def file_exists(path): return os.path.exists(path)",
23
- "def read_file(path): return open(path, 'r').read()",
24
- "def write_file(path, content): open(path, 'w').write(content)",
25
- "from datetime import datetime; def get_current_time(): return datetime.now()",
26
- "def to_upper(s): return s.upper()",
27
- "def to_lower(s): return s.lower()",
28
- "def reverse_string(s): return s[::-1]",
29
- "def list_length(lst): return len(lst)",
30
- "def list_max(lst): return max(lst)",
31
- "def list_min(lst): return min(lst)",
32
- "def sort_list(lst): return sorted(lst)",
33
- "def merge_lists(lst1, lst2): return lst1 + lst2",
34
- "def remove_element(lst, element): lst.remove(element)",
35
- "def is_list_empty(lst): return len(lst) == 0",
36
- "def count_char(s, char): return s.count(char)",
37
- "def contains_substring(s, sub): return sub in s",
38
- "def int_to_str(n): return str(n)",
39
- "def str_to_int(s): return int(s)",
40
- "def is_numeric(s): return s.isdigit()",
41
- "def get_index(lst, element): return lst.index(element)",
42
- "def clear_list(lst): lst.clear()",
43
- "def reverse_list(lst): lst.reverse()",
44
- "def remove_duplicates(lst): return list(set(lst))",
45
- "def is_in_list(lst, value): return value in lst",
46
- "def create_dict(): return {}",
47
- "def add_to_dict(d, key, value): d[key] = value",
48
- "def delete_key(d, key): del d[key]",
49
- "def get_keys(d): return list(d.keys())",
50
- "def get_values(d): return list(d.values())",
51
- "def merge_dicts(d1, d2): return {**d1, **d2}",
52
- "def is_dict_empty(d): return len(d) == 0",
53
- "def get_value(d, key): return d[key]",
54
- "def key_exists(d, key): return key in d",
55
- "def clear_dict(d): d.clear()",
56
- "def count_lines(path): return len(open(path).readlines())",
57
- "def write_list_to_file(path, lst): open(path, 'w').write('\\n'.join(map(str, lst)))",
58
- "def read_list_from_file(path): return open(path, 'r').read().splitlines()",
59
- "def count_words(path): return len(open(path, 'r').read().split())",
60
- "def is_leap_year(year): return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)",
61
- "from datetime import datetime; def format_time(dt): return dt.strftime('%Y-%m-%d %H:%M:%S')",
62
- "from datetime import date; def days_between(d1, d2): return (d2 - d1).days",
63
- "import os; def get_current_dir(): return os.getcwd()",
64
- "import os; def list_files(path): return os.listdir(path)",
65
- "import os; def create_dir(path): os.mkdir(path)"
66
- "import os; def remove_dir(path): os.rmdir(path)",
67
- "import os; def is_file(path): return os.path.isfile(path)",
68
- "import os; def is_dir(path): return os.path.isdir(path)",
69
- "import os; def get_file_size(path): return os.path.getsize(path)",
70
- "import os; def rename_file(src, dst): os.rename(src, dst)",
71
- "import shutil; def copy_file(src, dst): shutil.copy(src, dst)",
72
- "import shutil; def move_file(src, dst): shutil.move(src, dst)",
73
- "import os; def delete_file(path): os.remove(path)",
74
- "import os; def get_env_var(key): return os.getenv(key)",
75
- "import os; def set_env_var(key, value): os.environ[key] = value",
76
- "import webbrowser; def open_url(url): webbrowser.open(url)",
77
- "import requests; def send_get_request(url): return requests.get(url).text",
78
- "import json; def parse_json(data): return json.loads(data)",
79
- "import json; def write_json(data, path): open(path, 'w').write(json.dumps(data))",
80
- "import json; def read_json(path): return json.loads(open(path, 'r').read())",
81
- "def list_to_string(lst): return ''.join(lst)",
82
- "def string_to_list(s): return list(s)",
83
- "def join_with_comma(lst): return ','.join(lst)",
84
- "def join_with_newline(lst): return '\\n'.join(lst)",
85
- "def split_by_space(s): return s.split()",
86
- "def split_by_char(s, char): return s.split(char)",
87
- "def split_to_chars(s): return list(s)",
88
- "def replace_string(s, old, new): return s.replace(old, new)",
89
- "def remove_spaces(s): return s.replace(' ', '')",
90
- "import string; def remove_punctuation(s): return s.translate(str.maketrans('', '', string.punctuation))",
91
- "def is_string_empty(s): return len(s) == 0",
92
- "def is_palindrome(s): return s == s[::-1]",
93
- "import csv; def write_csv(data, path): open(path, 'w', newline='').write('\\n'.join([','.join(map(str, row)) for row in data]))",
94
- "import csv; def read_csv(path): return [row for row in csv.reader(open(path, 'r'))]",
95
- "def count_csv_lines(path): return len(open(path).readlines())",
96
- "import random; def shuffle_list(lst): random.shuffle(lst)",
97
- "import random; def random_choice(lst): return random.choice(lst)",
98
- "import random; def random_sample(lst, k): return random.sample(lst, k)",
99
- "import random; def roll_dice(): return random.randint(1, 6)",
100
- "import random; def flip_coin(): return random.choice(['Heads', 'Tails'])",
101
- "import random; import string; def generate_password(length=8): return ''.join(random.choices(string.ascii_letters + string.digits, k=length))",
102
- "import random; def generate_color(): return '#%06x' % random.randint(0, 0xFFFFFF)",
103
- "import uuid; def generate_uuid(): return str(uuid.uuid4())",
104
- "class MyClass: pass",
105
- "def create_instance(): return MyClass()",
106
- "class MyClass: def my_method(self): pass",
107
- "class MyClass: def __init__(self): self.my_attr = None",
108
- "class ChildClass(MyClass): pass",
109
- "class ChildClass(MyClass): def my_method(self): pass",
110
- "class MyClass: @classmethod def my_class_method(cls): pass",
111
- "class MyClass: @staticmethod def my_static_method(): pass",
112
- "def check_type(obj): return type(obj)",
113
- "def get_attr(obj, attr): return getattr(obj, attr)",
114
- "def set_attr(obj, attr, value): setattr(obj, attr, value)",
115
- "def del_attr(obj, attr): delattr(obj, attr)",
116
- """try:
117
- x = 1 / 0
118
- except ZeroDivisionError:
119
- pass""",
120
- """class CustomError(Exception): pass
121
- def raise_custom_error(): raise CustomError('Error occurred')""",
122
- """try:
123
- x = 1 / 0
124
- except Exception as e: return str(e)""",
125
- """import logging; logging.basicConfig(filename='error.log', level=logging.ERROR); logging.error('Error occurred')""",
126
- """import time; def timer(): start = time.time(); return lambda: time.time() - start""",
127
- """import time; def run_time(): start = time.time(); return lambda: time.time() - start""",
128
- """import sys; def print_progress(progress): sys.stdout.write(f'\\rProgress: {progress}%'); sys.stdout.flush()""",
129
- """import time; def delay(seconds): time.sleep(seconds)""",
130
- "lambda x: x * 2",
131
- "map(lambda x: x * 2, [1, 2, 3])",
132
- "filter(lambda x: x > 2, [1, 2, 3])",
133
- "from functools import reduce; reduce(lambda x, y: x + y, [1, 2, 3])",
134
- "[x * 2 for x in [1, 2, 3]]",
135
- "{x: x * 2 for x in [1, 2, 3]}",
136
- "{x for x in [1, 2, 3]}",
137
- "set1 & set2",
138
- "set1 | set2",
139
- "set1 - set2",
140
- "[x for x in lst if x is not None]",
141
- """try:
142
- with open('file.txt', 'r') as f: pass
143
- except IOError: pass""",
144
- "type(var)",
145
- "bool(s)",
146
- "if condition: pass",
147
- "while condition: pass",
148
- "for item in lst: pass",
149
- "for key, value in d.items(): pass",
150
- "for char in s: pass",
151
- "for item in lst: if condition: break",
152
- "for item in lst: if condition: continue",
153
- "def my_func(): pass",
154
- "def my_func(param=1): pass",
155
- "def my_func(): return 1, 2",
156
- "def my_func(*args): pass",
157
- "def my_func(**kwargs): pass",
158
- """import time; def timer(func):
159
- def wrapper(*args, **kwargs):
160
- start = time.time()
161
- result = func(*args, **kwargs)
162
- print(f'Time: {time.time() - start}'); return result
163
- return wrapper""",
164
- """def decorator(func):
165
- def wrapper(*args, **kwargs): return func(*args, **kwargs)
166
- return wrapper""",
167
- """from functools import lru_cache; @lru_cache(maxsize=None)
168
- def my_func(): pass""",
169
- "def my_generator(): yield 1",
170
- "gen = my_generator(); next(gen)",
171
- "class MyIterator: def __iter__(self): return self; def __next__(self): pass",
172
- "it = iter([1, 2, 3]); next(it)",
173
- "for i, val in enumerate(lst): pass",
174
- "list(zip(lst1, lst2))",
175
- "dict(zip(keys, values))",
176
- "lst1 == lst2",
177
- "dict1 == dict2",
178
- "set1 == set2",
179
- "set(lst)",
180
- "set.clear()",
181
- "len(set) == 0",
182
- "set.add(item)",
183
- "set.remove(item)",
184
- "item in set",
185
- "len(set)",
186
- "set1 & set2",
187
- "set(lst1).issubset(lst2)",
188
- "sub in s",
189
- "s[0]",
190
- "s[-1]",
191
- "import mimetypes; mimetypes.guess_type(path)[0] == 'text/plain'",
192
- "import mimetypes; mimetypes.guess_type(path)[0].startswith('image/')",
193
- "round(num)",
194
- "import math; math.ceil(num)",
195
- "import math; math.floor(num)",
196
- "f'{num:.2f}'",
197
- "import random; import string; ''.join(random.choices(string.ascii_letters + string.digits, k=8))",
198
- "import os; os.path.exists(path)",
199
- "import os; for root, dirs, files in os.walk(path): pass",
200
- "import os; os.path.splitext(path)[1]",
201
- "import os; os.path.basename(path)",
202
- "import os; os.path.abspath(path)",
203
- "import platform; platform.python_version()",
204
- "import platform; platform.system()",
205
- "import multiprocessing; multiprocessing.cpu_count()",
206
- "import psutil; psutil.virtual_memory().total",
207
- "import psutil; psutil.disk_usage('/')",
208
- "import socket; socket.gethostbyname(socket.gethostname())",
209
- "import requests; try: requests.get('http://www.google.com'); return True; except: return False",
210
- "import requests; def download_file(url, path): with open(path, 'wb') as f: f.write(requests.get(url).content)",
211
- "def upload_file(path): with open(path, 'rb') as f: requests.post('http://example.com/upload', files={'file': f})",
212
- "import requests; requests.post(url, data={'key': 'value'})",
213
- "import requests; requests.get(url, params={'key': 'value'})",
214
- "import requests; requests.get(url, headers={'key': 'value'})",
215
- "from bs4 import BeautifulSoup; BeautifulSoup(html, 'html.parser')",
216
- "from bs4 import BeautifulSoup; soup.title.text",
217
- "from bs4 import BeautifulSoup; [a['href'] for a in soup.find_all('a')]",
218
- "from bs4 import BeautifulSoup; import requests; for img in soup.find_all('img'): requests.get(img['src']).content",
219
- "from collections import Counter; Counter(text.split())",
220
- "import requests; session = requests.Session(); session.post(login_url, data={'username': 'user', 'password': 'pass'})",
221
- "from bs4 import BeautifulSoup; soup.get_text()",
222
- "import re; re.findall(r'[\\w.-]+@[\\w.-]+', text)",
223
- "import re; re.findall(r'\\+?\\d[\\d -]{8,12}\\d', text)",
224
- "import re; re.findall(r'\\d+', text)",
225
- "import re; re.sub(pattern, repl, text)",
226
- "import re; re.match(pattern, text)",
227
- "from bs4 import BeautifulSoup; soup.get_text()",
228
- "import html; html.escape(text)",
229
- "import html; html.unescape(text)",
230
- "import tkinter as tk; root = tk.Tk(); root.mainloop()",
231
- "import tkinter as tk; def add_button(window, text): return tk.Button(window, text=text)",
232
- """def bind_click(button, func): button.config(command=func)""",
233
- """import tkinter.messagebox; def show_alert(message): tkinter.messagebox.showinfo('Info', message)""",
234
- """def get_entry_text(entry): return entry.get()""",
235
- "def set_title(window, title): window.title(title)",
236
- "def set_size(window, width, height): window.geometry(f'{width}x{height}')",
237
- """def center_window(window):
238
- window.update_idletasks()
239
- width = window.winfo_width()
240
- height = window.winfo_height()
241
- x = (window.winfo_screenwidth() // 2) - (width // 2)
242
- y = (window.winfo_screenheight() // 2) - (height // 2)
243
- window.geometry(f'{width}x{height}+{x}+{y}')""",
244
- """def create_menu(window): return tk.Menu(window)""",
245
- "def create_combobox(window): return ttk.Combobox(window)",
246
- "def create_radiobutton(window, text): return tk.Radiobutton(window, text=text)",
247
- "def create_checkbutton(window, text): return tk.Checkbutton(window, text=text)",
248
- """from PIL import ImageTk, Image; def show_image(window, path):
249
- img = Image.open(path)
250
- photo = ImageTk.PhotoImage(img)
251
- label = tk.Label(window, image=photo)
252
- label.image = photo
253
- return label""",
254
- "import pygame; def play_audio(path): pygame.mixer.init(); pygame.mixer.music.load(path); pygame.mixer.music.play()",
255
- "import cv2; def play_video(path): cap = cv2.VideoCapture(path); while cap.isOpened(): ret, frame = cap.read()",
256
- "def get_playback_time(): return pygame.mixer.music.get_pos()",
257
- "import pyautogui; def screenshot(): return pyautogui.screenshot()",
258
- "import pyautogui; import time; def record_screen(duration): return [pyautogui.screenshot() for _ in range(duration)]",
259
- "def get_mouse_pos(): return pyautogui.position()",
260
- "import pyautogui; def type_text(text): pyautogui.write(text)",
261
- "import pyautogui; def click_mouse(x, y): pyautogui.click(x, y)",
262
- "import time; def get_timestamp(): return int(time.time())",
263
- "import datetime; def timestamp_to_date(ts): return datetime.datetime.fromtimestamp(ts)",
264
- "import time; def date_to_timestamp(dt): return int(time.mktime(dt.timetuple()))",
265
- "def get_weekday(): return datetime.datetime.now().strftime('%A')",
266
- "import calendar; def get_month_days(): return calendar.monthrange(datetime.datetime.now().year, datetime.datetime.now().month)[1]",
267
- "def first_day_of_year(): return datetime.date(datetime.datetime.now().year, 1, 1)",
268
- "def last_day_of_year(): return datetime.date(datetime.datetime.now().year, 12, 31)",
269
- "def first_day_of_month(month): return datetime.date(datetime.datetime.now().year, month, 1)",
270
- "import calendar; def last_day_of_month(month): return datetime.date(datetime.datetime.now().year, month, calendar.monthrange(datetime.datetime.now().year, month)[1])",
271
- "def is_weekday(): return datetime.datetime.now().weekday() < 5",
272
- "def is_weekend(): return datetime.datetime.now().weekday() >= 5",
273
- "def current_hour(): return datetime.datetime.now().hour",
274
- "def current_minute(): return datetime.datetime.now().minute",
275
- "def current_second(): return datetime.datetime.now().second",
276
- "import time; def delay_1s(): time.sleep(1)",
277
- "import time; def millis_timestamp(): return int(time.time() * 1000)",
278
- "def format_time(dt, fmt='%Y-%m-%d %H:%M:%S'): return dt.strftime(fmt)",
279
- "from dateutil.parser import parse; def parse_time(s): return parse(s)",
280
- "import threading; def create_thread(target): return threading.Thread(target=target)",
281
- "import time; def thread_pause(seconds): time.sleep(seconds)",
282
- "def run_threads(*threads): [t.start() for t in threads]",
283
- "import threading; def current_thread_name(): return threading.current_thread().name",
284
- "def set_daemon(thread): thread.daemon = True",
285
- "import threading; lock = threading.Lock()",
286
- "import multiprocessing; def create_process(target): return multiprocessing.Process(target=target)",
287
- "import os; def get_pid(): return os.getpid()",
288
- "import psutil; def is_process_alive(pid): return psutil.pid_exists(pid)",
289
- "def run_processes(*procs): [p.start() for p in procs]",
290
- "from queue import Queue; q = Queue()",
291
- "from multiprocessing import Pipe; parent_conn, child_conn = Pipe()",
292
- "import os; def limit_cpu_usage(percent): os.system(f'cpulimit -p {os.getpid()} -l {percent}')",
293
- "import subprocess; def run_command(cmd): subprocess.run(cmd, shell=True)",
294
- "import subprocess; def get_command_output(cmd): return subprocess.check_output(cmd, shell=True).decode()",
295
- "def get_exit_code(cmd): return subprocess.call(cmd, shell=True)",
296
- "def is_success(code): return code == 0",
297
- "import os; def script_path(): return os.path.realpath(__file__)",
298
- "import sys; def get_cli_args(): return sys.argv[1:]",
299
- "import argparse; parser = argparse.ArgumentParser()",
300
- "parser.print_help()",
301
- "help('modules')",
302
- "import pip; def install_pkg(pkg): pip.main(['install', pkg])",
303
- "import pip; def uninstall_pkg(pkg): pip.main(['uninstall', pkg])",
304
- "import pkg_resources; def get_pkg_version(pkg): return pkg_resources.get_distribution(pkg).version",
305
- "import venv; def create_venv(path): venv.create(path)",
306
- "import pip; def list_pkgs(): return pip.get_installed_distributions()",
307
- "import pip; def upgrade_pkg(pkg): pip.main(['install', '--upgrade', pkg])",
308
- "import sqlite3; conn = sqlite3.connect(':memory:')",
309
- "def execute_query(conn, query): return conn.execute(query)",
310
- """def insert_record(conn, table, data): conn.execute(f'INSERT INTO {table} VALUES ({",".join("?"*len(data))})', data)""",
311
- "def delete_record(conn, table, condition): conn.execute(f'DELETE FROM {table} WHERE {condition}')",
312
- "def update_record(conn, table, set_clause, condition): conn.execute(f'UPDATE {table} SET {set_clause} WHERE {condition}')",
313
- "def fetch_all(conn, query): return conn.execute(query).fetchall()",
314
- "def safe_query(conn, query, params): return conn.execute(query, params)",
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