Spaces:
Running
Running
File size: 39,072 Bytes
2a39044 90f5392 892f484 7c08c7b 90f5392 2a39044 90f5392 2a39044 892f484 90f5392 79ce9cc 892f484 9284d6e 07b1f25 e49fd82 e54550e 1d25027 892f484 7c08c7b 892f484 7c08c7b 2a39044 892f484 2a39044 79ce9cc 7c08c7b 79ce9cc 2a39044 7c08c7b 892f484 2a39044 892f484 2a39044 7c08c7b 2a39044 7c08c7b 79ce9cc 2a39044 c79e0ff 892f484 7c08c7b 2a39044 79ce9cc c79e0ff aacc39b 2a39044 c79e0ff 892f484 c79e0ff 892f484 2a39044 c79e0ff 2a39044 79ce9cc c79e0ff 79ce9cc c79e0ff 2a39044 c79e0ff 2a39044 aacc39b c79e0ff 892f484 90f5392 0db0051 2a39044 c79e0ff |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 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 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 |
from flask import Flask, request, jsonify, render_template_string
from sentence_transformers import SentenceTransformer, util
import logging
import sys
import signal
# 初始化 Flask 应用
app = Flask(__name__)
# 配置日志,级别设为 INFO
logging.basicConfig(level=logging.INFO)
app.logger = logging.getLogger("CodeSearchAPI")
# 预定义代码片段
CODE_SNIPPETS = [
"public static void PrintText(string text) => Console.WriteLine(text)",
"public static int Sum(int a, int b) => a + b",
"public static int GenerateRandomNumber() => new Random().Next()",
"public static bool IsEven(int number) => number % 2 == 0",
"public static int GetStringLength(string str) => str.Length",
"public static DateTime GetCurrentDate() => DateTime.Today",
"public static bool FileExists(string path) => File.Exists(path)",
"public static string ReadFileContent(string path) => File.ReadAllText(path)",
"public static void WriteToFile(string path, string content) => File.WriteAllText(path, content)",
"public static DateTime GetCurrentTime() => DateTime.Now",
"public static string ToUpperCase(string str) => str.ToUpper()",
"public static string ToLowerCase(string str) => str.ToLower()",
"public static string ReverseString(string str) => new string(str.Reverse().ToArray())",
"public static int CountListElements<T>(List<T> list) => list.Count",
"public static T GetMaxValue<T>(List<T> list) where T : IComparable => list.Max()",
"public static T GetMinValue<T>(List<T> list) where T : IComparable => list.Min()",
"public static List<T> SortList<T>(List<T> list) where T : IComparable => list.OrderBy(x => x).ToList()",
"public static List<T> MergeLists<T>(List<T> list1, List<T> list2) => list1.Concat(list2).ToList()",
"public static List<T> RemoveElement<T>(List<T> list, T element) => list.Where(x => !x.Equals(element)).ToList()",
"public static bool IsListEmpty<T>(List<T> list) => list.Count == 0",
"public static int CountCharInString(string str, char c) => str.Count(x => x == c)",
"public static bool ContainsSubstring(string str, string substring) => str.Contains(substring)",
"public static string NumberToString(int number) => number.ToString()",
"public static int StringToNumber(string str) => int.Parse(str)",
"public static bool IsNumeric(string str) => int.TryParse(str, out _)",
"public static int GetElementIndex<T>(List<T> list, T element) => list.IndexOf(element)",
"public static void ClearList<T>(List<T> list) => list.Clear()",
"public static List<T> ReverseList<T>(List<T> list) { list.Reverse(); return list; }",
"public static List<T> RemoveDuplicates<T>(List<T> list) => list.Distinct().ToList()",
"public static bool IsInList<T>(List<T> list, T value) => list.Contains(value)",
"public static Dictionary<TKey, TValue> CreateDictionary<TKey, TValue>() => new Dictionary<TKey, TValue>()",
"public static void AddToDictionary<TKey, TValue>(Dictionary<TKey, TValue> dict, TKey key, TValue value) => dict[key] = value",
"public static void RemoveKey<TKey, TValue>(Dictionary<TKey, TValue> dict, TKey key) => dict.Remove(key)",
"public static List<TKey> GetDictionaryKeys<TKey, TValue>(Dictionary<TKey, TValue> dict) => dict.Keys.ToList()",
"public static List<TValue> GetDictionaryValues<TKey, TValue>(Dictionary<TKey, TValue> dict) => dict.Values.ToList()",
"public static Dictionary<TKey, TValue> MergeDictionaries<TKey, TValue>(Dictionary<TKey, TValue> dict1, Dictionary<TKey, TValue> dict2) => dict1.Concat(dict2).ToDictionary(x => x.Key, x => x.Value)",
"public static bool IsDictionaryEmpty<TKey, TValue>(Dictionary<TKey, TValue> dict) => dict.Count == 0",
"public static TValue GetDictionaryValue<TKey, TValue>(Dictionary<TKey, TValue> dict, TKey key) => dict[key]",
"public static bool KeyExistsInDictionary<TKey, TValue>(Dictionary<TKey, TValue> dict, TKey key) => dict.ContainsKey(key)",
"public static void ClearDictionary<TKey, TValue>(Dictionary<TKey, TValue> dict) => dict.Clear()",
"public static int CountFileLines(string path) => File.ReadAllLines(path).Length",
"public static void WriteListToFile<T>(string path, List<T> list) => File.WriteAllLines(path, list.Select(x => x.ToString()))",
"public static List<T> ReadListFromFile<T>(string path, Func<string, T> converter) => File.ReadAllLines(path).Select(converter).ToList()",
"public static int CountFileWords(string path) => File.ReadAllText(path).Split(new[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries).Length",
"public static bool IsLeapYear(int year) => DateTime.IsLeapYear(year)",
"public static string FormatDateTime(DateTime dateTime, string format) => dateTime.ToString(format)",
"public static int DaysBetweenDates(DateTime date1, DateTime date2) => (date2 - date1).Days",
"public static string GetCurrentDirectory() => Directory.GetCurrentDirectory()",
"public static List<string> ListDirectoryFiles(string path) => Directory.GetFiles(path).ToList()",
"public static void CreateDirectory(string path) => Directory.CreateDirectory(path)",
"public static void DeleteDirectory(string path) => Directory.Delete(path)",
"public static bool IsFilePath(string path) => File.Exists(path)",
"public static bool IsDirectoryPath(string path) => Directory.Exists(path)",
"public static long GetFileSize(string path) => new FileInfo(path).Length",
"public static void RenameFile(string oldPath, string newPath) => File.Move(oldPath, newPath)",
"public static void CopyFile(string sourcePath, string destinationPath) => File.Copy(sourcePath, destinationPath)",
"public static void MoveFile(string sourcePath, string destinationPath) => File.Move(sourcePath, destinationPath)",
"public static void DeleteFile(string path) => File.Delete(path)",
"public static string GetEnvironmentVariable(string variable) => Environment.GetEnvironmentVariable(variable)",
"public static void SetEnvironmentVariable(string variable, string value) => Environment.SetEnvironmentVariable(variable, value)",
"public static void OpenWebLink(string url) => System.Diagnostics.Process.Start(url)",
"public static string SendGetRequest(string url) => new System.Net.WebClient().DownloadString(url)",
"public static T ParseJson<T>(string json) => System.Text.Json.JsonSerializer.Deserialize<T>(json)",
"public static void WriteJsonToFile<T>(string path, T data) => File.WriteAllText(path, System.Text.Json.JsonSerializer.Serialize(data))",
"public static T ReadJsonFromFile<T>(string path) => System.Text.Json.JsonSerializer.Deserialize<T>(File.ReadAllText(path))",
"public static string ListToString<T>(List<T> list) => string.Join("", list)",
"public static List<string> StringToList(string str) => str.ToCharArray().Select(c => c.ToString()).ToList()",
"public static string JoinListWithComma<T>(List<T> list) => string.Join(",", list)",
"public static string JoinListWithNewLine<T>(List<T> list) => string.Join("\n", list)",
"public static List<string> SplitStringBySpace(string str) => str.Split(' ').ToList()",
"public static List<string> SplitStringByDelimiter(string str, char delimiter) => str.Split(delimiter).ToList()",
"public static List<char> SplitStringToChars(string str) => str.ToCharArray().ToList()",
"public static string ReplaceStringContent(string str, string oldValue, string newValue) => str.Replace(oldValue, newValue)",
"public static string RemoveStringSpaces(string str) => str.Replace(" ", "")",
"public static string RemoveStringPunctuation(string str) => new string(str.Where(c => !char.IsPunctuation(c)).ToArray())",
"public static bool IsStringEmpty(string str) => string.IsNullOrEmpty(str)",
"public static bool IsPalindrome(string str) => str.SequenceEqual(str.Reverse())",
"public static void WriteTextToCsv(string path, List<string> lines) => File.WriteAllLines(path, lines)",
"public static List<string> ReadCsvFile(string path) => File.ReadAllLines(path).ToList()",
"public static int CountCsvLines(string path) => File.ReadAllLines(path).Length",
"public static List<T> ShuffleList<T>(List<T> list) => list.OrderBy(x => Guid.NewGuid()).ToList()",
"public static T GetRandomElement<T>(List<T> list) => list[new Random().Next(list.Count)]",
"public static List<T> GetRandomElements<T>(List<T> list, int count) => list.OrderBy(x => Guid.NewGuid()).Take(count).ToList()",
"public static int RollDice() => new Random().Next(1, 7)",
"public static string FlipCoin() => new Random().Next(2) == 0 ? \"Heads\" : \"Tails\"",
"public static string GenerateRandomPassword(int length) => new string(Enumerable.Repeat(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\", length).Select(s => s[new Random().Next(s.Length)]).ToArray())",
"public static string GenerateRandomColor() => string.Format(\"#{0:X6}\", new Random().Next(0x1000000))",
"public static string GenerateUniqueId() => Guid.NewGuid().ToString()",
"public class MyClass { }",
"public static MyClass CreateClassInstance() => new MyClass()",
"public class MyClass { public void MyMethod() { } }",
"public class MyClass { public string MyProperty { get; set; } }",
"public class ChildClass : MyClass { }",
"public class ChildClass : MyClass { public override void MyMethod() { } }",
"public static void UseClassMethod(MyClass obj) => obj.MyMethod()",
"public class MyClass { public static void StaticMethod() { } }",
"public static bool IsObjectType<T>(object obj) => obj is T",
"public static object GetObjectProperty(object obj, string propertyName) => obj.GetType().GetProperty(propertyName).GetValue(obj)",
"public static void SetObjectProperty(object obj, string propertyName, object value) => obj.GetType().GetProperty(propertyName).SetValue(obj, value)",
"public static void DeleteObjectProperty(object obj, string propertyName) => obj.GetType().GetProperty(propertyName).SetValue(obj, null)",
"""
public static void TryCatchExample()
{
try { throw new Exception("Example exception"); }
catch (Exception ex) { Console.WriteLine(ex.Message); }
}
""",
"""
public static void ThrowCustomException() => throw new CustomException("Custom exception"),
""",
"""
public static string GetExceptionInfo(Exception ex) => ex.Message,
""",
"""
public static void LogError(Exception ex) => Console.WriteLine($"Error: {ex.Message}"),
""",
"""
public static System.Diagnostics.Stopwatch CreateTimer() => System.Diagnostics.Stopwatch.StartNew(),
""",
"""
public static long GetProgramRuntime(System.Diagnostics.Stopwatch timer) => timer.ElapsedMilliseconds,
""",
"""
public static void PrintProgressBar(int progress, int total)
{
float percentage = (float)progress / total;
Console.Write($"\r[{'='.Repeat((int)(percentage * 20))}{' '.Repeat(20 - (int)(percentage * 20))}] {percentage * 100:F2}%");
}
""",
"""
public static void Delay(int milliseconds) => System.Threading.Thread.Sleep(milliseconds),
""",
"""
public static Func<int, int> LambdaExample = x => x * x,
""",
"""
public static List<int> MapExample(List<int> list, Func<int, int> func) => list.Select(func).ToList(),
""",
"""
public static List<int> FilterExample(List<int> list, Func<int, bool> func) => list.Where(func).ToList(),
""",
"""
public static int ReduceExample(List<int> list, Func<int, int, int> func) => list.Aggregate(func),
""",
"""
public static List<int> ListComprehensionExample(List<int> list) => list.Select(x => x * 2).ToList(),
""",
"""
public static Dictionary<int, int> DictComprehensionExample(List<int> list) => list.ToDictionary(x => x, x => x * 2),
""",
"""
public static HashSet<int> SetComprehensionExample(List<int> list) => new HashSet<int>(list.Select(x => x * 2)),
""",
"""
public static HashSet<T> Intersection<T>(HashSet<T> set1, HashSet<T> set2) => new HashSet<T>(set1.Intersect(set2)),
""",
"""
public static HashSet<T> Union<T>(HashSet<T> set1, HashSet<T> set2) => new HashSet<T>(set1.Union(set2)),
""",
"""
public static HashSet<T> Difference<T>(HashSet<T> set1, HashSet<T> set2) => new HashSet<T>(set1.Except(set2)),
""",
"""
public static List<T> RemoveNulls<T>(List<T> list) => list.Where(x => x != null).ToList(),
""",
"""
public static bool TryOpenFile(string path)
{
try { using (var file = File.OpenRead(path)) return true; }
catch { return false; }
}
""",
"""
public static bool CheckVariableType<T>(object obj) => obj is T,
""",
"""
public static bool StringToBool(string str) => bool.Parse(str),
""",
"""
public static void IfExample(bool condition) { if (condition) Console.WriteLine("True"); },
""",
"""
public static void WhileExample(int count) { while (count-- > 0) Console.WriteLine(count); },
""",
"""
public static void ForEachListExample(List<int> list) { foreach (var item in list) Console.WriteLine(item); },
""",
"""
public static void ForEachDictExample(Dictionary<int, string> dict) { foreach (var kvp in dict) Console.WriteLine($"{kvp.Key}: {kvp.Value}"); },
""",
"""
public static void ForEachStringExample(string str) { foreach (var c in str) Console.WriteLine(c); },
""",
"""
public static void BreakExample(List<int> list)
{
foreach (var item in list) { if (item == 0) break; Console.WriteLine(item); }
}
""",
"""
public static void ContinueExample(List<int> list)
{
foreach (var item in list) { if (item == 0) continue; Console.WriteLine(item); }
}
""",
"""
public static void DefineFunction() => Console.WriteLine("Function defined"),
""",
"""
public static void FunctionWithDefault(int a = 10) => Console.WriteLine(a),
""",
"""
public static (int, int) ReturnMultipleValues() => (1, 2),
""",
"""
public static void VariableParams(params int[] numbers) => Console.WriteLine(numbers.Sum()),
""",
"""
public static void KeywordParams(int a, int b) => Console.WriteLine(a + b),
""",
"""
public static void MeasureFunctionTime(Action action)
{
var timer = System.Diagnostics.Stopwatch.StartNew();
action();
Console.WriteLine($"Time: {timer.ElapsedMilliseconds}ms");
}
""",
"""
public static void DecorateFunction(Action action) => action(),
""",
"""
public static void CacheFunctionResult(Func<int> func) => func(),
""",
"""
public static IEnumerable<int> CreateGenerator()
{
for (int i = 0; i < 10; i++) yield return i;
}
""",
"""
public static IEnumerable<int> YieldExample()
{
yield return 1;
yield return 2;
}
""",
"""
public static int NextExample(IEnumerator<int> enumerator) => enumerator.Current,
""",
"""
public static IEnumerator<int> CreateIterator(List<int> list) => list.GetEnumerator(),
""",
"""
public static void ManualIterate(IEnumerator<int> enumerator)
{
while (enumerator.MoveNext()) Console.WriteLine(enumerator.Current);
}
""",
"""
public static void EnumerateExample(List<int> list)
{
foreach (var (index, value) in list.Select((v, i) => (i, v))) Console.WriteLine($"{index}: {value}");
}
""",
"""
public static List<(int, int)> ZipExample(List<int> list1, List<int> list2) => list1.Zip(list2, (a, b) => (a, b)).ToList(),
""",
"""
public static Dictionary<int, int> ListsToDict(List<int> keys, List<int> values) => keys.Zip(values, (k, v) => new { k, v }).ToDictionary(x => x.k, x => x.v),
""",
"""
public static bool AreListsEqual(List<int> list1, List<int> list2) => list1.SequenceEqual(list2),
""",
"""
public static bool AreDictsEqual(Dictionary<int, int> dict1, Dictionary<int, int> dict2) => dict1.OrderBy(kvp => kvp.Key).SequenceEqual(dict2.OrderBy(kvp => kvp.Key)),
""",
"""
public static bool AreSetsEqual(HashSet<int> set1, HashSet<int> set2) => set1.SetEquals(set2),
""",
"""
public static HashSet<T> RemoveDuplicatesSet<T>(HashSet<T> set) => new HashSet<T>(set),
""",
"""
public static void ClearSet<T>(HashSet<T> set) => set.Clear(),
""",
"""
public static bool IsSetEmpty<T>(HashSet<T> set) => set.Count == 0,
""",
"""
public static void AddToSet<T>(HashSet<T> set, T item) => set.Add(item),
""",
"""
public static void RemoveFromSet<T>(HashSet<T> set, T item) => set.Remove(item),
""",
"""
public static bool SetContains<T>(HashSet<T> set, T item) => set.Contains(item),
""",
"""
public static int GetSetLength<T>(HashSet<T> set) => set.Count,
""",
"""
public static bool SetsIntersect<T>(HashSet<T> set1, HashSet<T> set2) => set1.Overlaps(set2),
""",
"""
public static bool IsSubset<T>(List<T> list1, List<T> list2) => list1.All(list2.Contains),
""",
"""
public static bool IsSubstring(string str, string substring) => str.Contains(substring),
""",
"""
public static char GetFirstChar(string str) => str[0],
""",
"""
public static char GetLastChar(string str) => str[^1],
""",
"""
public static bool IsTextFile(string path) => Path.GetExtension(path).ToLower() == ".txt",
""",
"""
public static bool IsImageFile(string path) => new[] { ".jpg", ".png", ".gif" }.Contains(Path.GetExtension(path).ToLower()),
""",
"""
public static double RoundNumber(double number) => Math.Round(number),
""",
"""
public static double CeilNumber(double number) => Math.Ceiling(number),
""",
"""
public static double FloorNumber(double number) => Math.Floor(number),
""",
"""
public static string FormatDecimal(double number, int decimals) => number.ToString($"F{decimals}"),
""",
"""
public static string GenerateRandomString(int length) => new string(Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", length).Select(s => s[new Random().Next(s.Length)]).ToArray()),
""",
"""
public static bool PathExists(string path) => File.Exists(path) || Directory.Exists(path),
""",
"""
public static List<string> TraverseDirectory(string path) => Directory.GetFiles(path, "*", SearchOption.AllDirectories).ToList(),
""",
"""
public static string GetFileExtension(string path) => Path.GetExtension(path),
""",
"""
public static string GetFileName(string path) => Path.GetFileName(path),
""",
"""
public static string GetFullPath(string path) => Path.GetFullPath(path),
""",
"""
public static string GetPythonVersion() => Environment.Version.ToString(),
""",
"""
public static string GetSystemPlatform() => Environment.OSVersion.Platform.ToString(),
""",
"""
public static int GetCpuCores() => Environment.ProcessorCount,
""",
"""
public static long GetMemorySize() => GC.GetTotalMemory(false),
""",
"""
public static string GetDiskUsage() => new DriveInfo(Path.GetPathRoot(Environment.SystemDirectory)).AvailableFreeSpace.ToString(),
""",
"""
public static string GetIpAddress() => System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString(),
""",
"""
public static bool IsConnectedToInternet() => System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable(),
""",
"""
public static void DownloadFile(string url, string path) => new System.Net.WebClient().DownloadFile(url, path),
""",
"""
public static void UploadFile(string url, string path) => new System.Net.WebClient().UploadFile(url, path),
""",
"""
public static string SendPostRequest(string url, string data) => new System.Net.WebClient().UploadString(url, "POST", data),
""",
"""
public static string SendRequestWithParams(string url, System.Collections.Specialized.NameValueCollection data) => new System.Net.WebClient().UploadValues(url, data),
""",
"""
public static void SetRequestHeader(System.Net.WebClient client, string key, string value) => client.Headers[key] = value,
""",
"""
public static string ParseHtml(string html) => new HtmlAgilityPack.HtmlDocument { Text = html }.DocumentNode.InnerText,
""",
"""
public static string ExtractHtmlTitle(string html) => new HtmlAgilityPack.HtmlDocument { Text = html }.DocumentNode.SelectSingleNode("//title")?.InnerText,
""",
"""
public static List<string> ExtractHtmlLinks(string html) => new HtmlAgilityPack.HtmlDocument { Text = html }.DocumentNode.SelectNodes("//a[@href]")?.Select(node => node.GetAttributeValue("href", "")).ToList(),
""",
"""
public static void DownloadHtmlImages(string html, string path)
{
var doc = new HtmlAgilityPack.HtmlDocument { Text = html };
var images = doc.DocumentNode.SelectNodes("//img[@src]")?.Select(node => node.GetAttributeValue("src", "")).ToList();
if (images != null) foreach (var img in images) new System.Net.WebClient().DownloadFile(img, Path.Combine(path, Path.GetFileName(img)));
}
""",
"""
public static Dictionary<string, int> CountWordFrequency(string text) => text.Split(' ').GroupBy(word => word).ToDictionary(group => group.Key, group => group.Count()),
""",
"""
public static void SimulateLogin(string url, System.Collections.Specialized.NameValueCollection data) => new System.Net.WebClient().UploadValues(url, data),
""",
"""
public static string HtmlToText(string html) => new HtmlAgilityPack.HtmlDocument { Text = html }.DocumentNode.InnerText,
""",
"""
public static List<string> ExtractEmails(string text) => System.Text.RegularExpressions.Regex.Matches(text, @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*").Select(match => match.Value).ToList(),
""",
"""
public static List<string> ExtractPhoneNumbers(string text) => System.Text.RegularExpressions.Regex.Matches(text, @"\+?\d[\d -]{8,12}\d").Select(match => match.Value).ToList(),
""",
"""
public static List<string> FindAllNumbers(string text) => System.Text.RegularExpressions.Regex.Matches(text, @"\d+").Select(match => match.Value).ToList(),
""",
"""
public static string ReplaceWithRegex(string text, string pattern, string replacement) => System.Text.RegularExpressions.Regex.Replace(text, pattern, replacement),
""",
"""
public static bool IsRegexMatch(string text, string pattern) => System.Text.RegularExpressions.Regex.IsMatch(text, pattern),
""",
"""
public static string RemoveHtmlTags(string html) => System.Text.RegularExpressions.Regex.Replace(html, "<[^>]*>", string.Empty),
""",
"""
public static string EncodeHtmlEntities(string text) => System.Net.WebUtility.HtmlEncode(text),
""",
"""
public static string DecodeHtmlEntities(string text) => System.Net.WebUtility.HtmlDecode(text),
""",
"""
public static void CreateGuiWindow() => new System.Windows.Forms.Form().ShowDialog(),
""",
"public static void AddButtonToWindow(Form form, string text, int x, int y, EventHandler onClick) { Button button = new Button(); button.Text = text; button.Location = new Point(x, y); button.Click += onClick; form.Controls.Add(button); }", "public static void ShowMessageBox(string message) { MessageBox.Show(message); }", "public static string GetTextBoxText(TextBox textBox) { return textBox.Text; }", "public static void SetWindowTitle(Form form, string title) { form.Text = title; }", "public static void SetWindowSize(Form form, int width, int height) { form.Size = new Size(width, height); }", "public static void CenterWindow(Form form) { form.StartPosition = FormStartPosition.CenterScreen; }", "public static void AddMenuStrip(Form form, ToolStripMenuItem menuItem) { MenuStrip menuStrip = new MenuStrip(); menuStrip.Items.Add(menuItem); form.Controls.Add(menuStrip); }", "public static void AddComboBox(Form form, int x, int y, EventHandler onSelectedIndexChanged) { ComboBox comboBox = new ComboBox(); comboBox.Location = new Point(x, y); comboBox.SelectedIndexChanged += onSelectedIndexChanged; form.Controls.Add(comboBox); }", "public static void AddRadioButton(Form form, string text, int x, int y) { RadioButton radioButton = new RadioButton(); radioButton.Text = text; radioButton.Location = new Point(x, y); form.Controls.Add(radioButton); }", "public static void AddCheckBox(Form form, string text, int x, int y) { CheckBox checkBox = new CheckBox(); checkBox.Text = text; checkBox.Location = new Point(x, y); form.Controls.Add(checkBox); }", "public static void DisplayImage(Form form, string imagePath, int x, int y) { PictureBox pictureBox = new PictureBox(); pictureBox.Image = Image.FromFile(imagePath); pictureBox.Location = new Point(x, y); form.Controls.Add(pictureBox); }", "public static void PlayAudioFile(string filePath) { SoundPlayer player = new SoundPlayer(filePath); player.Play(); }", "public static void PlayVideoFile(Form form, string filePath, int x, int y) { AxWMPLib.AxWindowsMediaPlayer player = new AxWMPLib.AxWindowsMediaPlayer(); player.CreateControl(); player.URL = filePath; player.Location = new Point(x, y); form.Controls.Add(player); }", "public static TimeSpan GetCurrentPlayTime(AxWMPLib.AxWindowsMediaPlayer player) { return player.Ctlcontrols.currentPosition; }", "public static void CaptureScreen(string filePath) { Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); Graphics graphics = Graphics.FromImage(bitmap); graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size); bitmap.Save(filePath); }", "public static void RecordScreen(string filePath, int duration) { // Simulated implementation }", "public static Point GetMousePosition() { return Cursor.Position; }", "public static void SimulateKeyboardInput(string text) { SendKeys.SendWait(text); }", "public static void SimulateMouseClick(int x, int y) { Cursor.Position = new Point(x, y); mouse_event(0x0002 | 0x0004, x, y, 0, 0); }", "public static long GetCurrentTimestamp() { return DateTimeOffset.UtcNow.ToUnixTimeSeconds(); }", "public static DateTime TimestampToDate(long timestamp) { return DateTimeOffset.FromUnixTimeSeconds(timestamp).DateTime; }", "public static long DateToTimestamp(DateTime date) { return new DateTimeOffset(date).ToUnixTimeSeconds(); }", "public static string GetCurrentDayOfWeek() { return DateTime.Now.DayOfWeek.ToString(); }", "public static int GetDaysInCurrentMonth() { return DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month); }", "public static DateTime GetFirstDayOfYear() { return new DateTime(DateTime.Now.Year, 1, 1); }", "public static DateTime GetLastDayOfYear() { return new DateTime(DateTime.Now.Year, 12, 31); }", "public static DateTime GetFirstDayOfMonth(int year, int month) { return new DateTime(year, month, 1); }", "public static DateTime GetLastDayOfMonth(int year, int month) { return new DateTime(year, month, DateTime.DaysInMonth(year, month)); }", "public static bool IsWeekday() { DayOfWeek day = DateTime.Now.DayOfWeek; return day != DayOfWeek.Saturday && day != DayOfWeek.Sunday; }", "public static bool IsWeekend() { DayOfWeek day = DateTime.Now.DayOfWeek; return day == DayOfWeek.Saturday || day == DayOfWeek.Sunday; }", "public static int GetCurrentHour() { return DateTime.Now.Hour; }", "public static int GetCurrentMinute() { return DateTime.Now.Minute; }", "public static int GetCurrentSecond() { return DateTime.Now.Second; }", "public static void DelayOneSecond() { Thread.Sleep(1000); }", "public static long GetMillisecondTimestamp() { return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); }", "public static string FormatTimeToString(DateTime date, string format) { return date.ToString(format); }", "public static DateTime ParseStringToTime(string dateString, string format) { return DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture); }", "public static void CreateThread(ThreadStart start) { Thread thread = new Thread(start); thread.Start(); }", "public static void PauseThread(Thread thread) { thread.Suspend(); }", "public static void RunFunctionInThread(ThreadStart start) { Thread thread = new Thread(start); thread.Start(); }", "public static string GetCurrentThreadName() { return Thread.CurrentThread.Name; }", "public static void SetThreadAsDaemon(Thread thread) { thread.IsBackground = true; }", "public static void LockThread(object lockObject, Action action) { lock (lockObject) { action(); } }", "public static void CreateProcess(string fileName) { Process.Start(fileName); }", "public static int GetProcessId() { return Process.GetCurrentProcess().Id; }", "public static bool IsProcessAlive(int processId) { try { Process.GetProcessById(processId); return true; } catch { return false; } }", "public static void RunFunctionInProcess(Action action) { Task.Run(action); }", "public static void UseQueueToPassValue<T>(Queue<T> queue, T value) { queue.Enqueue(value); }", "public static void UsePipeToCommunicate() { // Simulated implementation }", "public static void LimitCpuUsage() { // Simulated implementation }", "public static void RunShellCommand(string command) { Process.Start(\"cmd.exe\", \"/c \" + command); }", "public static string GetCommandOutput(string command) { Process process = new Process(); process.StartInfo.FileName = \"cmd.exe\"; process.StartInfo.Arguments = \"/c \" + command; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.UseShellExecute = false; process.Start(); return process.StandardOutput.ReadToEnd(); }", "public static int GetCommandExitCode(string command) { Process process = Process.Start(\"cmd.exe\", \"/c \" + command); process.WaitForExit(); return process.ExitCode; }", "public static bool IsCommandSuccessful(string command) { return GetCommandExitCode(command) == 0; }", "public static string GetCurrentScriptPath() { return Assembly.GetExecutingAssembly().Location; }", "public static string[] GetCommandLineArgs() { return Environment.GetCommandLineArgs(); }", "public static void UseArgParse() { // Simulated implementation }", "public static void GenerateCommandHelp() { // Simulated implementation }", "public static void ListPythonModules() { // Simulated implementation }", "public static void InstallPythonPackage(string package) { // Simulated implementation }", "public static void UninstallPythonPackage(string package) { // Simulated implementation }", "public static string GetPackageVersion(string package) { // Simulated implementation return \"\"; }", "public static void UseVirtualEnvironment() { // Simulated implementation }", "public static void ListInstalledPackages() { // Simulated implementation }", "public static void UpgradePythonPackage(string package) { // Simulated implementation }", "public static void ConnectToLocalDatabase(string connectionString) { SqlConnection connection = new SqlConnection(connectionString); connection.Open(); }", "public static DataTable ExecuteSqlQuery(SqlConnection connection, string query) { SqlCommand command = new SqlCommand(query, connection); SqlDataAdapter adapter = new SqlDataAdapter(command); DataTable table = new DataTable(); adapter.Fill(table); return table; }", "public static void InsertRecord(SqlConnection connection, string table, Dictionary<string, object> values) { string columns = string.Join(\",\", values.Keys); string parameters = string.Join(\",\", values.Keys.Select(k => \"@\" + k)); string query = $\"INSERT INTO {table} ({columns}) VALUES ({parameters})\"; SqlCommand command = new SqlCommand(query, connection); foreach (var pair in values) { command.Parameters.AddWithValue(\"@\" + pair.Key, pair.Value); } command.ExecuteNonQuery(); }", "public static void DeleteRecord(SqlConnection connection, string table, string condition) { string query = $\"DELETE FROM {table} WHERE {condition}\"; SqlCommand command = new SqlCommand(query, connection); command.ExecuteNonQuery(); }", "public static void UpdateRecord(SqlConnection connection, string table, Dictionary<string, object> values, string condition) { string setClause = string.Join(\",\", values.Keys.Select(k => $\"{k} = @{k}\")); string query = $\"UPDATE {table} SET {setClause} WHERE {condition}\"; SqlCommand command = new SqlCommand(query, connection); foreach (var pair in values) { command.Parameters.AddWithValue(\"@\" + pair.Key, pair.Value); } command.ExecuteNonQuery(); }", "public static DataTable QueryMultipleRecords(SqlConnection connection, string query) { SqlCommand command = new SqlCommand(query, connection); SqlDataAdapter adapter = new SqlDataAdapter(command); DataTable table = new DataTable(); adapter.Fill(table); return table; }", "public static void UseParameterizedQuery(SqlConnection connection, string query, Dictionary<string, object> parameters) { SqlCommand command = new SqlCommand(query, connection); foreach (var pair in parameters) { command.Parameters.AddWithValue(\"@\" + pair.Key, pair.Value); } command.ExecuteNonQuery(); }", "public static void CloseDatabaseConnection(SqlConnection connection) { connection.Close(); }", "public static void CreateDatabaseTable(SqlConnection connection, string table, Dictionary<string, string> columns) { string columnDefinitions = string.Join(\",\", columns.Select(pair => $\"{pair.Key} {pair.Value}\")); string query = $\"CREATE TABLE {table} ({columnDefinitions})\"; SqlCommand command = new SqlCommand(query, connection); command.ExecuteNonQuery(); }", "public static void DeleteDatabaseTable(SqlConnection connection, string table) { string query = $\"DROP TABLE {table}\"; SqlCommand command = new SqlCommand(query, connection); command.ExecuteNonQuery(); }", "public static bool TableExists(SqlConnection connection, string table) { string query = $\"SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{table}'\"; SqlCommand command = new SqlCommand(query, connection); return command.ExecuteScalar() != null; }", "public static DataTable GetAllTables(SqlConnection connection) { string query = \"SELECT * FROM INFORMATION_SCHEMA.TABLES\"; SqlCommand command = new SqlCommand(query, connection); SqlDataAdapter adapter = new SqlDataAdapter(command); DataTable table = new DataTable(); adapter.Fill(table); return table; }", "public static void UseOrmInsertData<T>(DbContext context, T entity) where T : class { context.Set<T>().Add(entity); context.SaveChanges(); }", "public static List<T> UseOrmQueryData<T>(DbContext context) where T : class { return context.Set<T>().ToList(); }", "public static void UseOrmDeleteData<T>(DbContext context, T entity) where T : class { context.Set<T>().Remove(entity); context.SaveChanges(); }", "public static void UseOrmUpdateData<T>(DbContext context, T entity) where T : class { context.Set<T>().Update(entity); context.SaveChanges(); }", "public static void DefineDatabaseModelClass() { // Simulated implementation }", "public static void ImplementModelClassInheritance() { // Simulated implementation }", "public static void SetPrimaryKeyField() { // Simulated implementation }", "public static void SetUniqueConstraint() { // Simulated implementation }", "public static void SetFieldDefaultValue() { // Simulated implementation }", "public static void ExportDataToCsv(DataTable table, string filePath) { StringBuilder sb = new StringBuilder(); foreach (DataRow row in table.Rows) { sb.AppendLine(string.Join(\",\", row.ItemArray)); } File.WriteAllText(filePath, sb.ToString()); }", "public static void ExportDataToExcel(DataTable table, string filePath) { // Simulated implementation }", "public static void ExportDataToJson(DataTable table, string filePath) { string json = JsonConvert.SerializeObject(table); File.WriteAllText(filePath, json); }", "public static DataTable ReadDataFromExcel(string filePath) { // Simulated implementation return new DataTable(); }", "public static void MergeExcelFiles(List<string> filePaths, string outputPath) { // Simulated implementation }", "public static void AddNewSheetToExcel(string filePath, string sheetName) { // Simulated implementation }", "public static void CopyExcelSheetStyle(string sourceFilePath, string targetFilePath) { // Simulated implementation }", "public static void SetExcelCellColor(string filePath, string sheetName, int row, int column, string color) { // Simulated implementation }", "public static void SetExcelFontStyle(string filePath, string sheetName, int row, int column, string fontName, int fontSize) { // Simulated implementation }", "public static string ReadExcelCellContent(string filePath, string sheetName, int row, int column) { // Simulated implementation return \"\"; }", "public static void WriteExcelCellContent(string filePath, string sheetName, int row, int column, string content) { // Simulated implementation }", "public static Size GetImageDimensions(string imagePath) { Image image = Image.FromFile(imagePath); return image.Size; }", "public static void ResizeImage(string imagePath, string outputPath, int width, int height) { Image image = Image.FromFile(imagePath); Bitmap resizedImage = new Bitmap(image, width, height); resizedImage.Save(outputPath); }"
]
# 全局服务状态
service_ready = False
# 优雅关闭处理
def handle_shutdown(signum, frame):
app.logger.info("收到终止信号,开始关闭...")
sys.exit(0)
signal.signal(signal.SIGTERM, handle_shutdown)
signal.signal(signal.SIGINT, handle_shutdown)
# 初始化模型和预计算编码
try:
app.logger.info("开始加载模型...")
model = SentenceTransformer(
"flax-sentence-embeddings/st-codesearch-distilroberta-base",
cache_folder="/model-cache"
)
# 预计算代码片段的编码(强制使用 CPU)
code_emb = model.encode(CODE_SNIPPETS, convert_to_tensor=True, device="cpu")
service_ready = True
app.logger.info("服务初始化完成")
except Exception as e:
app.logger.error("初始化失败: %s", str(e))
raise
# Hugging Face 健康检查端点,必须响应根路径
@app.route('/')
def hf_health_check():
# 如果请求接受 HTML,则返回一个简单的 HTML 页面(包含测试链接)
if request.accept_mimetypes.accept_html:
html = """
<h2>CodeSearch API</h2>
<p>服务状态:{{ status }}</p>
<p>你可以在地址栏输入 /search?query=你的查询 来测试接口</p>
"""
status = "ready" if service_ready else "initializing"
return render_template_string(html, status=status)
# 否则返回 JSON 格式的健康检查
if service_ready:
return jsonify({"status": "ready"}), 200
else:
return jsonify({"status": "initializing"}), 503
# 搜索 API 端点,同时支持 GET 和 POST 请求
@app.route('/search', methods=['GET', 'POST'])
def handle_search():
if not service_ready:
app.logger.info("服务未就绪")
return jsonify({"error": "服务正在初始化"}), 503
try:
# 根据请求方法提取查询内容
if request.method == 'GET':
query = request.args.get('query', '').strip()
else:
data = request.get_json() or {}
query = data.get('query', '').strip()
if not query:
app.logger.info("收到空的查询请求")
return jsonify({"error": "查询不能为空"}), 400
# 记录接收到的查询
app.logger.info("收到查询请求: %s", query)
# 对查询进行编码,并进行语义搜索
query_emb = model.encode(query, convert_to_tensor=True, device="cpu")
hits = util.semantic_search(query_emb, code_emb, top_k=1)[0]
best = hits[0]
result = {
"code": CODE_SNIPPETS[best['corpus_id']],
"score": round(float(best['score']), 4)
}
# 记录返回结果
app.logger.info("返回结果: %s", result)
return jsonify(result)
except Exception as e:
app.logger.error("请求处理失败: %s", str(e))
return jsonify({"error": "服务器内部错误"}), 500
if __name__ == "__main__":
# 本地测试用,Hugging Face Spaces 通常通过 gunicorn 启动
app.run(host='0.0.0.0', port=7860)
|