Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -14,818 +14,327 @@ app.logger = logging.getLogger("CodeSearchAPI")
|
|
| 14 |
# 预定义代码片段
|
| 15 |
CODE_SNIPPETS = [
|
| 16 |
|
| 17 |
-
"
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 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 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 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 |
-
|
| 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 |
-
}"
|
| 316 |
-
"
|
| 317 |
-
|
| 318 |
-
}"
|
| 319 |
-
"
|
| 320 |
-
|
| 321 |
-
}"
|
| 322 |
-
"
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
"
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
"
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
}
|
| 337 |
-
fmt.Println(set)
|
| 338 |
-
}""",
|
| 339 |
-
"func isEmptySet(s map[interface{}]struct{}) bool { return len(s) == 0 }", "func addToSet(s map[interface{}]struct{}, element interface{}) { s[element] = struct{}{} }", "func removeFromSet(s map[interface{}]struct{}, element interface{}) { delete(s, element) }", "func containsInSet(s map[interface{}]struct{}, element interface{}) bool { _, exists := s[element]; return exists }", "func getSetLength(s map[interface{}]struct{}) int { return len(s) }", "func hasIntersection(s1, s2 map[interface{}]struct{}) bool { for k := range s1 { if _, exists := s2[k]; exists { return true } } return false }", "func isSubset(s1, s2 map[interface{}]struct{}) bool { for k := range s1 { if _, exists := s2[k]; !exists { return false } } return true }", "func isSubstring(s, substr string) bool { return strings.Contains(s, substr) }", "func getFirstChar(s string) string { return string(s[0]) }", "func getLastChar(s string) string { return string(s[len(s)-1]) }", "func isTextFile(filename string) bool { return strings.HasSuffix(filename, \".txt\") }", "func isImageFile(filename string) bool { ext := strings.ToLower(filepath.Ext(filename)); return ext == \".jpg\" || ext == \".png\" || ext == \".gif\" }", "func roundNumber(num float64) float64 { return math.Round(num) }", "func ceilNumber(num float64) float64 { return math.Ceil(num) }", "func floorNumber(num float64) float64 { return math.Floor(num) }", "func formatDecimal(num float64, precision int) string { return fmt.Sprintf(\"%.*f\", precision, num) }", "func generateRandomString(length int) string { rand.Seed(time.Now().UnixNano()); b := make([]byte, length); rand.Read(b); return fmt.Sprintf(\"%x\", b)[:length] }", "func pathExists(path string) bool { _, err := os.Stat(path); return !os.IsNotExist(err) }", """func listFilesInDir(dir string) []string {
|
| 340 |
-
var files []string
|
| 341 |
-
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
|
| 342 |
-
if !info.IsDir() {
|
| 343 |
-
files = append(files, path)
|
| 344 |
-
}
|
| 345 |
-
return nil
|
| 346 |
-
})
|
| 347 |
-
return files
|
| 348 |
-
}""", "func getFileExtension(filename string) string { return filepath.Ext(filename) }", "func getFileName(filename string) string { return filepath.Base(filename) }", "func getFullPath(filename string) string { absPath, _ := filepath.Abs(filename); return absPath }", "func getPythonVersion() string { return runtime.Version() }", "func getPlatformInfo() string { return runtime.GOOS }", "func getCPUCores() int { return runtime.NumCPU() }", "func getMemorySize() uint64 { var mem runtime.MemStats; runtime.ReadMemStats(&mem); return mem.Sys }", """func getDiskUsage() string {
|
| 349 |
-
var stat syscall.Statfs_t
|
| 350 |
-
syscall.Statfs("/", &stat)
|
| 351 |
-
return fmt.Sprintf("Total: %d, Free: %d", stat.Blocks*uint64(stat.Bsize), stat.Bavail*uint64(stat.Bsize))
|
| 352 |
-
}""", "func getIPAddress() string { conn, _ := net.Dial(\"udp\", \"8.8.8.8:80\"); defer conn.Close(); return conn.LocalAddr().(*net.UDPAddr).IP.String() }", "func isConnected() bool { _, err := net.LookupIP(\"google.com\"); return err == nil }", """func downloadFile(url, filename string) error {
|
| 353 |
-
resp, err := http.Get(url)
|
| 354 |
-
if err != nil {
|
| 355 |
-
return err
|
| 356 |
-
}
|
| 357 |
-
defer resp.Body.Close()
|
| 358 |
-
out, err := os.Create(filename)
|
| 359 |
-
if err != nil {
|
| 360 |
-
return err
|
| 361 |
-
}
|
| 362 |
-
defer out.Close()
|
| 363 |
-
_, err = io.Copy(out, resp.Body)
|
| 364 |
-
return err
|
| 365 |
-
}""", """func uploadFile(filename string) string {
|
| 366 |
-
return fmt.Sprintf("File %s uploaded", filename)
|
| 367 |
-
}""", """func sendPostRequest(url string, data map[string]string) (string, error) {
|
| 368 |
-
jsonData, _ := json.Marshal(data)
|
| 369 |
-
resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
|
| 370 |
-
if err != nil {
|
| 371 |
-
return "", err
|
| 372 |
-
}
|
| 373 |
-
defer resp.Body.Close()
|
| 374 |
-
body, _ := io.ReadAll(resp.Body)
|
| 375 |
-
return string(body), nil
|
| 376 |
-
}""", """func sendRequestWithParams(url string, params map[string]string) (string, error) {
|
| 377 |
-
req, err := http.NewRequest("GET", url, nil)
|
| 378 |
-
if err != nil {
|
| 379 |
-
return "", err
|
| 380 |
-
}
|
| 381 |
-
q := req.URL.Query()
|
| 382 |
-
for key, value := range params {
|
| 383 |
-
q.Add(key, value)
|
| 384 |
-
}
|
| 385 |
-
req.URL.RawQuery = q.Encode()
|
| 386 |
-
resp, err := http.DefaultClient.Do(req)
|
| 387 |
-
if err != nil {
|
| 388 |
-
return "", err
|
| 389 |
-
}
|
| 390 |
-
defer resp.Body.Close()
|
| 391 |
-
body, _ := io.ReadAll(resp.Body)
|
| 392 |
-
return string(body), nil
|
| 393 |
-
}""", """func setRequestHeader(req *http.Request, headers map[string]string) {
|
| 394 |
-
for key, value := range headers {
|
| 395 |
-
req.Header.Set(key, value)
|
| 396 |
-
}
|
| 397 |
-
}""", """func parseHTML(htmlContent string) (*goquery.Document, error) {
|
| 398 |
-
return goquery.NewDocumentFromReader(strings.NewReader(htmlContent))
|
| 399 |
-
}""", """func extractTitle(doc *goquery.Document) string {
|
| 400 |
-
return doc.Find("title").Text()
|
| 401 |
-
}""", """func extractLinks(doc *goquery.Document) []string {
|
| 402 |
-
var links []string
|
| 403 |
-
doc.Find("a").Each(func(i int, s *goquery.Selection) {
|
| 404 |
-
href, exists := s.Attr("href")
|
| 405 |
-
if exists {
|
| 406 |
-
links = append(links, href)
|
| 407 |
-
}
|
| 408 |
-
})
|
| 409 |
-
return links
|
| 410 |
-
}""", """func downloadImagesFromPage(url string) error {
|
| 411 |
-
doc, err := goquery.NewDocument(url)
|
| 412 |
-
if err != nil {
|
| 413 |
-
return err
|
| 414 |
-
}
|
| 415 |
-
doc.Find("img").Each(func(i int, s *goquery.Selection) {
|
| 416 |
-
src, exists := s.Attr("src")
|
| 417 |
-
if exists {
|
| 418 |
-
downloadFile(src, fmt.Sprintf("image%d.jpg", i))
|
| 419 |
-
}
|
| 420 |
-
})
|
| 421 |
-
return nil
|
| 422 |
-
}""", """func countWordFrequency(text string) map[string]int {
|
| 423 |
-
words := strings.Fields(text)
|
| 424 |
-
freq := make(map[string]int)
|
| 425 |
-
for _, word := range words {
|
| 426 |
-
freq[word]++
|
| 427 |
-
}
|
| 428 |
-
return freq
|
| 429 |
-
}""", """func simulateLogin(url, username, password string) (string, error) {
|
| 430 |
-
form := url.Values{}
|
| 431 |
-
form.Add("username", username)
|
| 432 |
-
form.Add("password", password)
|
| 433 |
-
resp, err := http.PostForm(url, form)
|
| 434 |
-
if err != nil {
|
| 435 |
-
return "", err
|
| 436 |
-
}
|
| 437 |
-
defer resp.Body.Close()
|
| 438 |
-
body, _ := io.ReadAll(resp.Body)
|
| 439 |
-
return string(body), nil
|
| 440 |
-
}""", """func htmlToText(htmlContent string) string {
|
| 441 |
-
doc, _ := goquery.NewDocumentFromReader(strings.NewReader(htmlContent))
|
| 442 |
-
return doc.Text()
|
| 443 |
-
}""", """func extractEmails(text string) []string {
|
| 444 |
-
re := regexp.MustCompile(`[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}`)
|
| 445 |
-
return re.FindAllString(text, -1)
|
| 446 |
-
}""", """func extractPhoneNumbers(text string) []string {
|
| 447 |
-
re := regexp.MustCompile(`\d{3}-\d{3}-\d{4}`)
|
| 448 |
-
return re.FindAllString(text, -1)
|
| 449 |
-
}""", """func findAllNumbers(text string) []string {
|
| 450 |
-
re := regexp.MustCompile(`\d+`)
|
| 451 |
-
return re.FindAllString(text, -1)
|
| 452 |
-
}""", """func replaceWithRegex(text, pattern, replacement string) string {
|
| 453 |
-
re := regexp.MustCompile(pattern)
|
| 454 |
-
return re.ReplaceAllString(text, replacement)
|
| 455 |
-
}""", """func matchRegex(text, pattern string) bool {
|
| 456 |
-
re := regexp.MustCompile(pattern)
|
| 457 |
-
return re.MatchString(text)
|
| 458 |
-
}""", """func removeHTMLTags(htmlContent string) string {
|
| 459 |
-
re := regexp.MustCompile(`<[^>]*>`)
|
| 460 |
-
return re.ReplaceAllString(htmlContent, "")
|
| 461 |
-
}""", """func encodeHTMLEntities(htmlContent string) string {
|
| 462 |
-
return html.EscapeString(htmlContent)
|
| 463 |
-
}""", """func decodeHTMLEntities(htmlContent string) string {
|
| 464 |
-
return html.UnescapeString(htmlContent)
|
| 465 |
-
}""", """func createGUIWindow() {
|
| 466 |
-
window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
|
| 467 |
-
window.SetTitle("Simple GUI Window")
|
| 468 |
-
window.Connect("destroy", func() {
|
| 469 |
-
gtk.MainQuit()
|
| 470 |
-
})
|
| 471 |
-
window.ShowAll()
|
| 472 |
-
gtk.Main()
|
| 473 |
-
}""",
|
| 474 |
|
| 475 |
|
| 476 |
-
"func addButton(w fyne.Window) { w.SetContent(widget.NewButton(\"Button\", nil)) }",
|
| 477 |
-
"""func handleClick(b *widget.Button) {
|
| 478 |
-
b.OnTapped = func() { fmt.Println("Clicked") }
|
| 479 |
-
}""",
|
| 480 |
-
"""func showDialog(w fyne.Window) {
|
| 481 |
-
dialog.ShowInformation("Title", "Message", w)
|
| 482 |
-
}""",
|
| 483 |
-
"func getText(e *widget.Entry) string { return e.Text }",
|
| 484 |
-
"func setTitle(w fyne.Window) { w.SetTitle(\"Title\") }",
|
| 485 |
-
"func resizeWindow(w fyne.Window) { w.Resize(fyne.NewSize(800, 600)) }",
|
| 486 |
-
"func centerWindow(w fyne.Window) { w.CenterOnScreen() }",
|
| 487 |
-
"""func addMenu(w fyne.Window) {
|
| 488 |
-
menu := fyne.NewMainMenu(fyne.NewMenu("File"))
|
| 489 |
-
w.SetMainMenu(menu)
|
| 490 |
-
}""",
|
| 491 |
-
"func createSelect() *widget.Select { return widget.NewSelect([]string{\"a\", \"b\"}, func(s string) {}) }",
|
| 492 |
-
"func createRadio() *widget.RadioGroup { return widget.NewRadioGroup([]string{\"a\", \"b\"}, func(s string) {}) }",
|
| 493 |
-
"func createCheck() *widget.Check { return widget.NewCheck(\"Check\", func(b bool) {}) }",
|
| 494 |
-
"func showImage() *canvas.Image { return canvas.NewImageFromFile(\"image.png\") }",
|
| 495 |
-
"""func playAudio() {
|
| 496 |
-
exec.Command("afplay", "audio.mp3").Start()
|
| 497 |
-
}""",
|
| 498 |
-
"""func playVideo() {
|
| 499 |
-
exec.Command("vlc", "video.mp4").Start()
|
| 500 |
-
}""",
|
| 501 |
-
"func getTimestamp() int64 { return time.Now().Unix() }",
|
| 502 |
-
"""func timestampToDate(ts int64) string {
|
| 503 |
-
return time.Unix(ts, 0).Format("2006-01-02")
|
| 504 |
-
}""",
|
| 505 |
-
"""func dateToTimestamp(date string) int64 {
|
| 506 |
-
t, _ := time.Parse("2006-01-02", date)
|
| 507 |
-
return t.Unix()
|
| 508 |
-
}""",
|
| 509 |
-
"func getWeekday() string { return time.Now().Weekday().String() }",
|
| 510 |
-
"""func getMonthDays() int {
|
| 511 |
-
return time.Date(time.Now().Year(), time.Now().Month()+1, 0, 0, 0, 0, 0, time.UTC).Day()
|
| 512 |
-
}""",
|
| 513 |
-
"func firstDayOfYear() time.Time { return time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.UTC) }",
|
| 514 |
-
"func lastDayOfYear() time.Time { return time.Date(time.Now().Year(), 12, 31, 0, 0, 0, 0, time.UTC) }",
|
| 515 |
-
"""func firstDayOfMonth(year int, month time.Month) time.Time {
|
| 516 |
-
return time.Date(year, month, 1, 0, 0, 0, 0, time.UTC)
|
| 517 |
-
}""",
|
| 518 |
-
"""func lastDayOfMonth(year int, month time.Month) int {
|
| 519 |
-
return time.Date(year, month+1, 0, 0, 0, 0, 0, time.UTC).Day()
|
| 520 |
-
}""",
|
| 521 |
-
"func isWorkday() bool { wd := time.Now().Weekday(); return wd != time.Saturday && wd != time.Sunday }",
|
| 522 |
-
"func isWeekend() bool { wd := time.Now().Weekday(); return wd == time.Saturday || wd == time.Sunday }",
|
| 523 |
-
"func currentHour() int { return time.Now().Hour() }",
|
| 524 |
-
"func currentMinute() int { return time.Now().Minute() }",
|
| 525 |
-
"func currentSecond() int { return time.Now().Second() }",
|
| 526 |
-
"func sleep() { time.Sleep(time.Second) }",
|
| 527 |
-
"func millis() int64 { return time.Now().UnixNano() / int64(time.Millisecond) }",
|
| 528 |
-
"""func formatTime(t time.Time) string {
|
| 529 |
-
return t.Format("2006-01-02 15:04:05")
|
| 530 |
-
}""",
|
| 531 |
-
"""func parseTime(s string) time.Time {
|
| 532 |
-
t, _ := time.Parse("2006-01-02", s)
|
| 533 |
-
return t
|
| 534 |
-
}""",
|
| 535 |
-
"""func startThread() {
|
| 536 |
-
go func() { fmt.Println("Thread") }()
|
| 537 |
-
}""",
|
| 538 |
-
"func threadSleep() { time.Sleep(time.Second) }",
|
| 539 |
-
"""func multiThread() {
|
| 540 |
-
for i := 0; i < 3; i++ { go func(i int) {}(i) }
|
| 541 |
-
}""",
|
| 542 |
-
"func threadName() string { return runtime.Version() }",
|
| 543 |
-
"func setDaemon() { /* Not applicable in Go */ }",
|
| 544 |
-
"""func useMutex() {
|
| 545 |
-
var mu sync.Mutex
|
| 546 |
-
mu.Lock()
|
| 547 |
-
defer mu.Unlock()
|
| 548 |
-
}""",
|
| 549 |
-
"""func createProcess() {
|
| 550 |
-
cmd := exec.Command("ls")
|
| 551 |
-
cmd.Start()
|
| 552 |
-
}""",
|
| 553 |
-
"func getPID() int { return os.Getpid() }",
|
| 554 |
-
"""func isProcessAlive(pid int) bool {
|
| 555 |
-
err := syscall.Kill(pid, syscall.Signal(0))
|
| 556 |
-
return err == nil
|
| 557 |
-
}""",
|
| 558 |
-
"""func multiProcess() {
|
| 559 |
-
exec.Command("ls").Start()
|
| 560 |
-
}""",
|
| 561 |
-
"""func useQueue() {
|
| 562 |
-
ch := make(chan int)
|
| 563 |
-
go func() { ch <- 1 }()
|
| 564 |
-
<-ch
|
| 565 |
-
}""",
|
| 566 |
-
"""func usePipe() {
|
| 567 |
-
r, w, _ := os.Pipe()
|
| 568 |
-
w.Write([]byte("data"))
|
| 569 |
-
var b [4]byte
|
| 570 |
-
r.Read(b[:])
|
| 571 |
-
}""",
|
| 572 |
-
"func limitCPUUsage() { runtime.GOMAXPROCS(1) }",
|
| 573 |
-
"""func runShellCommand(cmd string) error {
|
| 574 |
-
return exec.Command("sh", "-c", cmd).Run()
|
| 575 |
-
}""",
|
| 576 |
-
"""func getCommandOutput(cmd string) (string, error) {
|
| 577 |
-
out, err := exec.Command("sh", "-c", cmd).Output()
|
| 578 |
-
return string(out), err
|
| 579 |
-
}""",
|
| 580 |
-
"""func getCommandStatus(cmd string) (int, error) {
|
| 581 |
-
err := exec.Command("sh", "-c", cmd).Run()
|
| 582 |
-
if err != nil {
|
| 583 |
-
if exitError, ok := err.(*exec.ExitError); ok {
|
| 584 |
-
return exitError.ExitCode(), nil
|
| 585 |
-
}
|
| 586 |
-
return -1, err
|
| 587 |
-
}
|
| 588 |
-
return 0, nil
|
| 589 |
-
}""",
|
| 590 |
-
"""func isCommandSuccess(cmd string) (bool, error) {
|
| 591 |
-
err := exec.Command("sh", "-c", cmd).Run()
|
| 592 |
-
return err == nil, err
|
| 593 |
-
}""",
|
| 594 |
-
"""func getCurrentScriptPath() string {
|
| 595 |
-
_, filename, _, _ := runtime.Caller(1)
|
| 596 |
-
return filepath.Dir(filename)
|
| 597 |
-
}""",
|
| 598 |
-
"""func getCommandLineArgs() []string {
|
| 599 |
-
return os.Args
|
| 600 |
-
}""",
|
| 601 |
-
"""func parseArgs() (string, int) {
|
| 602 |
-
var name string
|
| 603 |
-
var age int
|
| 604 |
-
flag.StringVar(&name, "name", "", "Name of the person")
|
| 605 |
-
flag.IntVar(&age, "age", 0, "Age of the person")
|
| 606 |
-
flag.Parse()
|
| 607 |
-
return name, age
|
| 608 |
-
}""",
|
| 609 |
-
"""func generateHelp() string {
|
| 610 |
-
flag.Usage()
|
| 611 |
-
return ""
|
| 612 |
-
}""",
|
| 613 |
-
"""func listPythonModules() {
|
| 614 |
-
exec.Command("python", "-c", "help('modules')").Run()
|
| 615 |
-
}""",
|
| 616 |
-
"""func installPythonPackage(pkg string) error {
|
| 617 |
-
return exec.Command("pip", "install", pkg).Run()
|
| 618 |
-
}""",
|
| 619 |
-
"""func uninstallPythonPackage(pkg string) error {
|
| 620 |
-
return exec.Command("pip", "uninstall", "-y", pkg).Run()
|
| 621 |
-
}""",
|
| 622 |
-
"""func getPackageVersion(pkg string) (string, error) {
|
| 623 |
-
out, err := exec.Command("pip", "show", pkg).Output()
|
| 624 |
-
if err != nil {
|
| 625 |
-
return "", err
|
| 626 |
-
}
|
| 627 |
-
return string(out), nil
|
| 628 |
-
}""",
|
| 629 |
-
"""func useVirtualEnv(envPath string) error {
|
| 630 |
-
return exec.Command("source", filepath.Join(envPath, "bin", "activate")).Run()
|
| 631 |
-
}""",
|
| 632 |
-
"""func listInstalledPackages() (string, error) {
|
| 633 |
-
out, err := exec.Command("pip", "list").Output()
|
| 634 |
-
return string(out), err
|
| 635 |
-
}""",
|
| 636 |
-
"""func upgradePythonPackage(pkg string) error {
|
| 637 |
-
return exec.Command("pip", "install", "--upgrade", pkg).Run()
|
| 638 |
-
}""",
|
| 639 |
-
"""func connectLocalDB(dbName string) (*sql.DB, error) {
|
| 640 |
-
return sql.Open("sqlite3", dbName)
|
| 641 |
-
}""",
|
| 642 |
-
"""func executeSQLQuery(db *sql.DB, query string) (*sql.Rows, error) {
|
| 643 |
-
return db.Query(query)
|
| 644 |
-
}""",
|
| 645 |
-
"""func insertRecord(db *sql.DB, query string, args ...interface{}) (sql.Result, error) {
|
| 646 |
-
return db.Exec(query, args...)
|
| 647 |
-
}""",
|
| 648 |
-
"""func deleteRecord(db *sql.DB, query string, args ...interface{}) (sql.Result, error) {
|
| 649 |
-
return db.Exec(query, args...)
|
| 650 |
-
}""",
|
| 651 |
-
"""func updateRecord(db *sql.DB, query string, args ...interface{}) (sql.Result, error) {
|
| 652 |
-
return db.Exec(query, args...)
|
| 653 |
-
}""",
|
| 654 |
-
"""func queryMultipleRecords(db *sql.DB, query string, args ...interface{}) (*sql.Rows, error) {
|
| 655 |
-
return db.Query(query, args...)
|
| 656 |
-
}""",
|
| 657 |
-
"""func useParameterizedQuery(db *sql.DB, query string, args ...interface{}) (*sql.Rows, error) {
|
| 658 |
-
return db.Query(query, args...)
|
| 659 |
-
}""",
|
| 660 |
-
"""func closeDBConnection(db *sql.DB) error {
|
| 661 |
-
return db.Close()
|
| 662 |
-
}""",
|
| 663 |
-
"""func createTable(db *sql.DB, query string) (sql.Result, error) {
|
| 664 |
-
return db.Exec(query)
|
| 665 |
-
}""",
|
| 666 |
-
"""func dropTable(db *sql.DB, query string) (sql.Result, error) {
|
| 667 |
-
return db.Exec(query)
|
| 668 |
-
}""",
|
| 669 |
-
"""func tableExists(db *sql.DB, tableName string) (bool, error) {
|
| 670 |
-
var exists bool
|
| 671 |
-
err := db.QueryRow("SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type='table' AND name=?)", tableName).Scan(&exists)
|
| 672 |
-
return exists, err
|
| 673 |
-
}""",
|
| 674 |
-
"""func listAllTables(db *sql.DB) ([]string, error) {
|
| 675 |
-
rows, err := db.Query("SELECT name FROM sqlite_master WHERE type='table'")
|
| 676 |
-
if err != nil {
|
| 677 |
-
return nil, err
|
| 678 |
-
}
|
| 679 |
-
defer rows.Close()
|
| 680 |
-
var tables []string
|
| 681 |
-
for rows.Next() {
|
| 682 |
-
var table string
|
| 683 |
-
if err := rows.Scan(&table); err != nil {
|
| 684 |
-
return nil, err
|
| 685 |
-
}
|
| 686 |
-
tables = append(tables, table)
|
| 687 |
-
}
|
| 688 |
-
return tables, nil
|
| 689 |
-
}""",
|
| 690 |
-
"""func exportToCSV(data [][]string, filename string) error {
|
| 691 |
-
file, err := os.Create(filename)
|
| 692 |
-
if err != nil {
|
| 693 |
-
return err
|
| 694 |
-
}
|
| 695 |
-
defer file.Close()
|
| 696 |
-
writer := csv.NewWriter(file)
|
| 697 |
-
return writer.WriteAll(data)
|
| 698 |
-
}""",
|
| 699 |
-
"""func exportToExcel(data [][]string, filename string) error {
|
| 700 |
-
file := excelize.NewFile()
|
| 701 |
-
for i, row := range data {
|
| 702 |
-
for j, cell := range row {
|
| 703 |
-
file.SetCellValue("Sheet1", fmt.Sprintf("%c%d", 'A'+j, i+1), cell)
|
| 704 |
-
}
|
| 705 |
-
}
|
| 706 |
-
return file.SaveAs(filename)
|
| 707 |
-
}""",
|
| 708 |
-
"""func exportToJSON(data interface{}, filename string) error {
|
| 709 |
-
file, err := os.Create(filename)
|
| 710 |
-
if err != nil {
|
| 711 |
-
return err
|
| 712 |
-
}
|
| 713 |
-
defer file.Close()
|
| 714 |
-
encoder := json.NewEncoder(file)
|
| 715 |
-
return encoder.Encode(data)
|
| 716 |
-
}""",
|
| 717 |
-
"""func readExcel(filename string) ([][]string, error) {
|
| 718 |
-
file, err := excelize.OpenFile(filename)
|
| 719 |
-
if err != nil {
|
| 720 |
-
return nil, err
|
| 721 |
-
}
|
| 722 |
-
rows, err := file.GetRows("Sheet1")
|
| 723 |
-
return rows, err
|
| 724 |
-
}""",
|
| 725 |
-
"""func mergeExcelFiles(files []string, output string) error {
|
| 726 |
-
merged := excelize.NewFile()
|
| 727 |
-
for _, file := range files {
|
| 728 |
-
f, err := excelize.OpenFile(file)
|
| 729 |
-
if err != nil {
|
| 730 |
-
return err
|
| 731 |
-
}
|
| 732 |
-
rows, err := f.GetRows("Sheet1")
|
| 733 |
-
if err != nil {
|
| 734 |
-
return err
|
| 735 |
-
}
|
| 736 |
-
for i, row := range rows {
|
| 737 |
-
for j, cell := range row {
|
| 738 |
-
merged.SetCellValue("Sheet1", fmt.Sprintf("%c%d", 'A'+j, i+1), cell)
|
| 739 |
-
}
|
| 740 |
-
}
|
| 741 |
-
}
|
| 742 |
-
return merged.SaveAs(output)
|
| 743 |
-
}""",
|
| 744 |
-
"""func addSheetToExcel(filename, sheetName string) error {
|
| 745 |
-
file, err := excelize.OpenFile(filename)
|
| 746 |
-
if err != nil {
|
| 747 |
-
return err
|
| 748 |
-
}
|
| 749 |
-
file.NewSheet(sheetName)
|
| 750 |
-
return file.Save()
|
| 751 |
-
}""",
|
| 752 |
-
"""func copyExcelStyle(src, dst string) error {
|
| 753 |
-
srcFile, err := excelize.OpenFile(src)
|
| 754 |
-
if err != nil {
|
| 755 |
-
return err
|
| 756 |
-
}
|
| 757 |
-
dstFile, err := excelize.OpenFile(dst)
|
| 758 |
-
if err != nil {
|
| 759 |
-
return err
|
| 760 |
-
}
|
| 761 |
-
styleID, err := srcFile.GetCellStyle("Sheet1", "A1")
|
| 762 |
-
if err != nil {
|
| 763 |
-
return err
|
| 764 |
-
}
|
| 765 |
-
dstFile.SetCellStyle("Sheet1", "A1", "A1", styleID)
|
| 766 |
-
return dstFile.Save()
|
| 767 |
-
}""",
|
| 768 |
-
"""func setExcelCellColor(filename, cell, color string) error {
|
| 769 |
-
file, err := excelize.OpenFile(filename)
|
| 770 |
-
if err != nil {
|
| 771 |
-
return err
|
| 772 |
-
}
|
| 773 |
-
styleID, err := file.NewStyle(&excelize.Style{Fill: excelize.Fill{Type: "pattern", Color: []string{color}, Pattern: 1}})
|
| 774 |
-
if err != nil {
|
| 775 |
-
return err
|
| 776 |
-
}
|
| 777 |
-
file.SetCellStyle("Sheet1", cell, cell, styleID)
|
| 778 |
-
return file.Save()
|
| 779 |
-
}""",
|
| 780 |
-
"""func setExcelFontStyle(filename, cell, fontName string, fontSize int) error {
|
| 781 |
-
file, err := excelize.OpenFile(filename)
|
| 782 |
-
if err != nil {
|
| 783 |
-
return err
|
| 784 |
-
}
|
| 785 |
-
styleID, err := file.NewStyle(&excelize.Style{Font: &excelize.Font{Family: fontName, Size: fontSize}})
|
| 786 |
-
if err != nil {
|
| 787 |
-
return err
|
| 788 |
-
}
|
| 789 |
-
file.SetCellStyle("Sheet1", cell, cell, styleID)
|
| 790 |
-
return file.Save()
|
| 791 |
-
}""",
|
| 792 |
-
"""func readExcelCell(filename, cell string) (string, error) {
|
| 793 |
-
file, err := excelize.OpenFile(filename)
|
| 794 |
-
if err != nil {
|
| 795 |
-
return "", err
|
| 796 |
-
}
|
| 797 |
-
return file.GetCellValue("Sheet1", cell)
|
| 798 |
-
}""",
|
| 799 |
-
"""func writeExcelCell(filename, cell, value string) error {
|
| 800 |
-
file, err := excelize.OpenFile(filename)
|
| 801 |
-
if err != nil {
|
| 802 |
-
return err
|
| 803 |
-
}
|
| 804 |
-
file.SetCellValue("Sheet1", cell, value)
|
| 805 |
-
return file.Save()
|
| 806 |
-
}""",
|
| 807 |
-
"""func getImageDimensions(filename string) (int, int, error) {
|
| 808 |
-
file, err := os.Open(filename)
|
| 809 |
-
if err != nil {
|
| 810 |
-
return 0, 0, err
|
| 811 |
-
}
|
| 812 |
-
defer file.Close()
|
| 813 |
-
img, _, err := image.DecodeConfig(file)
|
| 814 |
-
return img.Width, img.Height, err
|
| 815 |
-
}""",
|
| 816 |
-
"""func resizeImage(filename string, width, height int) error {
|
| 817 |
-
file, err := os.Open(filename)
|
| 818 |
-
if err != nil {
|
| 819 |
-
return err
|
| 820 |
-
}
|
| 821 |
-
defer file.Close()
|
| 822 |
-
img, _, err := image.Decode(file)
|
| 823 |
-
if err != nil {
|
| 824 |
-
return err
|
| 825 |
-
}
|
| 826 |
-
resized := imaging.Resize(img, width, height, imaging.Lanczos)
|
| 827 |
-
return imaging.Save(resized, filename)
|
| 828 |
-
}"""
|
| 829 |
|
| 830 |
|
| 831 |
|
|
|
|
| 14 |
# 预定义代码片段
|
| 15 |
CODE_SNIPPETS = [
|
| 16 |
|
| 17 |
+
"console.log('Hello, World!')",
|
| 18 |
+
"const sum = (a, b) => a + b",
|
| 19 |
+
"const randomNum = Math.random()",
|
| 20 |
+
"const isEven = num => num % 2 === 0",
|
| 21 |
+
"const strLength = str => str.length",
|
| 22 |
+
"const currentDate = new Date().toLocaleDateString()",
|
| 23 |
+
"const fs = require('fs'); const fileExists = path => fs.existsSync(path)",
|
| 24 |
+
"const readFile = path => fs.readFileSync(path, 'utf8')",
|
| 25 |
+
"const writeFile = (path, content) => fs.writeFileSync(path, content)",
|
| 26 |
+
"const currentTime = new Date().toLocaleTimeString()",
|
| 27 |
+
"const toUpperCase = str => str.toUpperCase()",
|
| 28 |
+
"const toLowerCase = str => str.toLowerCase()",
|
| 29 |
+
"const reverseStr = str => str.split('').reverse().join('')",
|
| 30 |
+
"const countElements = list => list.length",
|
| 31 |
+
"const maxInList = list => Math.max(...list)",
|
| 32 |
+
"const minInList = list => Math.min(...list)",
|
| 33 |
+
"const sortList = list => list.sort()",
|
| 34 |
+
"const mergeLists = (list1, list2) => list1.concat(list2)",
|
| 35 |
+
"const removeElement = (list, element) => list.filter(e => e !== element)",
|
| 36 |
+
"const isListEmpty = list => list.length === 0",
|
| 37 |
+
"const countChar = (str, char) => str.split(char).length - 1",
|
| 38 |
+
"const containsSubstring = (str, substring) => str.includes(substring)",
|
| 39 |
+
"const numToString = num => num.toString()",
|
| 40 |
+
"const strToNum = str => Number(str)",
|
| 41 |
+
"const isNumeric = str => !isNaN(str)",
|
| 42 |
+
"const getIndex = (list, element) => list.indexOf(element)",
|
| 43 |
+
"const clearList = list => list.length = 0",
|
| 44 |
+
"const reverseList = list => list.reverse()",
|
| 45 |
+
"const removeDuplicates = list => [...new Set(list)]",
|
| 46 |
+
"const isInList = (list, value) => list.includes(value)",
|
| 47 |
+
"const createDict = () => ({})",
|
| 48 |
+
"const addToDict = (dict, key, value) => dict[key] = value",
|
| 49 |
+
"const removeKey = (dict, key) => delete dict[key]",
|
| 50 |
+
"const getDictKeys = dict => Object.keys(dict)",
|
| 51 |
+
"const getDictValues = dict => Object.values(dict)",
|
| 52 |
+
"const mergeDicts = (dict1, dict2) => ({ ...dict1, ...dict2 })",
|
| 53 |
+
"const isDictEmpty = dict => Object.keys(dict).length === 0",
|
| 54 |
+
"const getDictValue = (dict, key) => dict[key]",
|
| 55 |
+
"const keyExists = (dict, key) => key in dict",
|
| 56 |
+
"const clearDict = dict => Object.keys(dict).forEach(key => delete dict[key])",
|
| 57 |
+
"const countFileLines = path => fs.readFileSync(path, 'utf8').split('\n').length",
|
| 58 |
+
"const writeListToFile = (path, list) => fs.writeFileSync(path, list.join('\n'))",
|
| 59 |
+
"const readListFromFile = path => fs.readFileSync(path, 'utf8').split('\n')",
|
| 60 |
+
"const countFileWords = path => fs.readFileSync(path, 'utf8').split(/\s+/).length",
|
| 61 |
+
"const isLeapYear = year => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0",
|
| 62 |
+
"const formatTime = (date, format) => date.toLocaleTimeString('en-US', format)",
|
| 63 |
+
"const daysBetween = (date1, date2) => Math.abs(date1 - date2) / (1000 * 60 * 60 * 24)",
|
| 64 |
+
"const currentDir = process.cwd()",
|
| 65 |
+
"const listFiles = path => fs.readdirSync(path)",
|
| 66 |
+
"const createDir = path => fs.mkdirSync(path)",
|
| 67 |
+
"const removeDir = path => fs.rmdirSync(path)",
|
| 68 |
+
"const isFile = path => fs.statSync(path).isFile()",
|
| 69 |
+
"const isDirectory = path => fs.statSync(path).isDirectory()",
|
| 70 |
+
"const getFileSize = path => fs.statSync(path).size",
|
| 71 |
+
"const renameFile = (oldPath, newPath) => fs.renameSync(oldPath, newPath)",
|
| 72 |
+
"const copyFile = (src, dest) => fs.copyFileSync(src, dest)",
|
| 73 |
+
"const moveFile = (src, dest) => fs.renameSync(src, dest)",
|
| 74 |
+
"const deleteFile = path => fs.unlinkSync(path)",
|
| 75 |
+
"const getEnvVar = key => process.env[key]",
|
| 76 |
+
"const setEnvVar = (key, value) => process.env[key] = value",
|
| 77 |
+
"const openLink = url => require('open')(url)",
|
| 78 |
+
"const sendGetRequest = async url => await (await fetch(url)).text()",
|
| 79 |
+
"const parseJSON = json => JSON.parse(json)",
|
| 80 |
+
"const writeJSON = (path, data) => fs.writeFileSync(path, JSON.stringify(data))",
|
| 81 |
+
"const readJSON = path => JSON.parse(fs.readFileSync(path, 'utf8'))",
|
| 82 |
+
"const listToString = list => list.join('')",
|
| 83 |
+
"const stringToList = str => str.split('')",
|
| 84 |
+
"const joinWithComma = list => list.join(',')",
|
| 85 |
+
"const joinWithNewline = list => list.join('\n')",
|
| 86 |
+
"const splitBySpace = str => str.split(' ')",
|
| 87 |
+
"const splitByChar = (str, char) => str.split(char)",
|
| 88 |
+
"const splitToChars = str => str.split('')",
|
| 89 |
+
"const replaceInStr = (str, old, newStr) => str.replace(old, newStr)",
|
| 90 |
+
"const removeSpaces = str => str.replace(/\s+/g, '')",
|
| 91 |
+
"const removePunctuation = str => str.replace(/[^\w\s]/g, '')",
|
| 92 |
+
"const isStrEmpty = str => str.length === 0",
|
| 93 |
+
"const isPalindrome = str => str === str.split('').reverse().join('')",
|
| 94 |
+
"const writeCSV = (path, data) => fs.writeFileSync(path, data.map(row => row.join(',')).join('\n'))",
|
| 95 |
+
"const readCSV = path => fs.readFileSync(path, 'utf8').split('\n').map(row => row.split(','))",
|
| 96 |
+
"const countCSVLines = path => fs.readFileSync(path, 'utf8').split('\n').length",
|
| 97 |
+
"const shuffleList = list => list.sort(() => Math.random() - 0.5)",
|
| 98 |
+
"const randomElement = list => list[Math.floor(Math.random() * list.length)]",
|
| 99 |
+
"const randomElements = (list, count) => list.sort(() => Math.random() - 0.5).slice(0, count)",
|
| 100 |
+
"const rollDice = () => Math.floor(Math.random() * 6) + 1",
|
| 101 |
+
"const flipCoin = () => Math.random() < 0.5 ? 'Heads' : 'Tails'",
|
| 102 |
+
"const randomPassword = length => Array.from({ length }, () => Math.random().toString(36).charAt(2)).join('')",
|
| 103 |
+
"const randomColor = () => `#${Math.floor(Math.random() * 16777215).toString(16)}`",
|
| 104 |
+
"const uniqueID = () => Math.random().toString(36).substring(2) + Date.now().toString(36)",
|
| 105 |
+
"""class MyClass {
|
| 106 |
+
constructor() {}
|
| 107 |
+
}""",
|
| 108 |
+
"const myInstance = new MyClass()",
|
| 109 |
+
"""class MyClass {
|
| 110 |
+
myMethod() {}
|
| 111 |
+
}""",
|
| 112 |
+
"""class MyClass {
|
| 113 |
+
constructor() {
|
| 114 |
+
this.myProp = 'value'
|
| 115 |
+
}
|
| 116 |
+
}""",
|
| 117 |
+
"""class ChildClass extends MyClass {
|
| 118 |
+
constructor() {
|
| 119 |
+
super()
|
| 120 |
+
}
|
| 121 |
+
}""",
|
| 122 |
+
"""class ChildClass extends MyClass {
|
| 123 |
+
myMethod() {
|
| 124 |
+
super.myMethod()
|
| 125 |
+
}
|
| 126 |
+
}""",
|
| 127 |
+
"const instance = new MyClass(); instance.myMethod()",
|
| 128 |
+
"""class MyClass {
|
| 129 |
+
static myStaticMethod() {}
|
| 130 |
+
}""",
|
| 131 |
+
"const typeOf = obj => typeof obj",
|
| 132 |
+
"const getProp = (obj, prop) => obj[prop]",
|
| 133 |
+
"const setProp = (obj, prop, value) => obj[prop] = value",
|
| 134 |
+
"const deleteProp = (obj, prop) => delete obj[prop]",
|
| 135 |
+
已思考 4 秒
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
"try{foo();}catch(e){}",
|
| 139 |
+
"throw new Error('CustomError')",
|
| 140 |
+
"""try{foo();}catch(e){const info=e.message;}""",
|
| 141 |
+
"console.error(err)",
|
| 142 |
+
"const timer={start(){this.s=Date.now()},stop(){return Date.now()-this.s}}",
|
| 143 |
+
"const runtime=(s)=>Date.now()-s",
|
| 144 |
+
"""const progress=(i,n)=>process.stdout.write(Math.floor(i/n*100)+'%\r')""",
|
| 145 |
+
"const delay=(ms)=>new Promise(r=>setTimeout(r,ms))",
|
| 146 |
+
"const f=(x)=>x*2",
|
| 147 |
+
"const m=arr.map(x=>x*2)",
|
| 148 |
+
"const f2=arr.filter(x=>x>0)",
|
| 149 |
+
"const r=arr.reduce((a,x)=>a+x,0)",
|
| 150 |
+
"const a=\[1,2,3].map(x=>x)",
|
| 151 |
+
"const o={a:1,b:2};const d={k\:v for(\[k,v] of Object.entries(o))}",
|
| 152 |
+
"const s=new Set(\[1,2,3]);const p=new Set(x for(x of s))",
|
| 153 |
+
"const inter=new Set(\[...a].filter(x=>b.has(x)))",
|
| 154 |
+
"const uni=new Set(\[...a,...b])",
|
| 155 |
+
"const diff=new Set(\[...a].filter(x=>!b.has(x)))",
|
| 156 |
+
"const noNone=list.filter(x=>x!=null)",
|
| 157 |
+
"""try{fs.openSync(path)}catch{}""",
|
| 158 |
+
"typeof x==='string'",
|
| 159 |
+
"const b=!!str",
|
| 160 |
+
"if(cond)doSomething()",
|
| 161 |
+
"while(cond){}",
|
| 162 |
+
"for(const x of arr){}",
|
| 163 |
+
"for(const k in obj){}",
|
| 164 |
+
"for(const c of str){}",
|
| 165 |
+
"for(...){if(cond)break}",
|
| 166 |
+
"for(...){if(cond)continue}",
|
| 167 |
+
"function fn(){}",
|
| 168 |
+
"function fn(a=1){}",
|
| 169 |
+
"function fn(){return \[1,2]}",
|
| 170 |
+
"function fn(...a){}",
|
| 171 |
+
"function fn(kwargs){const{a,b}=kwargs}",
|
| 172 |
+
"""function timed(fn){return(...a)=>{const s=Date.now();const r=fn(...a);console.log(Date.now()-s);return r}}""",
|
| 173 |
+
"""const deco=fn=>(...a)=>fn(...a)""",
|
| 174 |
+
"""const memo=fn=>{const c={};return x=>c\[x]||=(fn(x))}""",
|
| 175 |
+
"function*gen(){yield 1;yield 2}",
|
| 176 |
+
"const g=gen();",
|
| 177 |
+
"const it={i:0,next(){return this.i<2?{value\:this.i++,done\:false}:{done\:true}}}",
|
| 178 |
+
"for(const x of it){}",
|
| 179 |
+
"for(const \[i,x] of arr.entries()){}",
|
| 180 |
+
"const z=arr1.map((v,i)=>\[v,arr2\[i]])",
|
| 181 |
+
"const dict=Object.fromEntries(arr1.map((v,i)=>\[v,arr2\[i]]))",
|
| 182 |
+
"JSON.stringify(arr1)===JSON.stringify(arr2)",
|
| 183 |
+
"JSON.stringify(obj1)===JSON.stringify(obj2)",
|
| 184 |
+
"JSON.stringify(new Set(a))===JSON.stringify(new Set(b))",
|
| 185 |
+
"const uniq=\[...new Set(arr)]",
|
| 186 |
+
"set.clear()",
|
| 187 |
+
"set.size===0",
|
| 188 |
+
"set.add(x)",
|
| 189 |
+
"set.delete(x)",
|
| 190 |
+
"set.has(x)",
|
| 191 |
+
"set.size",
|
| 192 |
+
"const hasInt=(\[...a].some(x=>b.has(x)))",
|
| 193 |
+
"arr1.every(x=>arr2.includes(x))",
|
| 194 |
+
"str.includes(sub)",
|
| 195 |
+
"str\[0]",
|
| 196 |
+
"str\[str.length-1]",
|
| 197 |
+
"""const isText=path=>\['.txt','.md'].includes(require('path').extname(path))""",
|
| 198 |
+
"""const isImage=path=>\['.png','.jpg','.jpeg','.gif'].includes(require('path').extname(path))""",
|
| 199 |
+
"Math.round(n)",
|
| 200 |
+
"Math.ceil(n)",
|
| 201 |
+
"Math.floor(n)",
|
| 202 |
+
"n.toFixed(2)",
|
| 203 |
+
"""const randStr=(l)=>\[...Array(l)].map(()=>Math.random().toString(36).charAt(2)).join('')""",
|
| 204 |
+
"const exists=require('fs').existsSync(path)",
|
| 205 |
+
"""const walk=(d)=>require('fs').readdirSync(d).flatMap(f=>{const p=require('path').join(d,f);return require('fs').statSync(p).isDirectory()?walk(p)\:p})""",
|
| 206 |
+
"""const ext=require('path').extname(fp)""",
|
| 207 |
+
"""const name=require('path').basename(fp)""",
|
| 208 |
+
"""const full=require('path').resolve(fp)""",
|
| 209 |
+
"process.version",
|
| 210 |
+
"process.platform",
|
| 211 |
+
"require('os').cpus().length",
|
| 212 |
+
"require('os').totalmem()",
|
| 213 |
+
"""const d=require('os').diskUsageSync?require('os').diskUsageSync('/')\:null""",
|
| 214 |
+
"require('os').networkInterfaces()",
|
| 215 |
+
"""require('dns').resolve('[www.google.com',e=>console.log(!e)](http://www.google.com',e=>console.log%28!e%29))""",
|
| 216 |
+
"""require('https').get(url,res=>res.pipe(require('fs').createWriteStream(dest)))""",
|
| 217 |
+
"""const upload=async f=>Promise.resolve('ok')""",
|
| 218 |
+
"""require('https').request({method:'POST',host,u\:path},()=>{}).end(data)""",
|
| 219 |
+
"""require('https').get(url+'?'+new URLSearchParams(params),res=>{})""",
|
| 220 |
+
"""const req=()=>fetch(url,{headers})""",
|
| 221 |
+
"""const jsdom=require('jsdom');const d=new jsdom.JSDOM(html)""",
|
| 222 |
+
"""const title=jsdom.JSDOM(html).window\.document.querySelector('title').textContent""",
|
| 223 |
+
"""const links=\[...d.window\.document.querySelectorAll('a')].map(a=>a.href)""",
|
| 224 |
+
"""Promise.all(links.map(u=>fetch(u).then(r=>r.blob()).then(b=>require('fs').writeFileSync(require('path').basename(u),Buffer.from(b)))))""",
|
| 225 |
+
"""const freq=html.split(/\W+/).reduce((c,w)=>{c\[w]=(c\[w]||0)+1;return c},{})""",
|
| 226 |
+
"""const login=()=>fetch(url,{method:'POST',body\:creds})""",
|
| 227 |
+
"""const text=html.replace(/<\[^>]+>/g,'')""",
|
| 228 |
+
"""const emails=html.match(/\[\w\.-]+@\[\w\.-]+/g)""",
|
| 229 |
+
"""const phones=html.match(/\\+?\d\[\d -]{7,}\d/g)""",
|
| 230 |
+
"""const nums=html.match(/\d+/g)""",
|
| 231 |
+
"""const newHtml=html.replace(/foo/g,'bar')""",
|
| 232 |
+
"""const ok=/^\d{3}\$/.test(str)""",
|
| 233 |
+
"""const noTags=html.replace(/<\[^>]\*>/g,'')""",
|
| 234 |
+
"""const enc=html.replace(/./g,c=>'\&#'+c.charCodeAt(0)+';')""",
|
| 235 |
+
"""const dec=enc.replace(/\&#(\d+);/g,(m,n)=>String.fromCharCode(n))""",
|
| 236 |
+
"""const {app,BrowserWindow}=require('electron');app.on('ready',()=>new BrowserWindow().loadURL('about\:blank'))""",
|
| 237 |
+
"const button = document.createElement('button'); button.textContent = 'Click Me'; document.body.appendChild(button)",
|
| 238 |
+
"button.addEventListener('click', () => alert('Button Clicked!'))",
|
| 239 |
+
"const input = document.createElement('input'); input.type = 'text'; document.body.appendChild(input)",
|
| 240 |
+
"const inputValue = input.value",
|
| 241 |
+
"document.title = 'New Title'",
|
| 242 |
+
"window.resizeTo(800, 600)",
|
| 243 |
+
"window.moveTo((window.screen.width - window.outerWidth) / 2, (window.screen.height - window.outerHeight) / 2)",
|
| 244 |
+
"const menuBar = document.createElement('menu'); document.body.appendChild(menuBar)",
|
| 245 |
+
"const select = document.createElement('select'); document.body.appendChild(select)",
|
| 246 |
+
"const radio = document.createElement('input'); radio.type = 'radio'; document.body.appendChild(radio)",
|
| 247 |
+
"const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; document.body.appendChild(checkbox)",
|
| 248 |
+
"const img = document.createElement('img'); img.src = 'image.png'; document.body.appendChild(img)",
|
| 249 |
+
"const audio = new Audio('audio.mp3'); audio.play()",
|
| 250 |
+
"const video = document.createElement('video'); video.src = 'video.mp4'; document.body.appendChild(video); video.play()",
|
| 251 |
+
"const currentTime = audio.currentTime",
|
| 252 |
+
"navigator.mediaDevices.getDisplayMedia().then(stream => {})",
|
| 253 |
+
"navigator.mediaDevices.getUserMedia({ video: true }).then(stream => {})",
|
| 254 |
+
"document.addEventListener('mousemove', (event) => { const x = event.clientX; const y = event.clientY })",
|
| 255 |
+
"document.execCommand('insertText', false, 'Hello World')",
|
| 256 |
+
"document.elementFromPoint(100, 100).click()",
|
| 257 |
+
"const timestamp = Date.now()",
|
| 258 |
+
"const date = new Date(timestamp)",
|
| 259 |
+
"const timestampFromDate = date.getTime()",
|
| 260 |
+
"const dayOfWeek = new Date().getDay()",
|
| 261 |
+
"const daysInMonth = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).getDate()",
|
| 262 |
+
"const firstDayOfYear = new Date(new Date().getFullYear(), 0, 1)",
|
| 263 |
+
"const lastDayOfYear = new Date(new Date().getFullYear(), 11, 31)",
|
| 264 |
+
"const firstDayOfMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1)",
|
| 265 |
+
"const lastDayOfMonth = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0)",
|
| 266 |
+
"const isWeekday = new Date().getDay() !== 0 && new Date().getDay() !== 6",
|
| 267 |
+
"const isWeekend = new Date().getDay() === 0 || new Date().getDay() === 6",
|
| 268 |
+
"const currentHour = new Date().getHours()",
|
| 269 |
+
"const currentMinute = new Date().getMinutes()",
|
| 270 |
+
"const currentSecond = new Date().getSeconds()",
|
| 271 |
+
"setTimeout(() => {}, 1000)",
|
| 272 |
+
"const millisecondsTimestamp = Date.now()",
|
| 273 |
+
"const formattedTime = new Date().toLocaleTimeString()",
|
| 274 |
+
"const parsedTime = Date.parse('2023-10-01T00:00:00Z')",
|
| 275 |
+
"const worker = new Worker('worker.js')",
|
| 276 |
+
"worker.postMessage('pause')",
|
| 277 |
+
"new Worker('worker.js').postMessage('start')",
|
| 278 |
+
"const threadName = self.name",
|
| 279 |
+
"worker.terminate()",
|
| 280 |
+
"const lock = new Mutex(); lock.acquire()",
|
| 281 |
+
"const process = new Worker('process.js')",
|
| 282 |
+
"const pid = process.pid",
|
| 283 |
+
"const isAlive = process.terminated === false",
|
| 284 |
+
"new Worker('process.js').postMessage('start')",
|
| 285 |
+
"const queue = new MessageChannel()",
|
| 286 |
+
"const pipe = new MessageChannel()",
|
| 287 |
+
"const cpuUsage = performance.now()",
|
| 288 |
+
"const output = new Response('ls -la').text()",
|
| 289 |
+
"const statusCode = new Response('ls -la').status",
|
| 290 |
+
"const isSuccess = new Response('ls -la').ok",
|
| 291 |
+
"const scriptPath = import.meta.url",
|
| 292 |
+
"const args = process.argv",
|
| 293 |
+
"const parser = new ArgumentParser(); parser.parse_args()",
|
| 294 |
+
"parser.print_help()",
|
| 295 |
+
"Object.keys(require.cache).forEach(module => console.log(module))",
|
| 296 |
+
"const { exec } = require('child_process'); exec('pip install package')",
|
| 297 |
+
"const { exec } = require('child_process'); exec('pip uninstall package')",
|
| 298 |
+
"const packageVersion = require('package').version",
|
| 299 |
+
"const { exec } = require('child_process'); exec('python -m venv venv')",
|
| 300 |
+
"const { exec } = require('child_process'); exec('pip list')",
|
| 301 |
+
"const { exec } = require('child_process'); exec('pip install --upgrade package')",
|
| 302 |
+
"const db = require('sqlite3').Database('db.sqlite')",
|
| 303 |
+
"db.all('SELECT * FROM table', (err, rows) => {})",
|
| 304 |
+
"db.run('INSERT INTO table (column) VALUES (?)', ['value'])",
|
| 305 |
+
"db.run('DELETE FROM table WHERE id = ?', [1])",
|
| 306 |
+
"db.run('UPDATE table SET column = ? WHERE id = ?', ['new_value', 1])",
|
| 307 |
+
"db.all('SELECT * FROM table', (err, rows) => {})",
|
| 308 |
+
"db.run('SELECT * FROM table WHERE column = ?', ['value'], (err, row) => {})",
|
| 309 |
+
"db.close()",
|
| 310 |
+
"db.run('CREATE TABLE table (column TEXT)')",
|
| 311 |
+
"db.run('DROP TABLE table')",
|
| 312 |
+
"db.get('SELECT name FROM sqlite_master WHERE type = "table" AND name = ?', ['table'], (err, row) => {})",
|
| 313 |
+
"db.all('SELECT name FROM sqlite_master WHERE type = "table"', (err, rows) => {})",
|
| 314 |
+
"const { Model } = require('sequelize'); Model.create({ column: 'value' })",
|
| 315 |
+
"Model.findAll({ where: { column: 'value' } })",
|
| 316 |
+
"Model.destroy({ where: { id: 1 } })",
|
| 317 |
+
"Model.update({ column: 'new_value' }, { where: { id: 1 } })",
|
| 318 |
+
"class Table extends Model {}",
|
| 319 |
+
"class ChildTable extends ParentTable {}",
|
| 320 |
+
"Model.init({ id: { type: DataTypes.INTEGER, primaryKey: true } }, { sequelize })",
|
| 321 |
+
"Model.init({ column: { type: DataTypes.STRING, unique: true } }, { sequelize })",
|
| 322 |
+
"Model.init({ column: { type: DataTypes.STRING, defaultValue: 'default' } }, { sequelize })",
|
| 323 |
+
"const csv = require('csv-parser'); fs.createReadStream('data.csv').pipe(csv())",
|
| 324 |
+
"const xlsx = require('xlsx'); xlsx.writeFile(data, 'data.xlsx')",
|
| 325 |
+
"const json = JSON.stringify(data)",
|
| 326 |
+
"const workbook = xlsx.readFile('data.xlsx')",
|
| 327 |
+
"const mergedWorkbook = xlsx.utils.book_append_sheet(workbook1, workbook2)",
|
| 328 |
+
"xlsx.utils.book_append_sheet(workbook, worksheet, 'New Sheet')",
|
| 329 |
+
"const style = workbook.Sheets['Sheet1']['A1'].s",
|
| 330 |
+
"const color = workbook.Sheets['Sheet1']['A1'].s.fill.fgColor",
|
| 331 |
+
"const font = workbook.Sheets['Sheet1']['A1'].s.font",
|
| 332 |
+
"const cellValue = workbook.Sheets['Sheet1']['A1'].v",
|
| 333 |
+
"workbook.Sheets['Sheet1']['A1'].v = 'New Value'",
|
| 334 |
+
"const { width, height } = require('image-size')('image.png')",
|
| 335 |
+
"const sharp = require('sharp'); sharp('image.png').resize(200, 200)"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
|
| 337 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 338 |
|
| 339 |
|
| 340 |
|