Hamhams commited on
Commit
c7f4bd0
1 Parent(s): c773802

commit files to HF hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +5 -0
  2. 0vercl0k__CVE-2019-11708.jsonl +6 -0
  3. 0xSobky__HackVault.jsonl +1 -0
  4. 18F__fbopen.jsonl +4 -0
  5. 28mm__blast-radius.jsonl +11 -0
  6. 3n1b-com__3n1b.com.jsonl +15 -0
  7. 54xingzhe__weixin_crawler.jsonl +0 -0
  8. 5alt__GitLeak.jsonl +11 -0
  9. 75team__SublimeJS.jsonl +12 -0
  10. AdguardTeam__AdGuardForSafari.jsonl +24 -0
  11. AdguardTeam__AdguardBrowserExtension.jsonl +2 -0
  12. Alem__django-jfu.jsonl +2 -0
  13. AlexAltea__unicorn.js.jsonl +2 -0
  14. AllAboutCode__EduBlocks.jsonl +0 -0
  15. AloneMonkey__frida-ios-dump.jsonl +1 -0
  16. Ameobea__robintrack.jsonl +19 -0
  17. Anaconda-Platform__nb_conda.jsonl +0 -0
  18. AniDevTwitter__animeopenings.jsonl +6 -0
  19. Arno0x__DNSExfiltrator.jsonl +2 -0
  20. AudiusProject__audius-protocol.jsonl +0 -0
  21. BE-Kits__xe-crawler.jsonl +2 -0
  22. BelaPlatform__Bela.jsonl +4 -0
  23. Blizzard__node-rdkafka.jsonl +0 -0
  24. BlocklyDuino__BlocklyDuino.jsonl +24 -0
  25. BosNaufal__react-simple-pwa.jsonl +4 -0
  26. ByronHsu__Never-Blink.jsonl +7 -0
  27. CERT-Polska__drakvuf-sandbox.jsonl +0 -0
  28. COVID-19-electronic-health-system__Corona-tracker.jsonl +10 -0
  29. CaliOpen__Caliopen.jsonl +0 -0
  30. CanonicalLtd__react-native.jsonl +2 -0
  31. CartoDB__cartodb.jsonl +2 -0
  32. CermakM__jupyter-datatables.jsonl +7 -0
  33. ChromeDevTools__devtools-frontend.jsonl +8 -0
  34. CivilHub__CivilHub.jsonl +0 -0
  35. Cloud-CV__Origami.jsonl +11 -0
  36. Codility__cui.jsonl +3 -0
  37. Crapworks__ceph-dash.jsonl +2 -0
  38. Creditas__challenge.jsonl +2 -0
  39. DFIRKuiper__Kuiper.jsonl +0 -0
  40. DaoCloud__daochain.jsonl +25 -0
  41. DataDog__documentation.jsonl +0 -0
  42. Dav1dde__glad-web.jsonl +2 -0
  43. Dieterbe__anthracite.jsonl +0 -0
  44. DingZaiHub__PythonSpider.jsonl +1 -0
  45. DocSavage__bloog.jsonl +0 -0
  46. E2OpenPlugins__e2openplugin-OpenWebif.jsonl +0 -0
  47. EDCD__EDDN.jsonl +13 -0
  48. EFForg__OpenWireless.jsonl +43 -0
  49. EFForg__https-everywhere.jsonl +0 -0
  50. EinsteinsWorkshop__BlocksCAD.jsonl +0 -0
.gitattributes CHANGED
@@ -35,3 +35,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
35
  *.mp3 filter=lfs diff=lfs merge=lfs -text
36
  *.ogg filter=lfs diff=lfs merge=lfs -text
37
  *.wav filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
35
  *.mp3 filter=lfs diff=lfs merge=lfs -text
36
  *.ogg filter=lfs diff=lfs merge=lfs -text
37
  *.wav filter=lfs diff=lfs merge=lfs -text
38
+ Nexedi__erp5.jsonl filter=lfs diff=lfs merge=lfs -text
39
+ Southpaw-TACTIC__TACTIC.jsonl filter=lfs diff=lfs merge=lfs -text
40
+ lgeiger__ide-python.jsonl filter=lfs diff=lfs merge=lfs -text
41
+ odoo__odoo.jsonl filter=lfs diff=lfs merge=lfs -text
42
+ replit-archive__jsrepl.jsonl filter=lfs diff=lfs merge=lfs -text
0vercl0k__CVE-2019-11708.jsonl ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
1
+ {"nwo":"0vercl0k\/CVE-2019-11708","sha":"fd4541afaddebf8c4c44683bd9b85e543e10e44a","path":"payload\/src\/genheaders.py","language":"python","identifier":"tabs","parameters":"(n)","argument_list":"","return_statement":"return ' ' * n","docstring":"Get enough space for `n` tabs.","docstring_summary":"Get enough space for `n` tabs.","docstring_tokens":["Get","enough","space","for","n","tabs","."],"function":"def tabs(n):\n '''Get enough space for `n` tabs.'''\n return ' ' * n","function_tokens":["def","tabs","(","n",")",":","return","' '","*","n"],"url":"https:\/\/github.com\/0vercl0k\/CVE-2019-11708\/blob\/fd4541afaddebf8c4c44683bd9b85e543e10e44a\/payload\/src\/genheaders.py#L7-L9"}
2
+ {"nwo":"0vercl0k\/CVE-2019-11708","sha":"fd4541afaddebf8c4c44683bd9b85e543e10e44a","path":"payload\/src\/genheaders.py","language":"python","identifier":"write_array","parameters":"(fout, arr, ntabs = 1)","argument_list":"","return_statement":"","docstring":"Format an uint8_t array in the output file.","docstring_summary":"Format an uint8_t array in the output file.","docstring_tokens":["Format","an","uint8_t","array","in","the","output","file","."],"function":"def write_array(fout, arr, ntabs = 1):\n '''Format an uint8_t array in the output file.''' \n fout.write('{')\n for i, by in enumerate(arr):\n if (i % 8) == 0:\n fout.write('\\n' + tabs(ntabs))\n fout.write('0x%.2x, ' % by)\n fout.write('''\n%s}''' % tabs(ntabs - 1))","function_tokens":["def","write_array","(","fout",",","arr",",","ntabs","=","1",")",":","fout",".","write","(","'{'",")","for","i",",","by","in","enumerate","(","arr",")",":","if","(","i","%","8",")","==","0",":","fout",".","write","(","'\\n'","+","tabs","(","ntabs",")",")","fout",".","write","(","'0x%.2x, '","%","by",")","fout",".","write","(","'''\n%s}'''","%","tabs","(","ntabs","-","1",")",")"],"url":"https:\/\/github.com\/0vercl0k\/CVE-2019-11708\/blob\/fd4541afaddebf8c4c44683bd9b85e543e10e44a\/payload\/src\/genheaders.py#L11-L19"}
3
+ {"nwo":"0vercl0k\/CVE-2019-11708","sha":"fd4541afaddebf8c4c44683bd9b85e543e10e44a","path":"payload\/src\/genheaders.py","language":"python","identifier":"palette2win","parameters":"(palette)","argument_list":"","return_statement":"return win_palette","docstring":"Convert a color palette into a palette that is friendly for Windows.\n `RGBQUAD` on Windows order blue, green, red, so we reorder here..\n We also append a zero byte for the `reserved` field in each `RGBQUAD`.\n typedef struct tagRGBQUAD {\n BYTE rgbBlue;\n BYTE rgbGreen;\n BYTE rgbRed;\n BYTE rgbReserved;\n } RGBQUAD;","docstring_summary":"Convert a color palette into a palette that is friendly for Windows.\n `RGBQUAD` on Windows order blue, green, red, so we reorder here..\n We also append a zero byte for the `reserved` field in each `RGBQUAD`.\n typedef struct tagRGBQUAD {\n BYTE rgbBlue;\n BYTE rgbGreen;\n BYTE rgbRed;\n BYTE rgbReserved;\n } RGBQUAD;","docstring_tokens":["Convert","a","color","palette","into","a","palette","that","is","friendly","for","Windows",".","RGBQUAD","on","Windows","order","blue","green","red","so","we","reorder","here","..","We","also","append","a","zero","byte","for","the","reserved","field","in","each","RGBQUAD",".","typedef","struct","tagRGBQUAD","{","BYTE","rgbBlue",";","BYTE","rgbGreen",";","BYTE","rgbRed",";","BYTE","rgbReserved",";","}","RGBQUAD",";"],"function":"def palette2win(palette):\n '''Convert a color palette into a palette that is friendly for Windows.\n `RGBQUAD` on Windows order blue, green, red, so we reorder here..\n We also append a zero byte for the `reserved` field in each `RGBQUAD`.\n typedef struct tagRGBQUAD {\n BYTE rgbBlue;\n BYTE rgbGreen;\n BYTE rgbRed;\n BYTE rgbReserved;\n } RGBQUAD;'''\n win_palette = []\n for i in range(0, len(palette), 3):\n r, g, b = palette[i : i + 3]\n win_palette.extend([b, g, r, 0])\n\n assert len(win_palette) == (256 * 4), 'Palette is expected to have 256 RGQUAD.'\n return win_palette","function_tokens":["def","palette2win","(","palette",")",":","win_palette","=","[","]","for","i","in","range","(","0",",","len","(","palette",")",",","3",")",":","r",",","g",",","b","=","palette","[","i",":","i","+","3","]","win_palette",".","extend","(","[","b",",","g",",","r",",","0","]",")","assert","len","(","win_palette",")","==","(","256","*","4",")",",","'Palette is expected to have 256 RGQUAD.'","return","win_palette"],"url":"https:\/\/github.com\/0vercl0k\/CVE-2019-11708\/blob\/fd4541afaddebf8c4c44683bd9b85e543e10e44a\/payload\/src\/genheaders.py#L21-L37"}
4
+ {"nwo":"0vercl0k\/CVE-2019-11708","sha":"fd4541afaddebf8c4c44683bd9b85e543e10e44a","path":"payload\/src\/genheaders.py","language":"python","identifier":"getbackground_color","parameters":"(im)","argument_list":"","return_statement":"return (r, g, b)","docstring":"Get the background RGB components. The most used color is assumed to be the\n background color.","docstring_summary":"Get the background RGB components. The most used color is assumed to be the\n background color.","docstring_tokens":["Get","the","background","RGB","components",".","The","most","used","color","is","assumed","to","be","the","background","color","."],"function":"def getbackground_color(im):\n '''Get the background RGB components. The most used color is assumed to be the\n background color.'''\n # Get the most used color, we'll assume it is the background.\n _, background_color = im.getcolors()[-1]\n palette = im.getpalette()\n # Get the RGB components off the palette.\n r, g, b = palette[background_color * 3 : (background_color * 3) + 3]\n return (r, g, b)","function_tokens":["def","getbackground_color","(","im",")",":","# Get the most used color, we'll assume it is the background.","_",",","background_color","=","im",".","getcolors","(",")","[","-","1","]","palette","=","im",".","getpalette","(",")","# Get the RGB components off the palette.","r",",","g",",","b","=","palette","[","background_color","*","3",":","(","background_color","*","3",")","+","3","]","return","(","r",",","g",",","b",")"],"url":"https:\/\/github.com\/0vercl0k\/CVE-2019-11708\/blob\/fd4541afaddebf8c4c44683bd9b85e543e10e44a\/payload\/src\/genheaders.py#L39-L47"}
5
+ {"nwo":"0vercl0k\/CVE-2019-11708","sha":"fd4541afaddebf8c4c44683bd9b85e543e10e44a","path":"payload\/src\/genheaders.py","language":"python","identifier":"compress","parameters":"(buffer_in, fmt)","argument_list":"","return_statement":"return buffer_out.raw[: compressed_size.value]","docstring":"Compress a buffer with a specific format.","docstring_summary":"Compress a buffer with a specific format.","docstring_tokens":["Compress","a","buffer","with","a","specific","format","."],"function":"def compress(buffer_in, fmt):\n '''Compress a buffer with a specific format.'''\n COMPRESSION_ENGINE_MAXIMUM = 256\n RtlCompressBuffer = ctypes.windll.ntdll.RtlCompressBuffer\n RtlGetCompressionWorkSpaceSize = ctypes.windll.ntdll.RtlGetCompressionWorkSpaceSize\n\n fmt_engine = fmt | COMPRESSION_ENGINE_MAXIMUM\n workspace_size = ctypes.c_ulong(0)\n workspace_fragment_size = ctypes.c_ulong(0)\n res = RtlGetCompressionWorkSpaceSize(\n ctypes.c_ushort(fmt_engine),\n ctypes.pointer(workspace_size),\n ctypes.pointer(workspace_fragment_size)\n )\n\n assert res == 0, 'RtlGetCompressionWorkSpaceSize failed.'\n\n workspace = ctypes.c_buffer(workspace_size.value)\n buffer_out = ctypes.c_buffer(len(buffer_in))\n compressed_size = ctypes.c_ulong(0)\n res = RtlCompressBuffer(\n ctypes.c_ushort(fmt_engine),\n buffer_in,\n len(buffer_in),\n buffer_out,\n len(buffer_out),\n ctypes.c_ulong(4096),\n ctypes.pointer(compressed_size),\n workspace\n )\n\n assert res == 0, 'RtlCompressBuffer failed.'\n return buffer_out.raw[: compressed_size.value]","function_tokens":["def","compress","(","buffer_in",",","fmt",")",":","COMPRESSION_ENGINE_MAXIMUM","=","256","RtlCompressBuffer","=","ctypes",".","windll",".","ntdll",".","RtlCompressBuffer","RtlGetCompressionWorkSpaceSize","=","ctypes",".","windll",".","ntdll",".","RtlGetCompressionWorkSpaceSize","fmt_engine","=","fmt","|","COMPRESSION_ENGINE_MAXIMUM","workspace_size","=","ctypes",".","c_ulong","(","0",")","workspace_fragment_size","=","ctypes",".","c_ulong","(","0",")","res","=","RtlGetCompressionWorkSpaceSize","(","ctypes",".","c_ushort","(","fmt_engine",")",",","ctypes",".","pointer","(","workspace_size",")",",","ctypes",".","pointer","(","workspace_fragment_size",")",")","assert","res","==","0",",","'RtlGetCompressionWorkSpaceSize failed.'","workspace","=","ctypes",".","c_buffer","(","workspace_size",".","value",")","buffer_out","=","ctypes",".","c_buffer","(","len","(","buffer_in",")",")","compressed_size","=","ctypes",".","c_ulong","(","0",")","res","=","RtlCompressBuffer","(","ctypes",".","c_ushort","(","fmt_engine",")",",","buffer_in",",","len","(","buffer_in",")",",","buffer_out",",","len","(","buffer_out",")",",","ctypes",".","c_ulong","(","4096",")",",","ctypes",".","pointer","(","compressed_size",")",",","workspace",")","assert","res","==","0",",","'RtlCompressBuffer failed.'","return","buffer_out",".","raw","[",":","compressed_size",".","value","]"],"url":"https:\/\/github.com\/0vercl0k\/CVE-2019-11708\/blob\/fd4541afaddebf8c4c44683bd9b85e543e10e44a\/payload\/src\/genheaders.py#L49-L81"}
6
+ {"nwo":"0vercl0k\/CVE-2019-11708","sha":"fd4541afaddebf8c4c44683bd9b85e543e10e44a","path":"payload\/src\/genheaders.py","language":"python","identifier":"compress_sprites","parameters":"(sprites)","argument_list":"","return_statement":"return (bestformat, map(ord, bestcompressed), len(sprites_buffer))","docstring":"Find the best compression ratio for the set of `sprites`.","docstring_summary":"Find the best compression ratio for the set of `sprites`.","docstring_tokens":["Find","the","best","compression","ratio","for","the","set","of","sprites","."],"function":"def compress_sprites(sprites):\n '''Find the best compression ratio for the set of `sprites`.'''\n compression_formats = {\n 2 : 'COMPRESSION_FORMAT_LZNT1',\n 3 : 'COMPRESSION_FORMAT_XPRESS',\n 4 : 'COMPRESSION_FORMAT_XPRESS_HUFF'\n }\n\n sprites_buffer = []\n for sprite in sprites:\n sprites_buffer.extend(sprite.getdata())\n\n sprites_buffer = ''.join(map(chr, sprites_buffer))\n bestformat, bestcompressed = '', None\n for compression_format in compression_formats.keys():\n compressed_buffer = compress(sprites_buffer, compression_format)\n if bestcompressed is None or len(compressed_buffer) < len(bestcompressed):\n bestformat = compression_formats[compression_format]\n bestcompressed = compressed_buffer\n\n return (bestformat, map(ord, bestcompressed), len(sprites_buffer))","function_tokens":["def","compress_sprites","(","sprites",")",":","compression_formats","=","{","2",":","'COMPRESSION_FORMAT_LZNT1'",",","3",":","'COMPRESSION_FORMAT_XPRESS'",",","4",":","'COMPRESSION_FORMAT_XPRESS_HUFF'","}","sprites_buffer","=","[","]","for","sprite","in","sprites",":","sprites_buffer",".","extend","(","sprite",".","getdata","(",")",")","sprites_buffer","=","''",".","join","(","map","(","chr",",","sprites_buffer",")",")","bestformat",",","bestcompressed","=","''",",","None","for","compression_format","in","compression_formats",".","keys","(",")",":","compressed_buffer","=","compress","(","sprites_buffer",",","compression_format",")","if","bestcompressed","is","None","or","len","(","compressed_buffer",")","<","len","(","bestcompressed",")",":","bestformat","=","compression_formats","[","compression_format","]","bestcompressed","=","compressed_buffer","return","(","bestformat",",","map","(","ord",",","bestcompressed",")",",","len","(","sprites_buffer",")",")"],"url":"https:\/\/github.com\/0vercl0k\/CVE-2019-11708\/blob\/fd4541afaddebf8c4c44683bd9b85e543e10e44a\/payload\/src\/genheaders.py#L83-L103"}
0xSobky__HackVault.jsonl ADDED
@@ -0,0 +1 @@
 
1
+ {"nwo":"0xSobky\/HackVault","sha":"6c45804095b407133182c1461455c7610b187f5f","path":"AutoRecon.py","language":"python","identifier":"main","parameters":"()","argument_list":"","return_statement":"","docstring":"Execute main code.","docstring_summary":"Execute main code.","docstring_tokens":["Execute","main","code","."],"function":"def main():\n \"\"\"Execute main code.\"\"\"\n try:\n domain = sys.argv[1]\n ip_address = socket.gethostbyname(domain)\n except IndexError:\n print('Error: Domain name not specified.')\n sys.exit(1)\n except socket.gaierror:\n print('Error: Domain name cannot be resolved.')\n raise\n procs = []\n whois_cmd = ['whois', domain]\n dig_cmd = ['dig', '-t', 'txt', '+short', domain]\n wpscan_cmd = ['wpscan', '--force', '--update', '--url', domain]\n nmap_hosts_cmd = ['nmap', '-sn', ip_address + '\/24']\n nmap_script_names = ('*-vuln*, banner, default, dns-brute,'\n 'dns-zone-transfer, ftp-*, hostmap-ip2hosts, http-config-backup,'\n 'http-cross*, http-devframework, http-enum, http-headers,'\n 'http-shellshock, http-sitemap-generator, http-waf-fingerprint,'\n 'http-xssed, smtp-*, ssl-*, version')\n nmap_full_cmd = ['nmap', '-sV', '-sS', '-A', '-Pn', '--script',\n nmap_script_names, domain]\n cmds = {'TXT Records': dig_cmd, 'WHOIS Info': whois_cmd,\n 'Active Hosts': nmap_hosts_cmd, 'Nmap Results': nmap_full_cmd,\n 'WPScan': wpscan_cmd}\n\n def handle_proc(proc):\n \"\"\"Handle subprocesses outputs.\"\"\"\n separator = '=================='\n output = b''.join(proc.stdout.readlines()).decode('utf-8')\n print(proc.title)\n print(separator)\n print(output.strip())\n print(separator + '\\n')\n procs.remove(proc)\n\n for title, cmd in cmds.items():\n try:\n proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n proc.title = title\n procs.append(proc)\n except OSError:\n print('%s >> Dependency error occurred.\\n' % title)\n\n while True:\n for proc in procs:\n retcode = proc.poll()\n if retcode is not None:\n handle_proc(proc)\n else:\n continue\n if not procs:\n break\n else:\n sleep(1)","function_tokens":["def","main","(",")",":","try",":","domain","=","sys",".","argv","[","1","]","ip_address","=","socket",".","gethostbyname","(","domain",")","except","IndexError",":","print","(","'Error: Domain name not specified.'",")","sys",".","exit","(","1",")","except","socket",".","gaierror",":","print","(","'Error: Domain name cannot be resolved.'",")","raise","procs","=","[","]","whois_cmd","=","[","'whois'",",","domain","]","dig_cmd","=","[","'dig'",",","'-t'",",","'txt'",",","'+short'",",","domain","]","wpscan_cmd","=","[","'wpscan'",",","'--force'",",","'--update'",",","'--url'",",","domain","]","nmap_hosts_cmd","=","[","'nmap'",",","'-sn'",",","ip_address","+","'\/24'","]","nmap_script_names","=","(","'*-vuln*, banner, default, dns-brute,'","'dns-zone-transfer, ftp-*, hostmap-ip2hosts, http-config-backup,'","'http-cross*, http-devframework, http-enum, http-headers,'","'http-shellshock, http-sitemap-generator, http-waf-fingerprint,'","'http-xssed, smtp-*, ssl-*, version'",")","nmap_full_cmd","=","[","'nmap'",",","'-sV'",",","'-sS'",",","'-A'",",","'-Pn'",",","'--script'",",","nmap_script_names",",","domain","]","cmds","=","{","'TXT Records'",":","dig_cmd",",","'WHOIS Info'",":","whois_cmd",",","'Active Hosts'",":","nmap_hosts_cmd",",","'Nmap Results'",":","nmap_full_cmd",",","'WPScan'",":","wpscan_cmd","}","def","handle_proc","(","proc",")",":","\"\"\"Handle subprocesses outputs.\"\"\"","separator","=","'=================='","output","=","b''",".","join","(","proc",".","stdout",".","readlines","(",")",")",".","decode","(","'utf-8'",")","print","(","proc",".","title",")","print","(","separator",")","print","(","output",".","strip","(",")",")","print","(","separator","+","'\\n'",")","procs",".","remove","(","proc",")","for","title",",","cmd","in","cmds",".","items","(",")",":","try",":","proc","=","subprocess",".","Popen","(","cmd",",","stdout","=","subprocess",".","PIPE",",","stderr","=","subprocess",".","STDOUT",")","proc",".","title","=","title","procs",".","append","(","proc",")","except","OSError",":","print","(","'%s >> Dependency error occurred.\\n'","%","title",")","while","True",":","for","proc","in","procs",":","retcode","=","proc",".","poll","(",")","if","retcode","is","not","None",":","handle_proc","(","proc",")","else",":","continue","if","not","procs",":","break","else",":","sleep","(","1",")"],"url":"https:\/\/github.com\/0xSobky\/HackVault\/blob\/6c45804095b407133182c1461455c7610b187f5f\/AutoRecon.py#L12-L67"}
18F__fbopen.jsonl ADDED
@@ -0,0 +1,4 @@
 
 
 
 
1
+ {"nwo":"18F\/fbopen","sha":"e5a71b8d837f528050a29c5b04a8ea409bc298a3","path":"loaders\/attachments\/base\/util.py","language":"python","identifier":"create_dir","parameters":"(log, dirname=None)","argument_list":"","return_statement":"return dirname","docstring":"Create a directory without failing if it already exists.","docstring_summary":"Create a directory without failing if it already exists.","docstring_tokens":["Create","a","directory","without","failing","if","it","already","exists","."],"function":"def create_dir(log, dirname=None):\n \"\"\"\n Create a directory without failing if it already exists.\n \"\"\"\n\n if dirname and not os.path.isdir(dirname):\n log.info(\"Checking directory... Creating {}\".format(dirname))\n os.makedirs(dirname)\n else:\n log.info(\"Checking directory... {} exists.\".format(dirname))\n\n return dirname","function_tokens":["def","create_dir","(","log",",","dirname","=","None",")",":","if","dirname","and","not","os",".","path",".","isdir","(","dirname",")",":","log",".","info","(","\"Checking directory... Creating {}\"",".","format","(","dirname",")",")","os",".","makedirs","(","dirname",")","else",":","log",".","info","(","\"Checking directory... {} exists.\"",".","format","(","dirname",")",")","return","dirname"],"url":"https:\/\/github.com\/18F\/fbopen\/blob\/e5a71b8d837f528050a29c5b04a8ea409bc298a3\/loaders\/attachments\/base\/util.py#L4-L15"}
2
+ {"nwo":"18F\/fbopen","sha":"e5a71b8d837f528050a29c5b04a8ea409bc298a3","path":"loaders\/attachments\/base\/runner.py","language":"python","identifier":"AttachmentsRunner.create_import_dir","parameters":"(self, dirname=None)","argument_list":"","return_statement":"return dirname","docstring":"Create a timestampped directory to perform an import in.\n Returns a string containing the directory name.","docstring_summary":"Create a timestampped directory to perform an import in.\n Returns a string containing the directory name.","docstring_tokens":["Create","a","timestampped","directory","to","perform","an","import","in",".","Returns","a","string","containing","the","directory","name","."],"function":"def create_import_dir(self, dirname=None):\n \"\"\"\n Create a timestampped directory to perform an import in.\n Returns a string containing the directory name.\n \"\"\"\n\n if not dirname:\n dirname = self.current_import_dirname()\n self.log.debug(dirname)\n\n self.create_dir(dirname=dirname)\n\n return dirname","function_tokens":["def","create_import_dir","(","self",",","dirname","=","None",")",":","if","not","dirname",":","dirname","=","self",".","current_import_dirname","(",")","self",".","log",".","debug","(","dirname",")","self",".","create_dir","(","dirname","=","dirname",")","return","dirname"],"url":"https:\/\/github.com\/18F\/fbopen\/blob\/e5a71b8d837f528050a29c5b04a8ea409bc298a3\/loaders\/attachments\/base\/runner.py#L20-L32"}
3
+ {"nwo":"18F\/fbopen","sha":"e5a71b8d837f528050a29c5b04a8ea409bc298a3","path":"loaders\/attachments\/base\/link_extractor.py","language":"python","identifier":"LinkExtractor.get_links","parameters":"(self, doc, solnbr, shelf)","argument_list":"","return_statement":"return len(links)","docstring":"Parses the links from a doc. Returns the number of links found.","docstring_summary":"Parses the links from a doc. Returns the number of links found.","docstring_tokens":["Parses","the","links","from","a","doc",".","Returns","the","number","of","links","found","."],"function":"def get_links(self, doc, solnbr, shelf):\n '''\n Parses the links from a doc. Returns the number of links found.\n '''\n shelf[solnbr] = {}\n links = self.collect_link_attrs(doc)\n shelf[solnbr] = {'attachments': links}\n\n return len(links)","function_tokens":["def","get_links","(","self",",","doc",",","solnbr",",","shelf",")",":","shelf","[","solnbr","]","=","{","}","links","=","self",".","collect_link_attrs","(","doc",")","shelf","[","solnbr","]","=","{","'attachments'",":","links","}","return","len","(","links",")"],"url":"https:\/\/github.com\/18F\/fbopen\/blob\/e5a71b8d837f528050a29c5b04a8ea409bc298a3\/loaders\/attachments\/base\/link_extractor.py#L62-L70"}
4
+ {"nwo":"18F\/fbopen","sha":"e5a71b8d837f528050a29c5b04a8ea409bc298a3","path":"loaders\/attachments\/base\/link_extractor.py","language":"python","identifier":"LinkExtractor.collect_link_attrs","parameters":"(self, doc)","argument_list":"","return_statement":"return attachments","docstring":"This would be the method to override if scraping a different site.\n It must return a list of dicts containing keys 'filename', 'url', and 'description'. Ala:\n [\n { 'filename': 'example1.txt', 'url': 'http:\/\/example.com\/example1.txt', 'description': 'Just some file' },\n { 'filename': 'example2.doc', 'url': 'http:\/\/example.com\/example2.doc', 'description': 'Some word doc' },\n ]\n 'filename' can be left as None, but it should be defined. This will help indicate that we have some\n more special processing to do, later down the line, than to just download a URL.","docstring_summary":"This would be the method to override if scraping a different site.\n It must return a list of dicts containing keys 'filename', 'url', and 'description'. Ala:\n [\n { 'filename': 'example1.txt', 'url': 'http:\/\/example.com\/example1.txt', 'description': 'Just some file' },\n { 'filename': 'example2.doc', 'url': 'http:\/\/example.com\/example2.doc', 'description': 'Some word doc' },\n ]\n 'filename' can be left as None, but it should be defined. This will help indicate that we have some\n more special processing to do, later down the line, than to just download a URL.","docstring_tokens":["This","would","be","the","method","to","override","if","scraping","a","different","site",".","It","must","return","a","list","of","dicts","containing","keys","filename","url","and","description",".","Ala",":","[","{","filename",":","example1",".","txt","url",":","http",":","\/\/","example",".","com","\/","example1",".","txt","description",":","Just","some","file","}","{","filename",":","example2",".","doc","url",":","http",":","\/\/","example",".","com","\/","example2",".","doc","description",":","Some","word","doc","}","]","filename","can","be","left","as","None","but","it","should","be","defined",".","This","will","help","indicate","that","we","have","some","more","special","processing","to","do","later","down","the","line","than","to","just","download","a","URL","."],"function":"def collect_link_attrs(self, doc):\n '''\n This would be the method to override if scraping a different site.\n It must return a list of dicts containing keys 'filename', 'url', and 'description'. Ala:\n [\n { 'filename': 'example1.txt', 'url': 'http:\/\/example.com\/example1.txt', 'description': 'Just some file' },\n { 'filename': 'example2.doc', 'url': 'http:\/\/example.com\/example2.doc', 'description': 'Some word doc' },\n ]\n 'filename' can be left as None, but it should be defined. This will help indicate that we have some\n more special processing to do, later down the line, than to just download a URL.\n '''\n\n attachments = []\n for div in doc('div.notice_attachment_ro'):\n a = {}\n d = pq(div)\n\n # only in cases where it's a file upload to FBO, then there's a '.file' div\n link_tag = d.find('div.file')('a') or d.find('div')('a')\n\n a = {\n 'filename': link_tag.text().strip(),\n 'url': urljoin(self.fbo_base_url, link_tag.attr('href')),\n 'desc': d.find('span.label').closest('div').remove('span').text().strip(),\n }\n\n attachments.append(a)\n\n if not attachments: # keep looking\n addl_info_link = doc('div#dnf_class_values_procurement_notice__additional_info_link__widget')('a')\n if addl_info_link:\n a = {\n 'filename': None,\n 'url': addl_info_link.attr('href'),\n 'desc': addl_info_link.text().strip(),\n }\n\n attachments.append(a)\n\n return attachments","function_tokens":["def","collect_link_attrs","(","self",",","doc",")",":","attachments","=","[","]","for","div","in","doc","(","'div.notice_attachment_ro'",")",":","a","=","{","}","d","=","pq","(","div",")","# only in cases where it's a file upload to FBO, then there's a '.file' div","link_tag","=","d",".","find","(","'div.file'",")","(","'a'",")","or","d",".","find","(","'div'",")","(","'a'",")","a","=","{","'filename'",":","link_tag",".","text","(",")",".","strip","(",")",",","'url'",":","urljoin","(","self",".","fbo_base_url",",","link_tag",".","attr","(","'href'",")",")",",","'desc'",":","d",".","find","(","'span.label'",")",".","closest","(","'div'",")",".","remove","(","'span'",")",".","text","(",")",".","strip","(",")",",","}","attachments",".","append","(","a",")","if","not","attachments",":","# keep looking","addl_info_link","=","doc","(","'div#dnf_class_values_procurement_notice__additional_info_link__widget'",")","(","'a'",")","if","addl_info_link",":","a","=","{","'filename'",":","None",",","'url'",":","addl_info_link",".","attr","(","'href'",")",",","'desc'",":","addl_info_link",".","text","(",")",".","strip","(",")",",","}","attachments",".","append","(","a",")","return","attachments"],"url":"https:\/\/github.com\/18F\/fbopen\/blob\/e5a71b8d837f528050a29c5b04a8ea409bc298a3\/loaders\/attachments\/base\/link_extractor.py#L72-L111"}
28mm__blast-radius.jsonl ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"28mm\/blast-radius","sha":"a7ec4ef78141ab0d2a688c65112f799adb9622ba","path":"blastradius\/graph.py","language":"python","identifier":"Graph.dot","parameters":"(self)","argument_list":"","return_statement":"return self.dot_template.render({ 'nodes': self.nodes, 'edges': self.edges })","docstring":"returns a dot\/graphviz representation of the graph (a string)","docstring_summary":"returns a dot\/graphviz representation of the graph (a string)","docstring_tokens":["returns","a","dot","\/","graphviz","representation","of","the","graph","(","a","string",")"],"function":"def dot(self):\n 'returns a dot\/graphviz representation of the graph (a string)'\n return self.dot_template.render({ 'nodes': self.nodes, 'edges': self.edges })","function_tokens":["def","dot","(","self",")",":","return","self",".","dot_template",".","render","(","{","'nodes'",":","self",".","nodes",",","'edges'",":","self",".","edges","}",")"],"url":"https:\/\/github.com\/28mm\/blast-radius\/blob\/a7ec4ef78141ab0d2a688c65112f799adb9622ba\/blastradius\/graph.py#L22-L24"}
2
+ {"nwo":"28mm\/blast-radius","sha":"a7ec4ef78141ab0d2a688c65112f799adb9622ba","path":"blastradius\/graph.py","language":"python","identifier":"Graph.svg","parameters":"(self)","argument_list":"","return_statement":"return completed.stdout.decode('utf-8')","docstring":"returns an svg representation of the graph (via graphviz\/dot)","docstring_summary":"returns an svg representation of the graph (via graphviz\/dot)","docstring_tokens":["returns","an","svg","representation","of","the","graph","(","via","graphviz","\/","dot",")"],"function":"def svg(self):\n 'returns an svg representation of the graph (via graphviz\/dot)'\n dot_str = self.dot()\n completed = subprocess.run(['dot', '-Tsvg'], input=dot_str.encode('utf-8'), stdout=subprocess.PIPE)\n if completed.returncode != 0:\n raise\n return completed.stdout.decode('utf-8')","function_tokens":["def","svg","(","self",")",":","dot_str","=","self",".","dot","(",")","completed","=","subprocess",".","run","(","[","'dot'",",","'-Tsvg'","]",",","input","=","dot_str",".","encode","(","'utf-8'",")",",","stdout","=","subprocess",".","PIPE",")","if","completed",".","returncode","!=","0",":","raise","return","completed",".","stdout",".","decode","(","'utf-8'",")"],"url":"https:\/\/github.com\/28mm\/blast-radius\/blob\/a7ec4ef78141ab0d2a688c65112f799adb9622ba\/blastradius\/graph.py#L26-L32"}
3
+ {"nwo":"28mm\/blast-radius","sha":"a7ec4ef78141ab0d2a688c65112f799adb9622ba","path":"blastradius\/graph.py","language":"python","identifier":"Graph.json","parameters":"(self)","argument_list":"","return_statement":"return json.dumps({ 'nodes' : dict(nodes), 'edges' : dict(edges) }, indent=4, sort=True)","docstring":"returns a json representation of the graph (a string)","docstring_summary":"returns a json representation of the graph (a string)","docstring_tokens":["returns","a","json","representation","of","the","graph","(","a","string",")"],"function":"def json(self):\n 'returns a json representation of the graph (a string)'\n return json.dumps({ 'nodes' : dict(nodes), 'edges' : dict(edges) }, indent=4, sort=True)","function_tokens":["def","json","(","self",")",":","return","json",".","dumps","(","{","'nodes'",":","dict","(","nodes",")",",","'edges'",":","dict","(","edges",")","}",",","indent","=","4",",","sort","=","True",")"],"url":"https:\/\/github.com\/28mm\/blast-radius\/blob\/a7ec4ef78141ab0d2a688c65112f799adb9622ba\/blastradius\/graph.py#L34-L36"}
4
+ {"nwo":"28mm\/blast-radius","sha":"a7ec4ef78141ab0d2a688c65112f799adb9622ba","path":"blastradius\/util.py","language":"python","identifier":"to_seconds","parameters":"(string)","argument_list":"","return_statement":"","docstring":"Parse Terraform time interval into an integer representing seconds.","docstring_summary":"Parse Terraform time interval into an integer representing seconds.","docstring_tokens":["Parse","Terraform","time","interval","into","an","integer","representing","seconds","."],"function":"def to_seconds(string):\n '''Parse Terraform time interval into an integer representing seconds.'''\n m = re.match(r'(?P<hours>\\d*h)*(?P<minutes>)\\d*m)*(?P<seconds>\\d*s)*', string)\n if not m:\n return TypeError\n d = m.groupdict()","function_tokens":["def","to_seconds","(","string",")",":","m","=","re",".","match","(","r'(?P<hours>\\d*h)*(?P<minutes>)\\d*m)*(?P<seconds>\\d*s)*'",",","string",")","if","not","m",":","return","TypeError","d","=","m",".","groupdict","(",")"],"url":"https:\/\/github.com\/28mm\/blast-radius\/blob\/a7ec4ef78141ab0d2a688c65112f799adb9622ba\/blastradius\/util.py#L32-L37"}
5
+ {"nwo":"28mm\/blast-radius","sha":"a7ec4ef78141ab0d2a688c65112f799adb9622ba","path":"blastradius\/handlers\/dot.py","language":"python","identifier":"DotGraph.get_node_by_name","parameters":"(self, label)","argument_list":"","return_statement":"return None","docstring":"return node by label (if exists) otherwise simple_name","docstring_summary":"return node by label (if exists) otherwise simple_name","docstring_tokens":["return","node","by","label","(","if","exists",")","otherwise","simple_name"],"function":"def get_node_by_name(self, label):\n '''return node by label (if exists) otherwise simple_name'''\n for n in self.nodes:\n if n.label == label:\n return n\n\n for n in self.nodes:\n if n.simple_name == label:\n return n\n \n return None","function_tokens":["def","get_node_by_name","(","self",",","label",")",":","for","n","in","self",".","nodes",":","if","n",".","label","==","label",":","return","n","for","n","in","self",".","nodes",":","if","n",".","simple_name","==","label",":","return","n","return","None"],"url":"https:\/\/github.com\/28mm\/blast-radius\/blob\/a7ec4ef78141ab0d2a688c65112f799adb9622ba\/blastradius\/handlers\/dot.py#L65-L75"}
6
+ {"nwo":"28mm\/blast-radius","sha":"a7ec4ef78141ab0d2a688c65112f799adb9622ba","path":"blastradius\/handlers\/dot.py","language":"python","identifier":"DotGraph.dot","parameters":"(self)","argument_list":"","return_statement":"return self.dot_template.render({ 'nodes': self.nodes, 'edges': self.edges, 'clusters' : self.clusters, 'EdgeType' : EdgeType })","docstring":"returns a dot\/graphviz representation of the graph (a string)","docstring_summary":"returns a dot\/graphviz representation of the graph (a string)","docstring_tokens":["returns","a","dot","\/","graphviz","representation","of","the","graph","(","a","string",")"],"function":"def dot(self):\n 'returns a dot\/graphviz representation of the graph (a string)'\n return self.dot_template.render({ 'nodes': self.nodes, 'edges': self.edges, 'clusters' : self.clusters, 'EdgeType' : EdgeType })","function_tokens":["def","dot","(","self",")",":","return","self",".","dot_template",".","render","(","{","'nodes'",":","self",".","nodes",",","'edges'",":","self",".","edges",",","'clusters'",":","self",".","clusters",",","'EdgeType'",":","EdgeType","}",")"],"url":"https:\/\/github.com\/28mm\/blast-radius\/blob\/a7ec4ef78141ab0d2a688c65112f799adb9622ba\/blastradius\/handlers\/dot.py#L81-L83"}
7
+ {"nwo":"28mm\/blast-radius","sha":"a7ec4ef78141ab0d2a688c65112f799adb9622ba","path":"blastradius\/handlers\/dot.py","language":"python","identifier":"DotGraph.stack","parameters":"(self, node_type, threshold=2)","argument_list":"","return_statement":"","docstring":"if a group of nodes of type 'type' number as many as 'threshold', \n and share the same (single) parent and (single) child, then\n hide their dependencies, and create a chain of pseudo-dependencies \n so that they stack one above the next in the final diagram.","docstring_summary":"if a group of nodes of type 'type' number as many as 'threshold', \n and share the same (single) parent and (single) child, then\n hide their dependencies, and create a chain of pseudo-dependencies \n so that they stack one above the next in the final diagram.","docstring_tokens":["if","a","group","of","nodes","of","type","type","number","as","many","as","threshold","and","share","the","same","(","single",")","parent","and","(","single",")","child","then","hide","their","dependencies","and","create","a","chain","of","pseudo","-","dependencies","so","that","they","stack","one","above","the","next","in","the","final","diagram","."],"function":"def stack(self, node_type, threshold=2):\n '''if a group of nodes of type 'type' number as many as 'threshold', \n and share the same (single) parent and (single) child, then\n hide their dependencies, and create a chain of pseudo-dependencies \n so that they stack one above the next in the final diagram.'''\n new_edges = []\n\n for n in self.nodes:\n if n.type != node_type:\n continue\n\n parents = [ e for e in self.edges if e.target == n.label ]\n children = [ e for e in self.edges if e.source == n.label ]\n\n if len(children) > 1 or len(parents) != 1:\n continue\n\n # setup the cluster.\n target = children[0].target if len(children) > 0 else ''\n n.cluster = 'cluster' + parents[0].source + '_' + node_type + '_' + target\n self.clusters[n.cluster] = True # <-- OrderedDict, used for its ordering. Pretend its a Set\n\n for cluster in [ cluster for cluster in self.clusters.keys() if re.match('.*_' + node_type + '_.*', cluster) ]:\n nodes = [ n for n in self.nodes if n.cluster == cluster ]\n prev = None\n last_edge = None\n\n if len(nodes) == 1:\n continue\n\n for n in nodes:\n\n # 1st iteration.\n if not prev: \n for e in self.edges:\n if e.source == n.label:\n e.edge_type = EdgeType.HIDDEN\n\n # subsequent iterations.\n else:\n last_edge = None\n for e in self.edges:\n if e.target == n.label:\n e.edge_type = EdgeType.HIDDEN\n if e.source == n.label:\n e.edge_type = EdgeType.HIDDEN\n last_edge = e\n new_edges.append(DotEdge(prev.label, n.label, fmt=Format('style=dashed,arrowhead=none'), edge_type=EdgeType.LAYOUT_SHOWN))\n\n # each iteration.\n prev = n\n \n if last_edge:\n last_edge.edge_type = EdgeType.NORMAL\n\n self.edges = self.edges + new_edges","function_tokens":["def","stack","(","self",",","node_type",",","threshold","=","2",")",":","new_edges","=","[","]","for","n","in","self",".","nodes",":","if","n",".","type","!=","node_type",":","continue","parents","=","[","e","for","e","in","self",".","edges","if","e",".","target","==","n",".","label","]","children","=","[","e","for","e","in","self",".","edges","if","e",".","source","==","n",".","label","]","if","len","(","children",")",">","1","or","len","(","parents",")","!=","1",":","continue","# setup the cluster.","target","=","children","[","0","]",".","target","if","len","(","children",")",">","0","else","''","n",".","cluster","=","'cluster'","+","parents","[","0","]",".","source","+","'_'","+","node_type","+","'_'","+","target","self",".","clusters","[","n",".","cluster","]","=","True","# <-- OrderedDict, used for its ordering. Pretend its a Set","for","cluster","in","[","cluster","for","cluster","in","self",".","clusters",".","keys","(",")","if","re",".","match","(","'.*_'","+","node_type","+","'_.*'",",","cluster",")","]",":","nodes","=","[","n","for","n","in","self",".","nodes","if","n",".","cluster","==","cluster","]","prev","=","None","last_edge","=","None","if","len","(","nodes",")","==","1",":","continue","for","n","in","nodes",":","# 1st iteration.","if","not","prev",":","for","e","in","self",".","edges",":","if","e",".","source","==","n",".","label",":","e",".","edge_type","=","EdgeType",".","HIDDEN","# subsequent iterations.","else",":","last_edge","=","None","for","e","in","self",".","edges",":","if","e",".","target","==","n",".","label",":","e",".","edge_type","=","EdgeType",".","HIDDEN","if","e",".","source","==","n",".","label",":","e",".","edge_type","=","EdgeType",".","HIDDEN","last_edge","=","e","new_edges",".","append","(","DotEdge","(","prev",".","label",",","n",".","label",",","fmt","=","Format","(","'style=dashed,arrowhead=none'",")",",","edge_type","=","EdgeType",".","LAYOUT_SHOWN",")",")","# each iteration.","prev","=","n","if","last_edge",":","last_edge",".","edge_type","=","EdgeType",".","NORMAL","self",".","edges","=","self",".","edges","+","new_edges"],"url":"https:\/\/github.com\/28mm\/blast-radius\/blob\/a7ec4ef78141ab0d2a688c65112f799adb9622ba\/blastradius\/handlers\/dot.py#L96-L151"}
8
+ {"nwo":"28mm\/blast-radius","sha":"a7ec4ef78141ab0d2a688c65112f799adb9622ba","path":"blastradius\/handlers\/dot.py","language":"python","identifier":"DotGraph.set_module_depth","parameters":"(self, depth)","argument_list":"","return_statement":"","docstring":"group resources belonging to modules into a single node, to simplify \n presentation. No claims made for this code. It's garbage!","docstring_summary":"group resources belonging to modules into a single node, to simplify \n presentation. No claims made for this code. It's garbage!","docstring_tokens":["group","resources","belonging","to","modules","into","a","single","node","to","simplify","presentation",".","No","claims","made","for","this","code",".","It","s","garbage!"],"function":"def set_module_depth(self, depth):\n \"\"\"\n group resources belonging to modules into a single node, to simplify \n presentation. No claims made for this code. It's garbage!\n \"\"\"\n\n depth += 1 # account for [root] module\n\n def is_too_deep(modules):\n if len(modules) >= depth and modules[0] != 'root':\n return True\n\n def find_edge(edges, e):\n for edge in edges:\n if e.source == edge.source and e.target == edge.target and e.edge_type == edge.edge_type:\n return True\n return False\n \n # find DotNodes at too great a depth.\n too_deep = [ n for n in self.nodes if is_too_deep(n.modules) ]\n\n # generate ModuleNodes to stand-in for DotNodes at too great a depth.\n placeholders = []\n for n in too_deep:\n match = False\n for p in placeholders:\n if p.is_standin(n.modules):\n match = True\n break\n if match == False:\n placeholders.append(ModuleNode(n.modules[:depth]))\n\n # create replacement edges\n new_edges = []\n for e in self.edges:\n src_mods = DotNode._label_to_modules(e.source)\n tgt_mods = DotNode._label_to_modules(e.target)\n\n if is_too_deep(src_mods) and is_too_deep(tgt_mods):\n continue\n elif is_too_deep(src_mods):\n for p in placeholders:\n if p.is_standin(src_mods):\n replace = True\n for ne in new_edges:\n if ne.source == p.label and ne.target == e.target:\n replace = False\n break\n if replace:\n new_edges.append(DotEdge(p.label, e.target, fmt=Format('')))\n break\n elif is_too_deep(tgt_mods):\n for p in placeholders:\n if p.is_standin(tgt_mods):\n replace = True\n for ne in new_edges:\n if ne.source == e.source and ne.target == p.label:\n replace = False\n break\n if replace:\n new_edges.append(DotEdge(e.source, p.label, fmt=Format('')))\n break\n else:\n new_edges.append(e)\n\n # make sure we haven't got any duplicate edges.\n final_edges = []\n for e in new_edges:\n if not find_edge(final_edges, e):\n final_edges.append(e)\n self.edges = final_edges\n\n # add placeholder nodes, remove nodes beyond specified module_depth.\n self.nodes = list(OrderedSet(placeholders) | (OrderedSet(self.nodes) - OrderedSet(too_deep)))","function_tokens":["def","set_module_depth","(","self",",","depth",")",":","depth","+=","1","# account for [root] module","def","is_too_deep","(","modules",")",":","if","len","(","modules",")",">=","depth","and","modules","[","0","]","!=","'root'",":","return","True","def","find_edge","(","edges",",","e",")",":","for","edge","in","edges",":","if","e",".","source","==","edge",".","source","and","e",".","target","==","edge",".","target","and","e",".","edge_type","==","edge",".","edge_type",":","return","True","return","False","# find DotNodes at too great a depth.","too_deep","=","[","n","for","n","in","self",".","nodes","if","is_too_deep","(","n",".","modules",")","]","# generate ModuleNodes to stand-in for DotNodes at too great a depth.","placeholders","=","[","]","for","n","in","too_deep",":","match","=","False","for","p","in","placeholders",":","if","p",".","is_standin","(","n",".","modules",")",":","match","=","True","break","if","match","==","False",":","placeholders",".","append","(","ModuleNode","(","n",".","modules","[",":","depth","]",")",")","# create replacement edges","new_edges","=","[","]","for","e","in","self",".","edges",":","src_mods","=","DotNode",".","_label_to_modules","(","e",".","source",")","tgt_mods","=","DotNode",".","_label_to_modules","(","e",".","target",")","if","is_too_deep","(","src_mods",")","and","is_too_deep","(","tgt_mods",")",":","continue","elif","is_too_deep","(","src_mods",")",":","for","p","in","placeholders",":","if","p",".","is_standin","(","src_mods",")",":","replace","=","True","for","ne","in","new_edges",":","if","ne",".","source","==","p",".","label","and","ne",".","target","==","e",".","target",":","replace","=","False","break","if","replace",":","new_edges",".","append","(","DotEdge","(","p",".","label",",","e",".","target",",","fmt","=","Format","(","''",")",")",")","break","elif","is_too_deep","(","tgt_mods",")",":","for","p","in","placeholders",":","if","p",".","is_standin","(","tgt_mods",")",":","replace","=","True","for","ne","in","new_edges",":","if","ne",".","source","==","e",".","source","and","ne",".","target","==","p",".","label",":","replace","=","False","break","if","replace",":","new_edges",".","append","(","DotEdge","(","e",".","source",",","p",".","label",",","fmt","=","Format","(","''",")",")",")","break","else",":","new_edges",".","append","(","e",")","# make sure we haven't got any duplicate edges.","final_edges","=","[","]","for","e","in","new_edges",":","if","not","find_edge","(","final_edges",",","e",")",":","final_edges",".","append","(","e",")","self",".","edges","=","final_edges","# add placeholder nodes, remove nodes beyond specified module_depth.","self",".","nodes","=","list","(","OrderedSet","(","placeholders",")","|","(","OrderedSet","(","self",".","nodes",")","-","OrderedSet","(","too_deep",")",")",")"],"url":"https:\/\/github.com\/28mm\/blast-radius\/blob\/a7ec4ef78141ab0d2a688c65112f799adb9622ba\/blastradius\/handlers\/dot.py#L153-L226"}
9
+ {"nwo":"28mm\/blast-radius","sha":"a7ec4ef78141ab0d2a688c65112f799adb9622ba","path":"blastradius\/handlers\/dot.py","language":"python","identifier":"DotGraph.center","parameters":"(self, node)","argument_list":"","return_statement":"","docstring":"prunes graph to include only (1) the given node, (2) its \n dependencies, and nodes that depend on it.","docstring_summary":"prunes graph to include only (1) the given node, (2) its \n dependencies, and nodes that depend on it.","docstring_tokens":["prunes","graph","to","include","only","(","1",")","the","given","node","(","2",")","its","dependencies","and","nodes","that","depend","on","it","."],"function":"def center(self, node):\n '''\n prunes graph to include only (1) the given node, (2) its \n dependencies, and nodes that depend on it.\n '''\n edges_by_source = {}\n for e in self.edges:\n if e.source in edges_by_source:\n edges_by_source[e.source].append(e)\n else:\n edges_by_source[e.source] = [ e ]\n\n edges_by_target = {}\n for e in self.edges: \n if e.target in edges_by_target:\n edges_by_target[e.target].append(e)\n else:\n edges_by_target[e.target] = [ e ]\n\n edges_to_save = OrderedSet() # edge objects\n nodes_to_save = OrderedSet() # label strings\n\n q = deque()\n if node.label in edges_by_source:\n q.append(node.label)\n nodes_to_save.add(node.label)\n while len(q) > 0:\n source = q.pop()\n if source in edges_by_source:\n for e in edges_by_source[source]:\n q.append(e.target)\n edges_to_save.add(e)\n nodes_to_save.add(e.target)\n\n q = deque()\n if node.label in edges_by_target:\n q.append(node.label)\n nodes_to_save.add(node.label)\n while len(q) > 0:\n target = q.pop()\n if target in edges_by_target:\n for e in edges_by_target[target]:\n q.append(e.source)\n edges_to_save.add(e)\n nodes_to_save.add(e.source)\n\n self.edges = list(edges_to_save)\n self.nodes = [ n for n in self.nodes if n.label in nodes_to_save ]","function_tokens":["def","center","(","self",",","node",")",":","edges_by_source","=","{","}","for","e","in","self",".","edges",":","if","e",".","source","in","edges_by_source",":","edges_by_source","[","e",".","source","]",".","append","(","e",")","else",":","edges_by_source","[","e",".","source","]","=","[","e","]","edges_by_target","=","{","}","for","e","in","self",".","edges",":","if","e",".","target","in","edges_by_target",":","edges_by_target","[","e",".","target","]",".","append","(","e",")","else",":","edges_by_target","[","e",".","target","]","=","[","e","]","edges_to_save","=","OrderedSet","(",")","# edge objects","nodes_to_save","=","OrderedSet","(",")","# label strings","q","=","deque","(",")","if","node",".","label","in","edges_by_source",":","q",".","append","(","node",".","label",")","nodes_to_save",".","add","(","node",".","label",")","while","len","(","q",")",">","0",":","source","=","q",".","pop","(",")","if","source","in","edges_by_source",":","for","e","in","edges_by_source","[","source","]",":","q",".","append","(","e",".","target",")","edges_to_save",".","add","(","e",")","nodes_to_save",".","add","(","e",".","target",")","q","=","deque","(",")","if","node",".","label","in","edges_by_target",":","q",".","append","(","node",".","label",")","nodes_to_save",".","add","(","node",".","label",")","while","len","(","q",")",">","0",":","target","=","q",".","pop","(",")","if","target","in","edges_by_target",":","for","e","in","edges_by_target","[","target","]",":","q",".","append","(","e",".","source",")","edges_to_save",".","add","(","e",")","nodes_to_save",".","add","(","e",".","source",")","self",".","edges","=","list","(","edges_to_save",")","self",".","nodes","=","[","n","for","n","in","self",".","nodes","if","n",".","label","in","nodes_to_save","]"],"url":"https:\/\/github.com\/28mm\/blast-radius\/blob\/a7ec4ef78141ab0d2a688c65112f799adb9622ba\/blastradius\/handlers\/dot.py#L229-L276"}
10
+ {"nwo":"28mm\/blast-radius","sha":"a7ec4ef78141ab0d2a688c65112f799adb9622ba","path":"blastradius\/handlers\/dot.py","language":"python","identifier":"DotGraph.focus","parameters":"(self, node)","argument_list":"","return_statement":"","docstring":"prunes graph to include only the given node and its dependencies.","docstring_summary":"prunes graph to include only the given node and its dependencies.","docstring_tokens":["prunes","graph","to","include","only","the","given","node","and","its","dependencies","."],"function":"def focus(self, node):\n '''\n prunes graph to include only the given node and its dependencies.\n '''\n edges_by_source = {}\n for e in self.edges:\n if e.source in edges_by_source:\n edges_by_source[e.source].append(e)\n else:\n edges_by_source[e.source] = [ e ]\n\n edges_to_save = OrderedSet() # edge objects\n nodes_to_save = OrderedSet() # label strings\n\n q = deque()\n if node.label in edges_by_source:\n q.append(node.label)\n nodes_to_save.add(node.label)\n while len(q) > 0:\n source = q.pop()\n if source in edges_by_source:\n for e in edges_by_source[source]:\n q.append(e.target)\n edges_to_save.add(e)\n nodes_to_save.add(e.target)\n\n self.edges = list(edges_to_save)\n self.nodes = [ n for n in self.nodes if n.label in nodes_to_save ]","function_tokens":["def","focus","(","self",",","node",")",":","edges_by_source","=","{","}","for","e","in","self",".","edges",":","if","e",".","source","in","edges_by_source",":","edges_by_source","[","e",".","source","]",".","append","(","e",")","else",":","edges_by_source","[","e",".","source","]","=","[","e","]","edges_to_save","=","OrderedSet","(",")","# edge objects","nodes_to_save","=","OrderedSet","(",")","# label strings","q","=","deque","(",")","if","node",".","label","in","edges_by_source",":","q",".","append","(","node",".","label",")","nodes_to_save",".","add","(","node",".","label",")","while","len","(","q",")",">","0",":","source","=","q",".","pop","(",")","if","source","in","edges_by_source",":","for","e","in","edges_by_source","[","source","]",":","q",".","append","(","e",".","target",")","edges_to_save",".","add","(","e",")","nodes_to_save",".","add","(","e",".","target",")","self",".","edges","=","list","(","edges_to_save",")","self",".","nodes","=","[","n","for","n","in","self",".","nodes","if","n",".","label","in","nodes_to_save","]"],"url":"https:\/\/github.com\/28mm\/blast-radius\/blob\/a7ec4ef78141ab0d2a688c65112f799adb9622ba\/blastradius\/handlers\/dot.py#L278-L305"}
11
+ {"nwo":"28mm\/blast-radius","sha":"a7ec4ef78141ab0d2a688c65112f799adb9622ba","path":"blastradius\/handlers\/dot.py","language":"python","identifier":"ModuleNode.is_standin","parameters":"(self, modules)","argument_list":"","return_statement":"return True","docstring":"should this ModuleNode standin for the provided DotNode?","docstring_summary":"should this ModuleNode standin for the provided DotNode?","docstring_tokens":["should","this","ModuleNode","standin","for","the","provided","DotNode?"],"function":"def is_standin(self, modules):\n 'should this ModuleNode standin for the provided DotNode?'\n if len(modules) < len(self.modules):\n return False\n for i in range(len(self.modules)):\n if self.modules[i] != modules[i]:\n return False\n return True","function_tokens":["def","is_standin","(","self",",","modules",")",":","if","len","(","modules",")","<","len","(","self",".","modules",")",":","return","False","for","i","in","range","(","len","(","self",".","modules",")",")",":","if","self",".","modules","[","i","]","!=","modules","[","i","]",":","return","False","return","True"],"url":"https:\/\/github.com\/28mm\/blast-radius\/blob\/a7ec4ef78141ab0d2a688c65112f799adb9622ba\/blastradius\/handlers\/dot.py#L484-L491"}
3n1b-com__3n1b.com.jsonl ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"3n1b-com\/3n1b.com","sha":"5ee4db23bb665dcbb926c9a55603279ea8a2a73e","path":"helper.py","language":"python","identifier":"Filters.pretty_date","parameters":"(self, time = False)","argument_list":"","return_statement":"return str(day_diff \/ 365) + \" \u5929\u524d\"","docstring":"Get a datetime object or a int() Epoch timestamp and return a\n pretty string like 'an hour ago', 'Yesterday', '3 months ago',\n 'just now', etc","docstring_summary":"Get a datetime object or a int() Epoch timestamp and return a\n pretty string like 'an hour ago', 'Yesterday', '3 months ago',\n 'just now', etc","docstring_tokens":["Get","a","datetime","object","or","a","int","()","Epoch","timestamp","and","return","a","pretty","string","like","an","hour","ago","Yesterday","3","months","ago","just","now","etc"],"function":"def pretty_date(self, time = False):\n \"\"\"\n Get a datetime object or a int() Epoch timestamp and return a\n pretty string like 'an hour ago', 'Yesterday', '3 months ago',\n 'just now', etc\n \"\"\"\n if time == None:\n return time\n\n from datetime import datetime\n now = datetime.now()\n if type(time) is str or type(time) is unicode:\n time = datetime.strptime(time, '%Y-%m-%d %H:%M:%S')\n elif type(time) is int:\n diff = now - datetime.fromtimestamp(time)\n elif isinstance(time, datetime):\n diff = now - time \n elif not time:\n diff = now - now\n second_diff = diff.seconds\n day_diff = diff.days\n\n if day_diff < 0:\n return ''\n\n if day_diff == 0:\n if second_diff < 10:\n return \"\u521a\u521a\"\n if second_diff < 60:\n return str(second_diff) + \" \u79d2\u524d\"\n if second_diff < 120:\n return \"1 \u5206\u949f\u524d\"\n if second_diff < 3600:\n return str(second_diff \/ 60) + \" \u5206\u949f\u524d\"\n if second_diff < 7200:\n return \"1 \u5c0f\u65f6\u524d\"\n if second_diff < 86400:\n return str(second_diff \/ 3600) + \" \u5c0f\u65f6\u524d\"\n if day_diff == 1:\n return \"\u6628\u5929\"\n if day_diff < 7:\n return str(day_diff) + \" \u5929\u524d\"\n if day_diff < 31:\n return str(day_diff \/ 7) + \" \u5468\u524d\"\n if day_diff < 365:\n return str(day_diff \/ 30) + \" \u6708\u524d\"\n return str(day_diff \/ 365) + \" \u5929\u524d\"","function_tokens":["def","pretty_date","(","self",",","time","=","False",")",":","if","time","==","None",":","return","time","from","datetime","import","datetime","now","=","datetime",".","now","(",")","if","type","(","time",")","is","str","or","type","(","time",")","is","unicode",":","time","=","datetime",".","strptime","(","time",",","'%Y-%m-%d %H:%M:%S'",")","elif","type","(","time",")","is","int",":","diff","=","now","-","datetime",".","fromtimestamp","(","time",")","elif","isinstance","(","time",",","datetime",")",":","diff","=","now","-","time","elif","not","time",":","diff","=","now","-","now","second_diff","=","diff",".","seconds","day_diff","=","diff",".","days","if","day_diff","<","0",":","return","''","if","day_diff","==","0",":","if","second_diff","<","10",":","return","\"\u521a\u521a\"","if","second_diff","<","60",":","return","str","(","second_diff",")","+","\" \u79d2\u524d\"","if","second_diff","<","120",":","return","\"1 \u5206\u949f\u524d\"","if","second_diff","<","3600",":","return","str","(","second_diff","\/","60",")","+","\" \u5206\u949f\u524d\"","if","second_diff","<","7200",":","return","\"1 \u5c0f\u65f6\u524d\"","if","second_diff","<","86400",":","return","str","(","second_diff","\/","3600",")","+","\" \u5c0f\u65f6\u524d\"","if","day_diff","==","1",":","return","\"\u6628\u5929\"","if","day_diff","<","7",":","return","str","(","day_diff",")","+","\" \u5929\u524d\"","if","day_diff","<","31",":","return","str","(","day_diff","\/","7",")","+","\" \u5468\u524d\"","if","day_diff","<","365",":","return","str","(","day_diff","\/","30",")","+","\" \u6708\u524d\"","return","str","(","day_diff","\/","365",")","+","\" \u5929\u524d\""],"url":"https:\/\/github.com\/3n1b-com\/3n1b.com\/blob\/5ee4db23bb665dcbb926c9a55603279ea8a2a73e\/helper.py#L82-L128"}
2
+ {"nwo":"3n1b-com\/3n1b.com","sha":"5ee4db23bb665dcbb926c9a55603279ea8a2a73e","path":"lib\/gravatar.py","language":"python","identifier":"sanitize_email","parameters":"(email)","argument_list":"","return_statement":"return email.lower().strip()","docstring":"Returns an e-mail address in lower-case and strip leading and trailing\n whitespaces.\n\n >>> sanitize_email(' MyEmailAddress@example.com ')\n 'myemailaddress@example.com'","docstring_summary":"Returns an e-mail address in lower-case and strip leading and trailing\n whitespaces.","docstring_tokens":["Returns","an","e","-","mail","address","in","lower","-","case","and","strip","leading","and","trailing","whitespaces","."],"function":"def sanitize_email(email):\n \"\"\"\n Returns an e-mail address in lower-case and strip leading and trailing\n whitespaces.\n\n >>> sanitize_email(' MyEmailAddress@example.com ')\n 'myemailaddress@example.com'\n\n \"\"\"\n return email.lower().strip()","function_tokens":["def","sanitize_email","(","email",")",":","return","email",".","lower","(",")",".","strip","(",")"],"url":"https:\/\/github.com\/3n1b-com\/3n1b.com\/blob\/5ee4db23bb665dcbb926c9a55603279ea8a2a73e\/lib\/gravatar.py#L129-L138"}
3
+ {"nwo":"3n1b-com\/3n1b.com","sha":"5ee4db23bb665dcbb926c9a55603279ea8a2a73e","path":"lib\/gravatar.py","language":"python","identifier":"md5_hash","parameters":"(email)","argument_list":"","return_statement":"return md5(email.encode('utf-8')).hexdigest()","docstring":"Returns a md5 hash from an e-mail address.\n\n >>> md5_hash('myemailaddress@example.com')\n '0bc83cb571cd1c50ba6f3e8a78ef1346'","docstring_summary":"Returns a md5 hash from an e-mail address.","docstring_tokens":["Returns","a","md5","hash","from","an","e","-","mail","address","."],"function":"def md5_hash(email):\n \"\"\"\n Returns a md5 hash from an e-mail address.\n\n >>> md5_hash('myemailaddress@example.com')\n '0bc83cb571cd1c50ba6f3e8a78ef1346'\n\n \"\"\"\n return md5(email.encode('utf-8')).hexdigest()","function_tokens":["def","md5_hash","(","email",")",":","return","md5","(","email",".","encode","(","'utf-8'",")",")",".","hexdigest","(",")"],"url":"https:\/\/github.com\/3n1b-com\/3n1b.com\/blob\/5ee4db23bb665dcbb926c9a55603279ea8a2a73e\/lib\/gravatar.py#L141-L149"}
4
+ {"nwo":"3n1b-com\/3n1b.com","sha":"5ee4db23bb665dcbb926c9a55603279ea8a2a73e","path":"lib\/gravatar.py","language":"python","identifier":"Gravatar.get_image","parameters":"(self, size=80, filetype_extension=True)","argument_list":"","return_statement":"return base_url.format(**data)","docstring":"Returns an URL to the user profile image.","docstring_summary":"Returns an URL to the user profile image.","docstring_tokens":["Returns","an","URL","to","the","user","profile","image","."],"function":"def get_image(self, size=80, filetype_extension=True):\n \"\"\"\n Returns an URL to the user profile image.\n \"\"\"\n base_url = 'http:\/\/www.gravatar.com\/avatar\/' \\\n '{hash}{extension}?size={size}'\n extension = '.jpg' if filetype_extension else ''\n\n data = {\n 'hash': self.email_hash,\n 'extension': extension,\n 'size': size,\n }\n return base_url.format(**data)","function_tokens":["def","get_image","(","self",",","size","=","80",",","filetype_extension","=","True",")",":","base_url","=","'http:\/\/www.gravatar.com\/avatar\/'","'{hash}{extension}?size={size}'","extension","=","'.jpg'","if","filetype_extension","else","''","data","=","{","'hash'",":","self",".","email_hash",",","'extension'",":","extension",",","'size'",":","size",",","}","return","base_url",".","format","(","*","*","data",")"],"url":"https:\/\/github.com\/3n1b-com\/3n1b.com\/blob\/5ee4db23bb665dcbb926c9a55603279ea8a2a73e\/lib\/gravatar.py#L44-L57"}
5
+ {"nwo":"3n1b-com\/3n1b.com","sha":"5ee4db23bb665dcbb926c9a55603279ea8a2a73e","path":"lib\/gravatar.py","language":"python","identifier":"Gravatar.get_profile","parameters":"(self, data_format='')","argument_list":"","return_statement":"return base_url.format(**data)","docstring":"Returns an URL to the profile information associated with the\n Gravatar account.","docstring_summary":"Returns an URL to the profile information associated with the\n Gravatar account.","docstring_tokens":["Returns","an","URL","to","the","profile","information","associated","with","the","Gravatar","account","."],"function":"def get_profile(self, data_format=''):\n \"\"\"\n Returns an URL to the profile information associated with the\n Gravatar account.\n \"\"\"\n base_url = 'http:\/\/www.gravatar.com\/{hash}{data_format}'\n\n valid_formats = ['json', 'xml', 'php', 'vcf', 'qr']\n if data_format and data_format in valid_formats:\n data_format = '.%s' % data_format\n\n data = {\n 'hash': self.email_hash,\n 'data_format': data_format,\n }\n return base_url.format(**data)","function_tokens":["def","get_profile","(","self",",","data_format","=","''",")",":","base_url","=","'http:\/\/www.gravatar.com\/{hash}{data_format}'","valid_formats","=","[","'json'",",","'xml'",",","'php'",",","'vcf'",",","'qr'","]","if","data_format","and","data_format","in","valid_formats",":","data_format","=","'.%s'","%","data_format","data","=","{","'hash'",":","self",".","email_hash",",","'data_format'",":","data_format",",","}","return","base_url",".","format","(","*","*","data",")"],"url":"https:\/\/github.com\/3n1b-com\/3n1b.com\/blob\/5ee4db23bb665dcbb926c9a55603279ea8a2a73e\/lib\/gravatar.py#L59-L74"}
6
+ {"nwo":"3n1b-com\/3n1b.com","sha":"5ee4db23bb665dcbb926c9a55603279ea8a2a73e","path":"lib\/gravatar.py","language":"python","identifier":"GravatarXMLRPC.exists","parameters":"(self, hashes)","argument_list":"","return_statement":"return results","docstring":"Checks whether a hash has a gravatar.","docstring_summary":"Checks whether a hash has a gravatar.","docstring_tokens":["Checks","whether","a","hash","has","a","gravatar","."],"function":"def exists(self, hashes):\n \"\"\"Checks whether a hash has a gravatar.\"\"\"\n response = self._call('exists', params={'hashes': hashes})\n results = {}\n for key, value in response.items():\n results[key] = True if value else False\n return results","function_tokens":["def","exists","(","self",",","hashes",")",":","response","=","self",".","_call","(","'exists'",",","params","=","{","'hashes'",":","hashes","}",")","results","=","{","}","for","key",",","value","in","response",".","items","(",")",":","results","[","key","]","=","True","if","value","else","False","return","results"],"url":"https:\/\/github.com\/3n1b-com\/3n1b.com\/blob\/5ee4db23bb665dcbb926c9a55603279ea8a2a73e\/lib\/gravatar.py#L93-L99"}
7
+ {"nwo":"3n1b-com\/3n1b.com","sha":"5ee4db23bb665dcbb926c9a55603279ea8a2a73e","path":"lib\/gravatar.py","language":"python","identifier":"GravatarXMLRPC.addresses","parameters":"(self)","argument_list":"","return_statement":"return self._call('addresses')","docstring":"Gets a list of addresses for this account.","docstring_summary":"Gets a list of addresses for this account.","docstring_tokens":["Gets","a","list","of","addresses","for","this","account","."],"function":"def addresses(self):\n \"\"\"Gets a list of addresses for this account.\"\"\"\n return self._call('addresses')","function_tokens":["def","addresses","(","self",")",":","return","self",".","_call","(","'addresses'",")"],"url":"https:\/\/github.com\/3n1b-com\/3n1b.com\/blob\/5ee4db23bb665dcbb926c9a55603279ea8a2a73e\/lib\/gravatar.py#L101-L103"}
8
+ {"nwo":"3n1b-com\/3n1b.com","sha":"5ee4db23bb665dcbb926c9a55603279ea8a2a73e","path":"lib\/gravatar.py","language":"python","identifier":"GravatarXMLRPC.userimages","parameters":"(self)","argument_list":"","return_statement":"return self._call('userimages')","docstring":"Returns a dict of userimages for this account.","docstring_summary":"Returns a dict of userimages for this account.","docstring_tokens":["Returns","a","dict","of","userimages","for","this","account","."],"function":"def userimages(self):\n \"\"\"Returns a dict of userimages for this account.\"\"\"\n return self._call('userimages')","function_tokens":["def","userimages","(","self",")",":","return","self",".","_call","(","'userimages'",")"],"url":"https:\/\/github.com\/3n1b-com\/3n1b.com\/blob\/5ee4db23bb665dcbb926c9a55603279ea8a2a73e\/lib\/gravatar.py#L105-L107"}
9
+ {"nwo":"3n1b-com\/3n1b.com","sha":"5ee4db23bb665dcbb926c9a55603279ea8a2a73e","path":"lib\/gravatar.py","language":"python","identifier":"GravatarXMLRPC.test","parameters":"(self)","argument_list":"","return_statement":"return self._call('test')","docstring":"Test the API.","docstring_summary":"Test the API.","docstring_tokens":["Test","the","API","."],"function":"def test(self):\n \"\"\"Test the API.\"\"\"\n return self._call('test')","function_tokens":["def","test","(","self",")",":","return","self",".","_call","(","'test'",")"],"url":"https:\/\/github.com\/3n1b-com\/3n1b.com\/blob\/5ee4db23bb665dcbb926c9a55603279ea8a2a73e\/lib\/gravatar.py#L109-L111"}
10
+ {"nwo":"3n1b-com\/3n1b.com","sha":"5ee4db23bb665dcbb926c9a55603279ea8a2a73e","path":"lib\/gravatar.py","language":"python","identifier":"GravatarXMLRPC._call","parameters":"(self, method, params={})","argument_list":"","return_statement":"","docstring":"Call a method from the API, gets 'grav.' prepended to it.","docstring_summary":"Call a method from the API, gets 'grav.' prepended to it.","docstring_tokens":["Call","a","method","from","the","API","gets","grav",".","prepended","to","it","."],"function":"def _call(self, method, params={}):\n \"\"\"Call a method from the API, gets 'grav.' prepended to it.\"\"\"\n\n args = {\n 'apikey': self.apikey,\n 'password': self.password,\n }\n args.update(params)\n\n try:\n return getattr(self._server, 'grav.' + method, None)(args)\n except xmlrpc.client.Fault as error:\n error_msg = \"Server error: {1} (error code: {0})\"\n print(error_msg.format(error.faultCode, error.faultString))","function_tokens":["def","_call","(","self",",","method",",","params","=","{","}",")",":","args","=","{","'apikey'",":","self",".","apikey",",","'password'",":","self",".","password",",","}","args",".","update","(","params",")","try",":","return","getattr","(","self",".","_server",",","'grav.'","+","method",",","None",")","(","args",")","except","xmlrpc",".","client",".","Fault","as","error",":","error_msg","=","\"Server error: {1} (error code: {0})\"","print","(","error_msg",".","format","(","error",".","faultCode",",","error",".","faultString",")",")"],"url":"https:\/\/github.com\/3n1b-com\/3n1b.com\/blob\/5ee4db23bb665dcbb926c9a55603279ea8a2a73e\/lib\/gravatar.py#L113-L126"}
11
+ {"nwo":"3n1b-com\/3n1b.com","sha":"5ee4db23bb665dcbb926c9a55603279ea8a2a73e","path":"lib\/forms.py","language":"python","identifier":"Form.__init__","parameters":"(self, formdata=None, obj=None, prefix='', **kwargs)","argument_list":"","return_statement":"","docstring":"Wrap the `formdata` with the `TornadoInputWrapper` and call the base\n constuctor.","docstring_summary":"Wrap the `formdata` with the `TornadoInputWrapper` and call the base\n constuctor.","docstring_tokens":["Wrap","the","formdata","with","the","TornadoInputWrapper","and","call","the","base","constuctor","."],"function":"def __init__(self, formdata=None, obj=None, prefix='', **kwargs):\n \"\"\"\n Wrap the `formdata` with the `TornadoInputWrapper` and call the base\n constuctor.\n \"\"\"\n self._handler = formdata\n super(Form, self).__init__(TornadoInputWrapper(formdata),\n obj=obj, prefix=prefix, **kwargs)","function_tokens":["def","__init__","(","self",",","formdata","=","None",",","obj","=","None",",","prefix","=","''",",","*","*","kwargs",")",":","self",".","_handler","=","formdata","super","(","Form",",","self",")",".","__init__","(","TornadoInputWrapper","(","formdata",")",",","obj","=","obj",",","prefix","=","prefix",",","*","*","kwargs",")"],"url":"https:\/\/github.com\/3n1b-com\/3n1b.com\/blob\/5ee4db23bb665dcbb926c9a55603279ea8a2a73e\/lib\/forms.py#L58-L65"}
12
+ {"nwo":"3n1b-com\/3n1b.com","sha":"5ee4db23bb665dcbb926c9a55603279ea8a2a73e","path":"lib\/xss.py","language":"python","identifier":"xssescape","parameters":"(text)","argument_list":"","return_statement":"return escape(text, quote=True)","docstring":"Gets rid of < and > and & and, for good measure, :","docstring_summary":"Gets rid of < and > and & and, for good measure, :","docstring_tokens":["Gets","rid","of","<","and",">","and","&","and","for","good","measure",":"],"function":"def xssescape(text):\n \"\"\"Gets rid of < and > and & and, for good measure, :\"\"\"\n # return escape(text, quote=True).replace(':','&#58;')\n # return re.sub(r'(?<!http)(?<!https):', '&#58;', escape(text, quote=True))\n return escape(text, quote=True)","function_tokens":["def","xssescape","(","text",")",":","# return escape(text, quote=True).replace(':','&#58;')","# return re.sub(r'(?<!http)(?<!https):', '&#58;', escape(text, quote=True))","return","escape","(","text",",","quote","=","True",")"],"url":"https:\/\/github.com\/3n1b-com\/3n1b.com\/blob\/5ee4db23bb665dcbb926c9a55603279ea8a2a73e\/lib\/xss.py#L17-L21"}
13
+ {"nwo":"3n1b-com\/3n1b.com","sha":"5ee4db23bb665dcbb926c9a55603279ea8a2a73e","path":"lib\/xss.py","language":"python","identifier":"XssCleaner.strip","parameters":"(self, rawstring)","argument_list":"","return_statement":"return self.result","docstring":"Returns the argument stripped of potentially harmful HTML or Javascript code","docstring_summary":"Returns the argument stripped of potentially harmful HTML or Javascript code","docstring_tokens":["Returns","the","argument","stripped","of","potentially","harmful","HTML","or","Javascript","code"],"function":"def strip(self, rawstring):\n \"\"\"Returns the argument stripped of potentially harmful HTML or Javascript code\"\"\"\n self.result = \"\"\n self.feed(rawstring)\n for endtag in self.open_tags:\n if endtag not in self.requires_no_close:\n self.result += \"<\/%s>\" % endtag\n return self.result","function_tokens":["def","strip","(","self",",","rawstring",")",":","self",".","result","=","\"\"","self",".","feed","(","rawstring",")","for","endtag","in","self",".","open_tags",":","if","endtag","not","in","self",".","requires_no_close",":","self",".","result","+=","\"<\/%s>\"","%","endtag","return","self",".","result"],"url":"https:\/\/github.com\/3n1b-com\/3n1b.com\/blob\/5ee4db23bb665dcbb926c9a55603279ea8a2a73e\/lib\/xss.py#L107-L114"}
14
+ {"nwo":"3n1b-com\/3n1b.com","sha":"5ee4db23bb665dcbb926c9a55603279ea8a2a73e","path":"lib\/xss.py","language":"python","identifier":"XssCleaner.xtags","parameters":"(self)","argument_list":"","return_statement":"return xssescape(tg.strip())","docstring":"Returns a printable string informing the user which tags are allowed","docstring_summary":"Returns a printable string informing the user which tags are allowed","docstring_tokens":["Returns","a","printable","string","informing","the","user","which","tags","are","allowed"],"function":"def xtags(self):\n \"\"\"Returns a printable string informing the user which tags are allowed\"\"\"\n self.permitted_tags.sort()\n tg = \"\"\n for x in self.permitted_tags:\n tg += \"<\" + x\n if x in self.allowed_attributes:\n for y in self.allowed_attributes[x]:\n tg += ' %s=\"\"' % y\n tg += \"> \"\n return xssescape(tg.strip())","function_tokens":["def","xtags","(","self",")",":","self",".","permitted_tags",".","sort","(",")","tg","=","\"\"","for","x","in","self",".","permitted_tags",":","tg","+=","\"<\"","+","x","if","x","in","self",".","allowed_attributes",":","for","y","in","self",".","allowed_attributes","[","x","]",":","tg","+=","' %s=\"\"'","%","y","tg","+=","\"> \"","return","xssescape","(","tg",".","strip","(",")",")"],"url":"https:\/\/github.com\/3n1b-com\/3n1b.com\/blob\/5ee4db23bb665dcbb926c9a55603279ea8a2a73e\/lib\/xss.py#L115-L125"}
15
+ {"nwo":"3n1b-com\/3n1b.com","sha":"5ee4db23bb665dcbb926c9a55603279ea8a2a73e","path":"handler\/topic.py","language":"python","identifier":"ProfileHandler.get","parameters":"(self, user, template_variables = {})","argument_list":"","return_statement":"","docstring":"if user_info[\"github\"]:\n github_repos = self.mc.get(str(\"%s_github_repos\" % user_info[\"github\"])) or json.JSONDecoder().decode(urllib2.urlopen('https:\/\/api.github.com\/users\/%s\/repos' % user_info[\"github\"]).read())\n self.mc.set(str(\"%s_github_repos\" % user_info[\"github\"]), github_repos)\n template_variables[\"github_repos\"] = github_repos","docstring_summary":"if user_info[\"github\"]:\n github_repos = self.mc.get(str(\"%s_github_repos\" % user_info[\"github\"])) or json.JSONDecoder().decode(urllib2.urlopen('https:\/\/api.github.com\/users\/%s\/repos' % user_info[\"github\"]).read())\n self.mc.set(str(\"%s_github_repos\" % user_info[\"github\"]), github_repos)\n template_variables[\"github_repos\"] = github_repos","docstring_tokens":["if","user_info","[","github","]",":","github_repos","=","self",".","mc",".","get","(","str","(","%s_github_repos","%","user_info","[","github","]","))","or","json",".","JSONDecoder","()",".","decode","(","urllib2",".","urlopen","(","https",":","\/\/","api",".","github",".","com","\/","users","\/","%s","\/","repos","%","user_info","[","github","]",")",".","read","()",")","self",".","mc",".","set","(","str","(","%s_github_repos","%","user_info","[","github","]",")","github_repos",")","template_variables","[","github_repos","]","=","github_repos"],"function":"def get(self, user, template_variables = {}):\n current_user_info = self.current_user\n if(re.match(r'^\\d+$', user)):\n user_info = self.user_model.get_user_by_uid(user)\n else:\n user_info = self.user_model.get_user_by_username(user)\n page = int(self.get_argument(\"p\", \"1\"))\n template_variables[\"user_info\"] = user_info\n follow_text = \"+\u5173\u6ce8\"\n show_follow = True;\n if(user_info):\n template_variables[\"user_info\"][\"counter\"] = {\n \"topics\": self.topic_model.get_user_all_topics_count(user_info[\"uid\"]),\n \"replies\": self.reply_model.get_user_all_replies_count(user_info[\"uid\"]),\n \"favorites\": self.favorite_model.get_user_favorite_count(user_info[\"uid\"]),\n \"notifications\": self.notification_model.get_user_unread_notification_count(user_info[\"uid\"]),\n \"messages\": self.message_model.get_user_unread_message_count(user_info[\"uid\"]),\n }\n if(current_user_info):\n if(user_info[\"uid\"] == current_user_info[\"uid\"]):\n show_follow = False;\n else:\n show_follow = True;\n follow = self.follow_model.get_follow_info_by_user_id_and_follow_user_id(current_user_info[\"uid\"], user_info[\"uid\"])\n if(follow):\n follow_text = \"\u53d6\u6d88\u5173\u6ce8\" \n template_variables[\"follow_text\"] = follow_text\n template_variables[\"show_follow\"] = show_follow\n\n '''\n if user_info[\"github\"]:\n github_repos = self.mc.get(str(\"%s_github_repos\" % user_info[\"github\"])) or json.JSONDecoder().decode(urllib2.urlopen('https:\/\/api.github.com\/users\/%s\/repos' % user_info[\"github\"]).read())\n self.mc.set(str(\"%s_github_repos\" % user_info[\"github\"]), github_repos)\n template_variables[\"github_repos\"] = github_repos\n '''\n\n template_variables[\"topics\"] = self.topic_model.get_user_all_topics(user_info[\"uid\"], current_page = page)\n template_variables[\"replies\"] = self.reply_model.get_user_all_replies(user_info[\"uid\"], current_page = page)\n template_variables[\"gen_random\"] = gen_random\n template_variables[\"active_page\"] = \"_blank\"\n template_variables[\"wallpaper\"] = self.get_wallpaper()\n self.render(\"topic\/profile.html\", **template_variables)","function_tokens":["def","get","(","self",",","user",",","template_variables","=","{","}",")",":","current_user_info","=","self",".","current_user","if","(","re",".","match","(","r'^\\d+$'",",","user",")",")",":","user_info","=","self",".","user_model",".","get_user_by_uid","(","user",")","else",":","user_info","=","self",".","user_model",".","get_user_by_username","(","user",")","page","=","int","(","self",".","get_argument","(","\"p\"",",","\"1\"",")",")","template_variables","[","\"user_info\"","]","=","user_info","follow_text","=","\"+\u5173\u6ce8\"","show_follow","=","True","if","(","user_info",")",":","template_variables","[","\"user_info\"","]","[","\"counter\"","]","=","{","\"topics\"",":","self",".","topic_model",".","get_user_all_topics_count","(","user_info","[","\"uid\"","]",")",",","\"replies\"",":","self",".","reply_model",".","get_user_all_replies_count","(","user_info","[","\"uid\"","]",")",",","\"favorites\"",":","self",".","favorite_model",".","get_user_favorite_count","(","user_info","[","\"uid\"","]",")",",","\"notifications\"",":","self",".","notification_model",".","get_user_unread_notification_count","(","user_info","[","\"uid\"","]",")",",","\"messages\"",":","self",".","message_model",".","get_user_unread_message_count","(","user_info","[","\"uid\"","]",")",",","}","if","(","current_user_info",")",":","if","(","user_info","[","\"uid\"","]","==","current_user_info","[","\"uid\"","]",")",":","show_follow","=","False","else",":","show_follow","=","True","follow","=","self",".","follow_model",".","get_follow_info_by_user_id_and_follow_user_id","(","current_user_info","[","\"uid\"","]",",","user_info","[","\"uid\"","]",")","if","(","follow",")",":","follow_text","=","\"\u53d6\u6d88\u5173\u6ce8\" ","template_variables","[","\"follow_text\"","]","=","follow_text","template_variables","[","\"show_follow\"","]","=","show_follow","template_variables","[","\"topics\"","]","=","self",".","topic_model",".","get_user_all_topics","(","user_info","[","\"uid\"","]",",","current_page","=","page",")","template_variables","[","\"replies\"","]","=","self",".","reply_model",".","get_user_all_replies","(","user_info","[","\"uid\"","]",",","current_page","=","page",")","template_variables","[","\"gen_random\"","]","=","gen_random","template_variables","[","\"active_page\"","]","=","\"_blank\"","template_variables","[","\"wallpaper\"","]","=","self",".","get_wallpaper","(",")","self",".","render","(","\"topic\/profile.html\"",",","*","*","template_variables",")"],"url":"https:\/\/github.com\/3n1b-com\/3n1b.com\/blob\/5ee4db23bb665dcbb926c9a55603279ea8a2a73e\/handler\/topic.py#L407-L448"}
54xingzhe__weixin_crawler.jsonl ADDED
The diff for this file is too large to render. See raw diff
5alt__GitLeak.jsonl ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"5alt\/GitLeak","sha":"43c64199a3c09c6357085e6acae9a2f38fea4d37","path":"GitLeak.py","language":"python","identifier":"init","parameters":"()","argument_list":"","return_statement":"return key_words","docstring":"Initialize GitPrey with module inspection and input inspection\n :return: None","docstring_summary":"Initialize GitPrey with module inspection and input inspection\n :return: None","docstring_tokens":["Initialize","GitPrey","with","module","inspection","and","input","inspection",":","return",":","None"],"function":"def init():\n \"\"\"\n Initialize GitPrey with module inspection and input inspection\n :return: None\n \"\"\"\n try:\n imp.find_module('lxml')\n except ImportError:\n error_print('[!_!]ERROR INFO: You have to install lxml module.')\n exit()\n\n # Get command parameters for searching level and key words\n parser = argparse.ArgumentParser(description=\"Searching sensitive file and content in GitHub.\")\n parser.add_argument(\"-l\", \"--level\", type=int, choices=range(1, 6), default=1, metavar=\"level\",\n help=\"Set search level within 1~5, default is 1.\")\n parser.add_argument(\"-k\", \"--keywords\", metavar=\"keywords\", required=True,\n help=\"Set key words to search projects.\")\n args = parser.parse_args()\n\n SEARCH_LEVEL = args.level if args.level else 1\n key_words = args.keywords if args.keywords else \"\"\n\n # Print GitPrey digital logo and version information.\n info_print(GitPrey.__doc__)\n\n keyword_output = \"[^_^] START INFO: The key word for searching is: {keyword}\"\n info_print(keyword_output.format(keyword=key_words))\n\n return key_words","function_tokens":["def","init","(",")",":","try",":","imp",".","find_module","(","'lxml'",")","except","ImportError",":","error_print","(","'[!_!]ERROR INFO: You have to install lxml module.'",")","exit","(",")","# Get command parameters for searching level and key words","parser","=","argparse",".","ArgumentParser","(","description","=","\"Searching sensitive file and content in GitHub.\"",")","parser",".","add_argument","(","\"-l\"",",","\"--level\"",",","type","=","int",",","choices","=","range","(","1",",","6",")",",","default","=","1",",","metavar","=","\"level\"",",","help","=","\"Set search level within 1~5, default is 1.\"",")","parser",".","add_argument","(","\"-k\"",",","\"--keywords\"",",","metavar","=","\"keywords\"",",","required","=","True",",","help","=","\"Set key words to search projects.\"",")","args","=","parser",".","parse_args","(",")","SEARCH_LEVEL","=","args",".","level","if","args",".","level","else","1","key_words","=","args",".","keywords","if","args",".","keywords","else","\"\"","# Print GitPrey digital logo and version information.","info_print","(","GitPrey",".","__doc__",")","keyword_output","=","\"[^_^] START INFO: The key word for searching is: {keyword}\"","info_print","(","keyword_output",".","format","(","keyword","=","key_words",")",")","return","key_words"],"url":"https:\/\/github.com\/5alt\/GitLeak\/blob\/43c64199a3c09c6357085e6acae9a2f38fea4d37\/GitLeak.py#L268-L296"}
2
+ {"nwo":"5alt\/GitLeak","sha":"43c64199a3c09c6357085e6acae9a2f38fea4d37","path":"GitLeak.py","language":"python","identifier":"project_miner","parameters":"(key_words)","argument_list":"","return_statement":"","docstring":"Search projects for content and path inspection later.\n :param key_words: key words for searching\n :return:","docstring_summary":"Search projects for content and path inspection later.\n :param key_words: key words for searching\n :return:","docstring_tokens":["Search","projects","for","content","and","path","inspection","later",".",":","param","key_words",":","key","words","for","searching",":","return",":"],"function":"def project_miner(key_words):\n \"\"\"\n Search projects for content and path inspection later.\n :param key_words: key words for searching\n :return:\n \"\"\"\n # Search projects according to key words and searching level\n _gitprey = GitPrey(key_words)\n total_project_list = _gitprey.search_project()[:MAX_SEARCH_REPO]\n\n project_info_output = \"\\n[*_*] PROJECT INFO: Found {num} public projects related to the key words.\\n\"\n info_print(project_info_output.format(num=len(total_project_list)))\n\n if not total_project_list:\n return\n\n # Scan all projects with pattern content\n info_print(\"[^_^] START INFO: Begin searching sensitive content.\")\n result = {}\n for i in xrange(len(total_project_list)\/MAX_REPO_SINGLE_SEARCH+1):\n repo_list = total_project_list[i*MAX_REPO_SINGLE_SEARCH:i*MAX_REPO_SINGLE_SEARCH+MAX_REPO_SINGLE_SEARCH]\n # Join projects to together to search\n\n if len(repo_list) == 0: break\n\n repo_string = \" repo:\" + \" repo:\".join(repo_list)\n result.update(_gitprey.sensitive_info_query(repo_string))\n jsonify_result(result)\n info_print(\"[^_^] END INFO: Sensitive content searching is done.\\n\")","function_tokens":["def","project_miner","(","key_words",")",":","# Search projects according to key words and searching level","_gitprey","=","GitPrey","(","key_words",")","total_project_list","=","_gitprey",".","search_project","(",")","[",":","MAX_SEARCH_REPO","]","project_info_output","=","\"\\n[*_*] PROJECT INFO: Found {num} public projects related to the key words.\\n\"","info_print","(","project_info_output",".","format","(","num","=","len","(","total_project_list",")",")",")","if","not","total_project_list",":","return","# Scan all projects with pattern content","info_print","(","\"[^_^] START INFO: Begin searching sensitive content.\"",")","result","=","{","}","for","i","in","xrange","(","len","(","total_project_list",")","\/","MAX_REPO_SINGLE_SEARCH","+","1",")",":","repo_list","=","total_project_list","[","i","*","MAX_REPO_SINGLE_SEARCH",":","i","*","MAX_REPO_SINGLE_SEARCH","+","MAX_REPO_SINGLE_SEARCH","]","# Join projects to together to search","if","len","(","repo_list",")","==","0",":","break","repo_string","=","\" repo:\"","+","\" repo:\"",".","join","(","repo_list",")","result",".","update","(","_gitprey",".","sensitive_info_query","(","repo_string",")",")","jsonify_result","(","result",")","info_print","(","\"[^_^] END INFO: Sensitive content searching is done.\\n\"",")"],"url":"https:\/\/github.com\/5alt\/GitLeak\/blob\/43c64199a3c09c6357085e6acae9a2f38fea4d37\/GitLeak.py#L299-L327"}
3
+ {"nwo":"5alt\/GitLeak","sha":"43c64199a3c09c6357085e6acae9a2f38fea4d37","path":"GitLeak.py","language":"python","identifier":"GitPrey.search_project","parameters":"(self)","argument_list":"","return_statement":"return unique_project_list","docstring":"Search related projects with recently indexed sort according to keyword\n :returns: Related projects list","docstring_summary":"Search related projects with recently indexed sort according to keyword\n :returns: Related projects list","docstring_tokens":["Search","related","projects","with","recently","indexed","sort","according","to","keyword",":","returns",":","Related","projects","list"],"function":"def search_project(self):\n \"\"\"\n Search related projects with recently indexed sort according to keyword\n :returns: Related projects list\n \"\"\"\n unique_project_list = []\n self.__auto_login(USER_NAME, PASSWORD)\n info_print('[@_@] Searching projects hard...')\n\n # Get unique project list of first page searched results\n total_progress = SCAN_DEEP[SEARCH_LEVEL - 1]\n query_string = self.keyword + \" -language:\" + \" -language:\".join(LANG_BLACKLIST)\n for i in xrange(total_progress):\n # Print process of searching project\n progress_point = int((i + 1) * (100 \/ total_progress))\n sys.stdout.write(str(progress_point) + '%|' + '#' * progress_point + '|\\r')\n sys.stdout.flush()\n # Search project in each page\n code_url = self.search_url.format(page=1, keyword=quote(query_string))\n page_html_parse = self.__get_page_html(code_url)\n project_list = self.__page_project_list(page_html_parse) # Project list of per result page\n page_project_num, project_list = len(project_list), list(set(project_list))\n unique_project_list.extend(project_list) # Extend unique project list of per page\n if page_project_num < MAX_RLT_PER_PAGE:\n break\n project = \" -repo:\" + \" -repo:\".join(project_list)\n query_string += project\n # Deal with last progress bar stdout\n sys.stdout.write('100%|' + '#' * 100 + '|\\r')\n sys.stdout.flush()\n return unique_project_list","function_tokens":["def","search_project","(","self",")",":","unique_project_list","=","[","]","self",".","__auto_login","(","USER_NAME",",","PASSWORD",")","info_print","(","'[@_@] Searching projects hard...'",")","# Get unique project list of first page searched results","total_progress","=","SCAN_DEEP","[","SEARCH_LEVEL","-","1","]","query_string","=","self",".","keyword","+","\" -language:\"","+","\" -language:\"",".","join","(","LANG_BLACKLIST",")","for","i","in","xrange","(","total_progress",")",":","# Print process of searching project","progress_point","=","int","(","(","i","+","1",")","*","(","100","\/","total_progress",")",")","sys",".","stdout",".","write","(","str","(","progress_point",")","+","'%|'","+","'#'","*","progress_point","+","'|\\r'",")","sys",".","stdout",".","flush","(",")","# Search project in each page","code_url","=","self",".","search_url",".","format","(","page","=","1",",","keyword","=","quote","(","query_string",")",")","page_html_parse","=","self",".","__get_page_html","(","code_url",")","project_list","=","self",".","__page_project_list","(","page_html_parse",")","# Project list of per result page","page_project_num",",","project_list","=","len","(","project_list",")",",","list","(","set","(","project_list",")",")","unique_project_list",".","extend","(","project_list",")","# Extend unique project list of per page","if","page_project_num","<","MAX_RLT_PER_PAGE",":","break","project","=","\" -repo:\"","+","\" -repo:\"",".","join","(","project_list",")","query_string","+=","project","# Deal with last progress bar stdout","sys",".","stdout",".","write","(","'100%|'","+","'#'","*","100","+","'|\\r'",")","sys",".","stdout",".","flush","(",")","return","unique_project_list"],"url":"https:\/\/github.com\/5alt\/GitLeak\/blob\/43c64199a3c09c6357085e6acae9a2f38fea4d37\/GitLeak.py#L68-L98"}
4
+ {"nwo":"5alt\/GitLeak","sha":"43c64199a3c09c6357085e6acae9a2f38fea4d37","path":"GitLeak.py","language":"python","identifier":"GitPrey.__page_project_list","parameters":"(page_html)","argument_list":"","return_statement":"return page_project","docstring":"Get project list of one searching result page\n :param page_html: Html page content\n :returns: Project list of per page","docstring_summary":"Get project list of one searching result page\n :param page_html: Html page content\n :returns: Project list of per page","docstring_tokens":["Get","project","list","of","one","searching","result","page",":","param","page_html",":","Html","page","content",":","returns",":","Project","list","of","per","page"],"function":"def __page_project_list(page_html):\n \"\"\"\n Get project list of one searching result page\n :param page_html: Html page content\n :returns: Project list of per page\n \"\"\"\n cur_par_html = BeautifulSoup(page_html, \"lxml\")\n project_info = cur_par_html.select(\"a.text-bold\")\n page_project = [project.text for project in project_info if not project.text.endswith('.github.io') and not len([i for i in REPO_NAME_BLACKLIST if i in project.text.lower()])]\n return page_project","function_tokens":["def","__page_project_list","(","page_html",")",":","cur_par_html","=","BeautifulSoup","(","page_html",",","\"lxml\"",")","project_info","=","cur_par_html",".","select","(","\"a.text-bold\"",")","page_project","=","[","project",".","text","for","project","in","project_info","if","not","project",".","text",".","endswith","(","'.github.io'",")","and","not","len","(","[","i","for","i","in","REPO_NAME_BLACKLIST","if","i","in","project",".","text",".","lower","(",")","]",")","]","return","page_project"],"url":"https:\/\/github.com\/5alt\/GitLeak\/blob\/43c64199a3c09c6357085e6acae9a2f38fea4d37\/GitLeak.py#L101-L110"}
5
+ {"nwo":"5alt\/GitLeak","sha":"43c64199a3c09c6357085e6acae9a2f38fea4d37","path":"GitLeak.py","language":"python","identifier":"GitPrey.sensitive_info_query","parameters":"(self, project_string)","argument_list":"","return_statement":"return code_dic","docstring":"Search sensitive information and sensitive file from projects\n :param project_string: Key words string for querying\n :returns: None","docstring_summary":"Search sensitive information and sensitive file from projects\n :param project_string: Key words string for querying\n :returns: None","docstring_tokens":["Search","sensitive","information","and","sensitive","file","from","projects",":","param","project_string",":","Key","words","string","for","querying",":","returns",":","None"],"function":"def sensitive_info_query(self, project_string):\n \"\"\"\n Search sensitive information and sensitive file from projects\n :param project_string: Key words string for querying\n :returns: None\n \"\"\"\n # Output code line with sensitive key words like username.\n info_sig_list = self.__pattern_db_list(INFO_DB)\n file_sig_list = self.__pattern_db_list(FILE_DB)\n file_pattern = \" filename:\" + \" filename:\".join(file_sig_list)\n code_dic = {}\n # Most five AND\/OR operators in search function.\n for i in xrange(len(info_sig_list)\/MAX_INFONUM+1):\n project_pattern = info_sig_list[i*MAX_INFONUM:i*MAX_INFONUM+MAX_INFONUM]\n\n if len(project_pattern) == 0: break\n\n repo_code_dic = self.__file_content_inspect(project_string, file_pattern, project_pattern)\n code_dic.update(repo_code_dic)\n return code_dic","function_tokens":["def","sensitive_info_query","(","self",",","project_string",")",":","# Output code line with sensitive key words like username.","info_sig_list","=","self",".","__pattern_db_list","(","INFO_DB",")","file_sig_list","=","self",".","__pattern_db_list","(","FILE_DB",")","file_pattern","=","\" filename:\"","+","\" filename:\"",".","join","(","file_sig_list",")","code_dic","=","{","}","# Most five AND\/OR operators in search function.","for","i","in","xrange","(","len","(","info_sig_list",")","\/","MAX_INFONUM","+","1",")",":","project_pattern","=","info_sig_list","[","i","*","MAX_INFONUM",":","i","*","MAX_INFONUM","+","MAX_INFONUM","]","if","len","(","project_pattern",")","==","0",":","break","repo_code_dic","=","self",".","__file_content_inspect","(","project_string",",","file_pattern",",","project_pattern",")","code_dic",".","update","(","repo_code_dic",")","return","code_dic"],"url":"https:\/\/github.com\/5alt\/GitLeak\/blob\/43c64199a3c09c6357085e6acae9a2f38fea4d37\/GitLeak.py#L112-L131"}
6
+ {"nwo":"5alt\/GitLeak","sha":"43c64199a3c09c6357085e6acae9a2f38fea4d37","path":"GitLeak.py","language":"python","identifier":"GitPrey.__file_content_inspect","parameters":"(self, project_string, file_pattern, project_pattern)","argument_list":"","return_statement":"return repo_code_dic","docstring":"Check sensitive code in particular project\n :param content_query_string: Content string for searching\n :param info_sig_match: information signature match regular\n :returns: None","docstring_summary":"Check sensitive code in particular project\n :param content_query_string: Content string for searching\n :param info_sig_match: information signature match regular\n :returns: None","docstring_tokens":["Check","sensitive","code","in","particular","project",":","param","content_query_string",":","Content","string","for","searching",":","param","info_sig_match",":","information","signature","match","regular",":","returns",":","None"],"function":"def __file_content_inspect(self, project_string, file_pattern, project_pattern):\n \"\"\"\n Check sensitive code in particular project\n :param content_query_string: Content string for searching\n :param info_sig_match: information signature match regular\n :returns: None\n \"\"\"\n if not project_pattern: return {}\n query_string = \" OR \".join(project_pattern)\n repo_file_dic = self.__file_name_inspect(query_string + project_string + file_pattern)\n repo_code_dic = {}\n for repo_name in repo_file_dic:\n self.__output_project_info(repo_name)\n repo_code_dic[repo_name] = {} # Set code line dictionary\n for file_url in repo_file_dic[repo_name]:\n file_url_output = \"[-] Compromise File: {file_url}\"\n file_print(file_url_output.format(file_url=file_url))\n repo_code_dic[repo_name][file_url] = [] # Set code block of project file\n # Read codes from raw file by replace host to raw host.\n code_file = self.__get_page_html(file_url.replace(HOST_NAME, RAW_NAME).replace('blob\/', ''))\n for code_line in code_file.split('\\n'):\n if len(repo_code_dic[repo_name][file_url]) > MAX_COUNT_SINGLE_FILE: break\n line_check = [i for i in LINE_MUSTHAVE if i in code_line]\n if not line_check: continue\n account_code = re.search('|'.join(project_pattern), code_line, re.I)\n if account_code:\n code = code_line.encode('utf-8').strip()\n if len(code) > MAX_LINELEN: continue\n code_print(code)\n repo_code_dic[repo_name][file_url].append(code)\n else:\n continue\n if len(repo_code_dic[repo_name][file_url]) > MAX_COUNT_SINGLE_FILE or not repo_code_dic[repo_name][file_url]:\n del repo_code_dic[repo_name][file_url]\n\n return repo_code_dic","function_tokens":["def","__file_content_inspect","(","self",",","project_string",",","file_pattern",",","project_pattern",")",":","if","not","project_pattern",":","return","{","}","query_string","=","\" OR \"",".","join","(","project_pattern",")","repo_file_dic","=","self",".","__file_name_inspect","(","query_string","+","project_string","+","file_pattern",")","repo_code_dic","=","{","}","for","repo_name","in","repo_file_dic",":","self",".","__output_project_info","(","repo_name",")","repo_code_dic","[","repo_name","]","=","{","}","# Set code line dictionary","for","file_url","in","repo_file_dic","[","repo_name","]",":","file_url_output","=","\"[-] Compromise File: {file_url}\"","file_print","(","file_url_output",".","format","(","file_url","=","file_url",")",")","repo_code_dic","[","repo_name","]","[","file_url","]","=","[","]","# Set code block of project file","# Read codes from raw file by replace host to raw host.","code_file","=","self",".","__get_page_html","(","file_url",".","replace","(","HOST_NAME",",","RAW_NAME",")",".","replace","(","'blob\/'",",","''",")",")","for","code_line","in","code_file",".","split","(","'\\n'",")",":","if","len","(","repo_code_dic","[","repo_name","]","[","file_url","]",")",">","MAX_COUNT_SINGLE_FILE",":","break","line_check","=","[","i","for","i","in","LINE_MUSTHAVE","if","i","in","code_line","]","if","not","line_check",":","continue","account_code","=","re",".","search","(","'|'",".","join","(","project_pattern",")",",","code_line",",","re",".","I",")","if","account_code",":","code","=","code_line",".","encode","(","'utf-8'",")",".","strip","(",")","if","len","(","code",")",">","MAX_LINELEN",":","continue","code_print","(","code",")","repo_code_dic","[","repo_name","]","[","file_url","]",".","append","(","code",")","else",":","continue","if","len","(","repo_code_dic","[","repo_name","]","[","file_url","]",")",">","MAX_COUNT_SINGLE_FILE","or","not","repo_code_dic","[","repo_name","]","[","file_url","]",":","del","repo_code_dic","[","repo_name","]","[","file_url","]","return","repo_code_dic"],"url":"https:\/\/github.com\/5alt\/GitLeak\/blob\/43c64199a3c09c6357085e6acae9a2f38fea4d37\/GitLeak.py#L133-L168"}
7
+ {"nwo":"5alt\/GitLeak","sha":"43c64199a3c09c6357085e6acae9a2f38fea4d37","path":"GitLeak.py","language":"python","identifier":"GitPrey.__file_name_inspect","parameters":"(self, file_query_string, print_mode=0)","argument_list":"","return_statement":"return repo_file_dic","docstring":"Inspect sensitive file in particular project\n :param file_query_string: File string for searching\n :returns: None","docstring_summary":"Inspect sensitive file in particular project\n :param file_query_string: File string for searching\n :returns: None","docstring_tokens":["Inspect","sensitive","file","in","particular","project",":","param","file_query_string",":","File","string","for","searching",":","returns",":","None"],"function":"def __file_name_inspect(self, file_query_string, print_mode=0):\n \"\"\"\n Inspect sensitive file in particular project\n :param file_query_string: File string for searching\n :returns: None\n \"\"\"\n page_num = 1\n repo_file_dic = {}\n while page_num <= SCAN_DEEP[SEARCH_LEVEL - 1]:\n check_url = self.search_url.format(page=page_num, keyword=quote(file_query_string))\n page_html = self.__get_page_html(check_url)\n project_html = BeautifulSoup(page_html, 'lxml')\n repo_list = project_html.select('div .d-inline-block.col-10 > a:nth-of-type(2)')\n if not repo_list:\n break\n # Handle file links for each project\n for repo in repo_list:\n file_url = repo.attrs['href']\n cur_project_name = \"\/\".join(file_url.split(\"\/\")[1:3])\n if cur_project_name not in repo_file_dic.keys():\n if print_mode:\n self.__output_project_info(cur_project_name)\n file_print(\"[-] Compromise File:\")\n repo_file_dic[cur_project_name] = [] # Set compromise project item\n if os.path.splitext(file_url)[1].lower() not in EXT_BLACKLIST:\n repo_file_dic[cur_project_name].append(HOST_NAME + file_url[1:]) # Set compromise project file item\n if print_mode:\n file_print(HOST_NAME + file_url[1:])\n page_num += 1\n\n return repo_file_dic","function_tokens":["def","__file_name_inspect","(","self",",","file_query_string",",","print_mode","=","0",")",":","page_num","=","1","repo_file_dic","=","{","}","while","page_num","<=","SCAN_DEEP","[","SEARCH_LEVEL","-","1","]",":","check_url","=","self",".","search_url",".","format","(","page","=","page_num",",","keyword","=","quote","(","file_query_string",")",")","page_html","=","self",".","__get_page_html","(","check_url",")","project_html","=","BeautifulSoup","(","page_html",",","'lxml'",")","repo_list","=","project_html",".","select","(","'div .d-inline-block.col-10 > a:nth-of-type(2)'",")","if","not","repo_list",":","break","# Handle file links for each project","for","repo","in","repo_list",":","file_url","=","repo",".","attrs","[","'href'","]","cur_project_name","=","\"\/\"",".","join","(","file_url",".","split","(","\"\/\"",")","[","1",":","3","]",")","if","cur_project_name","not","in","repo_file_dic",".","keys","(",")",":","if","print_mode",":","self",".","__output_project_info","(","cur_project_name",")","file_print","(","\"[-] Compromise File:\"",")","repo_file_dic","[","cur_project_name","]","=","[","]","# Set compromise project item","if","os",".","path",".","splitext","(","file_url",")","[","1","]",".","lower","(",")","not","in","EXT_BLACKLIST",":","repo_file_dic","[","cur_project_name","]",".","append","(","HOST_NAME","+","file_url","[","1",":","]",")","# Set compromise project file item","if","print_mode",":","file_print","(","HOST_NAME","+","file_url","[","1",":","]",")","page_num","+=","1","return","repo_file_dic"],"url":"https:\/\/github.com\/5alt\/GitLeak\/blob\/43c64199a3c09c6357085e6acae9a2f38fea4d37\/GitLeak.py#L170-L200"}
8
+ {"nwo":"5alt\/GitLeak","sha":"43c64199a3c09c6357085e6acae9a2f38fea4d37","path":"GitLeak.py","language":"python","identifier":"GitPrey.__pattern_db_list","parameters":"(file_path)","argument_list":"","return_statement":"return item_list","docstring":"Read file name pattern item from signature file\n :param file_path: Pattern file path\n :returns: Signature item list","docstring_summary":"Read file name pattern item from signature file\n :param file_path: Pattern file path\n :returns: Signature item list","docstring_tokens":["Read","file","name","pattern","item","from","signature","file",":","param","file_path",":","Pattern","file","path",":","returns",":","Signature","item","list"],"function":"def __pattern_db_list(file_path):\n \"\"\"\n Read file name pattern item from signature file\n :param file_path: Pattern file path\n :returns: Signature item list\n \"\"\"\n item_list = []\n with open(file_path, 'r') as pattern_file:\n item_line = pattern_file.readline()\n while item_line:\n item_list.append(item_line.strip())\n item_line = pattern_file.readline()\n return item_list","function_tokens":["def","__pattern_db_list","(","file_path",")",":","item_list","=","[","]","with","open","(","file_path",",","'r'",")","as","pattern_file",":","item_line","=","pattern_file",".","readline","(",")","while","item_line",":","item_list",".","append","(","item_line",".","strip","(",")",")","item_line","=","pattern_file",".","readline","(",")","return","item_list"],"url":"https:\/\/github.com\/5alt\/GitLeak\/blob\/43c64199a3c09c6357085e6acae9a2f38fea4d37\/GitLeak.py#L203-L215"}
9
+ {"nwo":"5alt\/GitLeak","sha":"43c64199a3c09c6357085e6acae9a2f38fea4d37","path":"GitLeak.py","language":"python","identifier":"GitPrey.__output_project_info","parameters":"(project)","argument_list":"","return_statement":"","docstring":"Output user information and project information of particular project\n :returns: None","docstring_summary":"Output user information and project information of particular project\n :returns: None","docstring_tokens":["Output","user","information","and","project","information","of","particular","project",":","returns",":","None"],"function":"def __output_project_info(project):\n \"\"\"\n Output user information and project information of particular project\n :returns: None\n \"\"\"\n user_name, project_name = project.split(r\"\/\")\n user_info = \"[+_+] User Nickname: {nickname}\"\n project_print(user_info.format(nickname=user_name))\n project_info = \"[+_+] Project Name: {name}\"\n project_print(project_info.format(name=project_name))\n project_info = \"[+_+] Project Link: {link}\"\n project_print(project_info.format(link=HOST_NAME + project))","function_tokens":["def","__output_project_info","(","project",")",":","user_name",",","project_name","=","project",".","split","(","r\"\/\"",")","user_info","=","\"[+_+] User Nickname: {nickname}\"","project_print","(","user_info",".","format","(","nickname","=","user_name",")",")","project_info","=","\"[+_+] Project Name: {name}\"","project_print","(","project_info",".","format","(","name","=","project_name",")",")","project_info","=","\"[+_+] Project Link: {link}\"","project_print","(","project_info",".","format","(","link","=","HOST_NAME","+","project",")",")"],"url":"https:\/\/github.com\/5alt\/GitLeak\/blob\/43c64199a3c09c6357085e6acae9a2f38fea4d37\/GitLeak.py#L218-L229"}
10
+ {"nwo":"5alt\/GitLeak","sha":"43c64199a3c09c6357085e6acae9a2f38fea4d37","path":"GitLeak.py","language":"python","identifier":"GitPrey.__auto_login","parameters":"(self, username, password)","argument_list":"","return_statement":"","docstring":"Get cookie for logining GitHub\n :returns: None","docstring_summary":"Get cookie for logining GitHub\n :returns: None","docstring_tokens":["Get","cookie","for","logining","GitHub",":","returns",":","None"],"function":"def __auto_login(self, username, password):\n \"\"\"\n Get cookie for logining GitHub\n :returns: None\n \"\"\"\n login_request = requests.Session()\n login_html = login_request.get(\"https:\/\/github.com\/login\", headers=self.headers)\n post_data = {}\n soup = BeautifulSoup(login_html.text, \"lxml\")\n input_items = soup.find_all('input')\n for item in input_items:\n post_data[item.get('name')] = item.get('value')\n post_data['login'], post_data['password'] = username, password\n login_request.post(\"https:\/\/github.com\/session\", data=post_data, headers=self.headers)\n self.cookies = login_request.cookies\n if self.cookies['logged_in'] == 'no':\n error_print('[!_!] ERROR INFO: Login Github failed, please check account in config file.')\n exit()","function_tokens":["def","__auto_login","(","self",",","username",",","password",")",":","login_request","=","requests",".","Session","(",")","login_html","=","login_request",".","get","(","\"https:\/\/github.com\/login\"",",","headers","=","self",".","headers",")","post_data","=","{","}","soup","=","BeautifulSoup","(","login_html",".","text",",","\"lxml\"",")","input_items","=","soup",".","find_all","(","'input'",")","for","item","in","input_items",":","post_data","[","item",".","get","(","'name'",")","]","=","item",".","get","(","'value'",")","post_data","[","'login'","]",",","post_data","[","'password'","]","=","username",",","password","login_request",".","post","(","\"https:\/\/github.com\/session\"",",","data","=","post_data",",","headers","=","self",".","headers",")","self",".","cookies","=","login_request",".","cookies","if","self",".","cookies","[","'logged_in'","]","==","'no'",":","error_print","(","'[!_!] ERROR INFO: Login Github failed, please check account in config file.'",")","exit","(",")"],"url":"https:\/\/github.com\/5alt\/GitLeak\/blob\/43c64199a3c09c6357085e6acae9a2f38fea4d37\/GitLeak.py#L231-L248"}
11
+ {"nwo":"5alt\/GitLeak","sha":"43c64199a3c09c6357085e6acae9a2f38fea4d37","path":"GitLeak.py","language":"python","identifier":"GitPrey.__get_page_html","parameters":"(self, url)","argument_list":"","return_statement":"","docstring":"Get parse html page from requesting url\n :param url: Requesting url\n :returns: Parsed html page","docstring_summary":"Get parse html page from requesting url\n :param url: Requesting url\n :returns: Parsed html page","docstring_tokens":["Get","parse","html","page","from","requesting","url",":","param","url",":","Requesting","url",":","returns",":","Parsed","html","page"],"function":"def __get_page_html(self, url):\n \"\"\"\n Get parse html page from requesting url\n :param url: Requesting url\n :returns: Parsed html page\n \"\"\"\n try:\n page_html = requests.get(url, headers=self.headers, cookies=self.cookies, timeout=SCAN_DEEP[SEARCH_LEVEL - 1])\n if page_html.status_code == 429:\n time.sleep(SCAN_DEEP[SEARCH_LEVEL - 1])\n self.__get_page_html(url)\n return page_html.text\n except requests.ConnectionError, e:\n error_print(\"[!_!] ERROR INFO: There is '%s' problem in requesting html page.\" % str(e))\n exit()\n except requests.ReadTimeout:\n return ''","function_tokens":["def","__get_page_html","(","self",",","url",")",":","try",":","page_html","=","requests",".","get","(","url",",","headers","=","self",".","headers",",","cookies","=","self",".","cookies",",","timeout","=","SCAN_DEEP","[","SEARCH_LEVEL","-","1","]",")","if","page_html",".","status_code","==","429",":","time",".","sleep","(","SCAN_DEEP","[","SEARCH_LEVEL","-","1","]",")","self",".","__get_page_html","(","url",")","return","page_html",".","text","except","requests",".","ConnectionError",",","e",":","error_print","(","\"[!_!] ERROR INFO: There is '%s' problem in requesting html page.\"","%","str","(","e",")",")","exit","(",")","except","requests",".","ReadTimeout",":","return","''"],"url":"https:\/\/github.com\/5alt\/GitLeak\/blob\/43c64199a3c09c6357085e6acae9a2f38fea4d37\/GitLeak.py#L250-L266"}
75team__SublimeJS.jsonl ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"75team\/SublimeJS","sha":"96e7d34ee1c3103b19e81debba3a4a934afc5028","path":"v8.py","language":"python","identifier":"init","parameters":"()","argument_list":"","return_statement":"","docstring":"Init sublime-v8 engine","docstring_summary":"Init sublime-v8 engine","docstring_tokens":["Init","sublime","-","v8","engine"],"function":"def init():\n\t\"Init sublime-v8 engine\"\n\n\t# setup environment for PyV8 loading\n\tpyv8_paths = [\n\t\tos.path.join(PACKAGES_PATH, 'PyV8'),\n\t\tos.path.join(PACKAGES_PATH, 'PyV8', pyv8loader.get_arch()),\n\t\tos.path.join(PACKAGES_PATH, 'PyV8', 'pyv8-%s' % pyv8loader.get_arch())\n\t]\n\n\tsys.path += pyv8_paths\n\n\t# unpack recently loaded binary, is exists\n\tfor p in pyv8_paths:\n\t\tpyv8loader.unpack_pyv8(p)\n\n\t###################################\n\t# if you need update PyV8, comment this\n\ttry:\n\t\timport PyV8\n\texcept:\n\t\tpass\n\t###################################\n\n\t# create JS environment\n\tdelegate = SublimeLoaderDelegate()\n\n\tpyv8loader.load(pyv8_paths[1], delegate)","function_tokens":["def","init","(",")",":","# setup environment for PyV8 loading","pyv8_paths","=","[","os",".","path",".","join","(","PACKAGES_PATH",",","'PyV8'",")",",","os",".","path",".","join","(","PACKAGES_PATH",",","'PyV8'",",","pyv8loader",".","get_arch","(",")",")",",","os",".","path",".","join","(","PACKAGES_PATH",",","'PyV8'",",","'pyv8-%s'","%","pyv8loader",".","get_arch","(",")",")","]","sys",".","path","+=","pyv8_paths","# unpack recently loaded binary, is exists","for","p","in","pyv8_paths",":","pyv8loader",".","unpack_pyv8","(","p",")","###################################","# if you need update PyV8, comment this","try",":","import","PyV8","except",":","pass","###################################","# create JS environment","delegate","=","SublimeLoaderDelegate","(",")","pyv8loader",".","load","(","pyv8_paths","[","1","]",",","delegate",")"],"url":"https:\/\/github.com\/75team\/SublimeJS\/blob\/96e7d34ee1c3103b19e81debba3a4a934afc5028\/v8.py#L179-L206"}
2
+ {"nwo":"75team\/SublimeJS","sha":"96e7d34ee1c3103b19e81debba3a4a934afc5028","path":"v8.py","language":"python","identifier":"SublimeLoaderDelegate.setting","parameters":"(self, name, default=None)","argument_list":"","return_statement":"return self.settings.get(name, default)","docstring":"Returns specified setting name","docstring_summary":"Returns specified setting name","docstring_tokens":["Returns","specified","setting","name"],"function":"def setting(self, name, default=None):\n\t\t\"Returns specified setting name\"\n\t\treturn self.settings.get(name, default)","function_tokens":["def","setting","(","self",",","name",",","default","=","None",")",":","return","self",".","settings",".","get","(","name",",","default",")"],"url":"https:\/\/github.com\/75team\/SublimeJS\/blob\/96e7d34ee1c3103b19e81debba3a4a934afc5028\/v8.py#L269-L271"}
3
+ {"nwo":"75team\/SublimeJS","sha":"96e7d34ee1c3103b19e81debba3a4a934afc5028","path":"SublimeJS\/core\/semver.py","language":"python","identifier":"parse","parameters":"(version)","argument_list":"","return_statement":"return verinfo","docstring":"Parse version to major, minor, patch, pre-release, build parts.","docstring_summary":"Parse version to major, minor, patch, pre-release, build parts.","docstring_tokens":["Parse","version","to","major","minor","patch","pre","-","release","build","parts","."],"function":"def parse(version):\n \"\"\"\n Parse version to major, minor, patch, pre-release, build parts.\n \"\"\"\n match = _REGEX.match(version)\n if match is None:\n raise ValueError('%s is not valid SemVer string' % version)\n\n verinfo = match.groupdict()\n\n verinfo['major'] = int(verinfo['major'])\n verinfo['minor'] = int(verinfo['minor'])\n verinfo['patch'] = int(verinfo['patch'] or '0')\n\n return verinfo","function_tokens":["def","parse","(","version",")",":","match","=","_REGEX",".","match","(","version",")","if","match","is","None",":","raise","ValueError","(","'%s is not valid SemVer string'","%","version",")","verinfo","=","match",".","groupdict","(",")","verinfo","[","'major'","]","=","int","(","verinfo","[","'major'","]",")","verinfo","[","'minor'","]","=","int","(","verinfo","[","'minor'","]",")","verinfo","[","'patch'","]","=","int","(","verinfo","[","'patch'","]","or","'0'",")","return","verinfo"],"url":"https:\/\/github.com\/75team\/SublimeJS\/blob\/96e7d34ee1c3103b19e81debba3a4a934afc5028\/SublimeJS\/core\/semver.py#L14-L28"}
4
+ {"nwo":"75team\/SublimeJS","sha":"96e7d34ee1c3103b19e81debba3a4a934afc5028","path":"SublimeJS\/core\/context.py","language":"python","identifier":"should_use_unicode","parameters":"()","argument_list":"","return_statement":"return use_unicode","docstring":"WinXP unable to eval JS in unicode object (while other OSes requires it)\n\tThis function checks if we have to use unicode when reading files","docstring_summary":"WinXP unable to eval JS in unicode object (while other OSes requires it)\n\tThis function checks if we have to use unicode when reading files","docstring_tokens":["WinXP","unable","to","eval","JS","in","unicode","object","(","while","other","OSes","requires","it",")","This","function","checks","if","we","have","to","use","unicode","when","reading","files"],"function":"def should_use_unicode():\n\t\"\"\"\n\tWinXP unable to eval JS in unicode object (while other OSes requires it)\n\tThis function checks if we have to use unicode when reading files\n\t\"\"\"\n\tctx = PyV8.JSContext()\n\tctx.enter()\n\tuse_unicode = True\n\ttry:\n\t\tctx.eval(u'(function(){return;})()')\n\texcept:\n\t\tuse_unicode = False\n\n\tctx.leave()\n\n\treturn use_unicode","function_tokens":["def","should_use_unicode","(",")",":","ctx","=","PyV8",".","JSContext","(",")","ctx",".","enter","(",")","use_unicode","=","True","try",":","ctx",".","eval","(","u'(function(){return;})()'",")","except",":","use_unicode","=","False","ctx",".","leave","(",")","return","use_unicode"],"url":"https:\/\/github.com\/75team\/SublimeJS\/blob\/96e7d34ee1c3103b19e81debba3a4a934afc5028\/SublimeJS\/core\/context.py#L23-L38"}
5
+ {"nwo":"75team\/SublimeJS","sha":"96e7d34ee1c3103b19e81debba3a4a934afc5028","path":"SublimeJS\/core\/child_process.py","language":"python","identifier":"_process","parameters":"(commands, callback=None, working_dir=None, wait_for_completion=None, **kwargs)","argument_list":"","return_statement":"","docstring":"Process one or more OS commands.","docstring_summary":"Process one or more OS commands.","docstring_tokens":["Process","one","or","more","OS","commands","."],"function":"def _process(commands, callback=None, working_dir=None, wait_for_completion=None, **kwargs):\n '''Process one or more OS commands.'''\n\n if wait_for_completion is None:\n wait_for_completion = False\n\n # We're expecting a list of commands, so if we only have one, convert\n # it to a list:\n #\n if isinstance(commands, str):\n commands = [commands]\n\n results = []\n\n # Windows needs STARTF_USESHOWWINDOW in order to start the process with a\n # hidden window.\n #\n # See:\n #\n # http:\/\/stackoverflow.com\/questions\/1016384\/cross-platform-subprocess-with-hidden-window\n #\n startupinfo = None\n if os.name == 'nt':\n startupinfo = subprocess.STARTUPINFO()\n startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\n\n # Now we can execute each command:\n #\n for command in commands:\n\n # Split the command properly, in case it has options and\n # parameters:\n #\n command = shlex.split(command)\n\n try:\n\n proc = subprocess.Popen(command,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n cwd=working_dir,\n startupinfo=startupinfo)\n\n # We're going to keep polling the command and either:\n #\n # 1. we get None to tell us that the command is still running, or;\n # 2. we get a return code to indicate that the command has finished.\n #\n return_code = None\n while return_code is None:\n return_code = proc.poll()\n\n # If there's no error then see what we got from the command:\n #\n if return_code is None or return_code == 0:\n r, _, _ = select.select([proc.stdout], [], [])\n if r:\n # Process whatever output we can get:\n #\n output = True\n while output:\n output = proc.stdout.readline().decode()\n\n # If the caller wants everything in one go, or\n # there is no callback function, then batch up\n # the output. Otherwise pass it back to the\n # caller as it becomes available:\n #\n if wait_for_completion is True or callback is None:\n results += output\n else:\n sublime.set_timeout_async(functools.partial(callback, *args, **kwargs), 0)\n\n except subprocess.CalledProcessError as e:\n\n sublime.set_timeout_async(functools.partial(callback, *args, **kwargs), 0)\n\n except OSError as e:\n\n if e.errno == 2:\n sublime.message_dialog('Command not found\\n\\nCommand is: %s' % command)\n else:\n raise e\n\n # Concatenate all of the results and return the value. If we've been\n # using the callback then just make one last call with 'None' to indicate\n # that we're finished:\n #\n result = ''.join(results)\n\n if callback is None:\n return result\n\n if wait_for_completion is True:\n sublime.set_timeout_async(functools.partial(callback, *args, **kwargs), 0)\n\n sublime.set_timeout_async(functools.partial(callback, *args, **kwargs), 0)","function_tokens":["def","_process","(","commands",",","callback","=","None",",","working_dir","=","None",",","wait_for_completion","=","None",",","*","*","kwargs",")",":","if","wait_for_completion","is","None",":","wait_for_completion","=","False","# We're expecting a list of commands, so if we only have one, convert","# it to a list:","#","if","isinstance","(","commands",",","str",")",":","commands","=","[","commands","]","results","=","[","]","# Windows needs STARTF_USESHOWWINDOW in order to start the process with a","# hidden window.","#","# See:","#","# http:\/\/stackoverflow.com\/questions\/1016384\/cross-platform-subprocess-with-hidden-window","#","startupinfo","=","None","if","os",".","name","==","'nt'",":","startupinfo","=","subprocess",".","STARTUPINFO","(",")","startupinfo",".","dwFlags","|=","subprocess",".","STARTF_USESHOWWINDOW","# Now we can execute each command:","#","for","command","in","commands",":","# Split the command properly, in case it has options and","# parameters:","#","command","=","shlex",".","split","(","command",")","try",":","proc","=","subprocess",".","Popen","(","command",",","stdin","=","subprocess",".","PIPE",",","stdout","=","subprocess",".","PIPE",",","stderr","=","subprocess",".","STDOUT",",","cwd","=","working_dir",",","startupinfo","=","startupinfo",")","# We're going to keep polling the command and either:","#","# 1. we get None to tell us that the command is still running, or;","# 2. we get a return code to indicate that the command has finished.","#","return_code","=","None","while","return_code","is","None",":","return_code","=","proc",".","poll","(",")","# If there's no error then see what we got from the command:","#","if","return_code","is","None","or","return_code","==","0",":","r",",","_",",","_","=","select",".","select","(","[","proc",".","stdout","]",",","[","]",",","[","]",")","if","r",":","# Process whatever output we can get:","#","output","=","True","while","output",":","output","=","proc",".","stdout",".","readline","(",")",".","decode","(",")","# If the caller wants everything in one go, or","# there is no callback function, then batch up","# the output. Otherwise pass it back to the","# caller as it becomes available:","#","if","wait_for_completion","is","True","or","callback","is","None",":","results","+=","output","else",":","sublime",".","set_timeout_async","(","functools",".","partial","(","callback",",","*","args",",","*","*","kwargs",")",",","0",")","except","subprocess",".","CalledProcessError","as","e",":","sublime",".","set_timeout_async","(","functools",".","partial","(","callback",",","*","args",",","*","*","kwargs",")",",","0",")","except","OSError","as","e",":","if","e",".","errno","==","2",":","sublime",".","message_dialog","(","'Command not found\\n\\nCommand is: %s'","%","command",")","else",":","raise","e","# Concatenate all of the results and return the value. If we've been","# using the callback then just make one last call with 'None' to indicate","# that we're finished:","#","result","=","''",".","join","(","results",")","if","callback","is","None",":","return","result","if","wait_for_completion","is","True",":","sublime",".","set_timeout_async","(","functools",".","partial","(","callback",",","*","args",",","*","*","kwargs",")",",","0",")","sublime",".","set_timeout_async","(","functools",".","partial","(","callback",",","*","args",",","*","*","kwargs",")",",","0",")"],"url":"https:\/\/github.com\/75team\/SublimeJS\/blob\/96e7d34ee1c3103b19e81debba3a4a934afc5028\/SublimeJS\/core\/child_process.py#L29-L126"}
6
+ {"nwo":"75team\/SublimeJS","sha":"96e7d34ee1c3103b19e81debba3a4a934afc5028","path":"SublimeJS\/loader\/pyv8loader.py","language":"python","identifier":"load","parameters":"(dest_path, delegate=None)","argument_list":"","return_statement":"","docstring":"Main function that attempts to load or update PyV8 binary.\n First, it loads list of available PyV8 modules and check if\n PyV8 should be downloaded or updated.\n @param dest_path: Path where PyV8 lib should be downloaded \n @param delegate: instance of LoaderDelegate that will receive\n loader progress events\n @returns: `True` if download progress was initiated","docstring_summary":"Main function that attempts to load or update PyV8 binary.\n First, it loads list of available PyV8 modules and check if\n PyV8 should be downloaded or updated.","docstring_tokens":["Main","function","that","attempts","to","load","or","update","PyV8","binary",".","First","it","loads","list","of","available","PyV8","modules","and","check","if","PyV8","should","be","downloaded","or","updated","."],"function":"def load(dest_path, delegate=None):\n \"\"\"\n Main function that attempts to load or update PyV8 binary.\n First, it loads list of available PyV8 modules and check if\n PyV8 should be downloaded or updated.\n @param dest_path: Path where PyV8 lib should be downloaded \n @param delegate: instance of LoaderDelegate that will receive\n loader progress events\n @returns: `True` if download progress was initiated\n \"\"\"\n if delegate is None:\n delegate = LoaderDelegate()\n\n config = get_loader_config(dest_path)\n\n if 'PyV8' in sys.modules and (config['skip_update'] or time.time() < config['last_update'] + CHECK_INTERVAL):\n # No need to load anything: user already has PyV8 binary\n # or decided to disable update process\n delegate.log('No need to update PyV8')\n if(delegate.on_ready):\n \tdelegate.on_ready()\n return False\n\n def on_complete(result, *args, **kwargs):\n if result is not None:\n # Most recent version was downloaded\n config['last_id'] = result \n if 'PyV8' not in sys.modules:\n # PyV8 is not loaded yet, we can safely unpack it \n unpack_pyv8(dest_path)\n\n config['last_update'] = time.time()\n save_loader_config(dest_path, config)\n delegate.on_complete(*args, **kwargs)\n\n # try to download most recent version of PyV8\n # As PyV8 for Sublime Text spreads the world, it's possible\n # that multiple distinct PyV8Loader's may start doing the same\n # job at the same time. In this case, we should check if there's\n # already a thread that load PyV8 and hook on existing thread\n # rather that creating a new one\n thread = None\n thread_exists = False\n for t in threading.enumerate():\n if hasattr(t, 'is_pyv8_thread'):\n print('PyV8: Reusing thread')\n thread = t\n thread_exists = True\n break\n\n if not thread:\n print('PyV8: Creating new thread')\n thread = PyV8Loader(get_arch(), dest_path, config, delegate=delegate)\n thread.start()\n\n delegate.on_start()\n \n # watch on download progress\n prog = ThreadProgress(thread, delegate, thread_exists)\n prog.on('complete', on_complete if not thread_exists else delegate.on_complete)\n prog.on('error', delegate.on_error)","function_tokens":["def","load","(","dest_path",",","delegate","=","None",")",":","if","delegate","is","None",":","delegate","=","LoaderDelegate","(",")","config","=","get_loader_config","(","dest_path",")","if","'PyV8'","in","sys",".","modules","and","(","config","[","'skip_update'","]","or","time",".","time","(",")","<","config","[","'last_update'","]","+","CHECK_INTERVAL",")",":","# No need to load anything: user already has PyV8 binary","# or decided to disable update process","delegate",".","log","(","'No need to update PyV8'",")","if","(","delegate",".","on_ready",")",":","delegate",".","on_ready","(",")","return","False","def","on_complete","(","result",",","*","args",",","*","*","kwargs",")",":","if","result","is","not","None",":","# Most recent version was downloaded","config","[","'last_id'","]","=","result","if","'PyV8'","not","in","sys",".","modules",":","# PyV8 is not loaded yet, we can safely unpack it ","unpack_pyv8","(","dest_path",")","config","[","'last_update'","]","=","time",".","time","(",")","save_loader_config","(","dest_path",",","config",")","delegate",".","on_complete","(","*","args",",","*","*","kwargs",")","# try to download most recent version of PyV8","# As PyV8 for Sublime Text spreads the world, it's possible","# that multiple distinct PyV8Loader's may start doing the same","# job at the same time. In this case, we should check if there's","# already a thread that load PyV8 and hook on existing thread","# rather that creating a new one","thread","=","None","thread_exists","=","False","for","t","in","threading",".","enumerate","(",")",":","if","hasattr","(","t",",","'is_pyv8_thread'",")",":","print","(","'PyV8: Reusing thread'",")","thread","=","t","thread_exists","=","True","break","if","not","thread",":","print","(","'PyV8: Creating new thread'",")","thread","=","PyV8Loader","(","get_arch","(",")",",","dest_path",",","config",",","delegate","=","delegate",")","thread",".","start","(",")","delegate",".","on_start","(",")","# watch on download progress","prog","=","ThreadProgress","(","thread",",","delegate",",","thread_exists",")","prog",".","on","(","'complete'",",","on_complete","if","not","thread_exists","else","delegate",".","on_complete",")","prog",".","on","(","'error'",",","delegate",".","on_error",")"],"url":"https:\/\/github.com\/75team\/SublimeJS\/blob\/96e7d34ee1c3103b19e81debba3a4a934afc5028\/SublimeJS\/loader\/pyv8loader.py#L34-L94"}
7
+ {"nwo":"75team\/SublimeJS","sha":"96e7d34ee1c3103b19e81debba3a4a934afc5028","path":"SublimeJS\/loader\/pyv8loader.py","language":"python","identifier":"get_arch","parameters":"()","argument_list":"","return_statement":"","docstring":"Returns architecture name for PyV8 binary","docstring_summary":"Returns architecture name for PyV8 binary","docstring_tokens":["Returns","architecture","name","for","PyV8","binary"],"function":"def get_arch():\n \"Returns architecture name for PyV8 binary\"\n suffix = is_python3 and '-p3' or ''\n p = lambda a: '%s%s' % (a, suffix)\n is_64bit = sys.maxsize > 2**32\n system_name = platform.system()\n if system_name == 'Darwin':\n try:\n if semver.match(platform.mac_ver()[0], '<10.7.0'):\n return p('mac106')\n except:\n pass\n\n return p('osx')\n if system_name == 'Windows':\n return p('win64') if is_64bit else p('win32')\n if system_name == 'Linux':\n return p('linux64') if is_64bit else p('linux32')","function_tokens":["def","get_arch","(",")",":","suffix","=","is_python3","and","'-p3'","or","''","p","=","lambda","a",":","'%s%s'","%","(","a",",","suffix",")","is_64bit","=","sys",".","maxsize",">","2","**","32","system_name","=","platform",".","system","(",")","if","system_name","==","'Darwin'",":","try",":","if","semver",".","match","(","platform",".","mac_ver","(",")","[","0","]",",","'<10.7.0'",")",":","return","p","(","'mac106'",")","except",":","pass","return","p","(","'osx'",")","if","system_name","==","'Windows'",":","return","p","(","'win64'",")","if","is_64bit","else","p","(","'win32'",")","if","system_name","==","'Linux'",":","return","p","(","'linux64'",")","if","is_64bit","else","p","(","'linux32'",")"],"url":"https:\/\/github.com\/75team\/SublimeJS\/blob\/96e7d34ee1c3103b19e81debba3a4a934afc5028\/SublimeJS\/loader\/pyv8loader.py#L96-L113"}
8
+ {"nwo":"75team\/SublimeJS","sha":"96e7d34ee1c3103b19e81debba3a4a934afc5028","path":"SublimeJS\/loader\/pyv8loader.py","language":"python","identifier":"LoaderDelegate.on_start","parameters":"(self, *args, **kwargs)","argument_list":"","return_statement":"","docstring":"Invoked when download process is initiated","docstring_summary":"Invoked when download process is initiated","docstring_tokens":["Invoked","when","download","process","is","initiated"],"function":"def on_start(self, *args, **kwargs):\n \"Invoked when download process is initiated\"\n pass","function_tokens":["def","on_start","(","self",",","*","args",",","*","*","kwargs",")",":","pass"],"url":"https:\/\/github.com\/75team\/SublimeJS\/blob\/96e7d34ee1c3103b19e81debba3a4a934afc5028\/SublimeJS\/loader\/pyv8loader.py#L239-L241"}
9
+ {"nwo":"75team\/SublimeJS","sha":"96e7d34ee1c3103b19e81debba3a4a934afc5028","path":"SublimeJS\/loader\/pyv8loader.py","language":"python","identifier":"LoaderDelegate.on_progress","parameters":"(self, *args, **kwargs)","argument_list":"","return_statement":"","docstring":"Invoked on download progress","docstring_summary":"Invoked on download progress","docstring_tokens":["Invoked","on","download","progress"],"function":"def on_progress(self, *args, **kwargs):\n \"Invoked on download progress\"\n pass","function_tokens":["def","on_progress","(","self",",","*","args",",","*","*","kwargs",")",":","pass"],"url":"https:\/\/github.com\/75team\/SublimeJS\/blob\/96e7d34ee1c3103b19e81debba3a4a934afc5028\/SublimeJS\/loader\/pyv8loader.py#L243-L245"}
10
+ {"nwo":"75team\/SublimeJS","sha":"96e7d34ee1c3103b19e81debba3a4a934afc5028","path":"SublimeJS\/loader\/pyv8loader.py","language":"python","identifier":"LoaderDelegate.on_complete","parameters":"(self, *args, **kwargs)","argument_list":"","return_statement":"","docstring":"Invoked when download process was finished successfully","docstring_summary":"Invoked when download process was finished successfully","docstring_tokens":["Invoked","when","download","process","was","finished","successfully"],"function":"def on_complete(self, *args, **kwargs):\n \"Invoked when download process was finished successfully\"\n pass","function_tokens":["def","on_complete","(","self",",","*","args",",","*","*","kwargs",")",":","pass"],"url":"https:\/\/github.com\/75team\/SublimeJS\/blob\/96e7d34ee1c3103b19e81debba3a4a934afc5028\/SublimeJS\/loader\/pyv8loader.py#L247-L249"}
11
+ {"nwo":"75team\/SublimeJS","sha":"96e7d34ee1c3103b19e81debba3a4a934afc5028","path":"SublimeJS\/loader\/pyv8loader.py","language":"python","identifier":"LoaderDelegate.on_error","parameters":"(self, *args, **kwargs)","argument_list":"","return_statement":"","docstring":"Invoked when error occured during download process","docstring_summary":"Invoked when error occured during download process","docstring_tokens":["Invoked","when","error","occured","during","download","process"],"function":"def on_error(self, *args, **kwargs):\n \"Invoked when error occured during download process\"\n pass","function_tokens":["def","on_error","(","self",",","*","args",",","*","*","kwargs",")",":","pass"],"url":"https:\/\/github.com\/75team\/SublimeJS\/blob\/96e7d34ee1c3103b19e81debba3a4a934afc5028\/SublimeJS\/loader\/pyv8loader.py#L251-L253"}
12
+ {"nwo":"75team\/SublimeJS","sha":"96e7d34ee1c3103b19e81debba3a4a934afc5028","path":"SublimeJS\/loader\/pyv8loader.py","language":"python","identifier":"LoaderDelegate.setting","parameters":"(self, name, default=None)","argument_list":"","return_statement":"return self.settings[name] if name in self.settings else default","docstring":"Returns specified setting name","docstring_summary":"Returns specified setting name","docstring_tokens":["Returns","specified","setting","name"],"function":"def setting(self, name, default=None):\n \"Returns specified setting name\"\n return self.settings[name] if name in self.settings else default","function_tokens":["def","setting","(","self",",","name",",","default","=","None",")",":","return","self",".","settings","[","name","]","if","name","in","self",".","settings","else","default"],"url":"https:\/\/github.com\/75team\/SublimeJS\/blob\/96e7d34ee1c3103b19e81debba3a4a934afc5028\/SublimeJS\/loader\/pyv8loader.py#L255-L257"}
AdguardTeam__AdGuardForSafari.jsonl ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/notarize.py","language":"python","identifier":"get_user_configuration","parameters":"()","argument_list":"","return_statement":"","docstring":"Reads developer configuration","docstring_summary":"Reads developer configuration","docstring_tokens":["Reads","developer","configuration"],"function":"def get_user_configuration():\n \"\"\"Reads developer configuration\n \"\"\"\n path = os.path.join(CURRENT_DIR, DEVCONFIG_PATH)\n if not os.path.exists(path):\n raise ValueError(\"{0} does not exist!\".format(path))\n\n with open(path, 'r') as file:\n data = file.read()\n config_json = json.loads(data)\n username = config_json[\"AC_USERNAME\"]\n keychain_record = config_json[\"AC_PASSWORD\"]\n return (username, keychain_record)","function_tokens":["def","get_user_configuration","(",")",":","path","=","os",".","path",".","join","(","CURRENT_DIR",",","DEVCONFIG_PATH",")","if","not","os",".","path",".","exists","(","path",")",":","raise","ValueError","(","\"{0} does not exist!\"",".","format","(","path",")",")","with","open","(","path",",","'r'",")","as","file",":","data","=","file",".","read","(",")","config_json","=","json",".","loads","(","data",")","username","=","config_json","[","\"AC_USERNAME\"","]","keychain_record","=","config_json","[","\"AC_PASSWORD\"","]","return","(","username",",","keychain_record",")"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/notarize.py#L26-L38"}
2
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/notarize.py","language":"python","identifier":"create_zip_archive","parameters":"(path)","argument_list":"","return_statement":"return zip_path","docstring":"Notary service accepts ZIP archives so we should prepare one","docstring_summary":"Notary service accepts ZIP archives so we should prepare one","docstring_tokens":["Notary","service","accepts","ZIP","archives","so","we","should","prepare","one"],"function":"def create_zip_archive(path):\n \"\"\"Notary service accepts ZIP archives so we should prepare one\n \"\"\"\n zip_path = os.path.join(TEMP_DIR, \"to_notarize.zip\")\n\n # Create a ZIP archive suitable for altool.\n result = subprocess.run([\n \"\/usr\/bin\/ditto\",\n \"-c\", \"-k\", \"--keepParent\",\n path,\n zip_path\n ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if result.returncode != 0:\n print(\"out: {0}\".format(result.stdout))\n print(\"out: {0}\".format(result.stderr))\n raise ChildProcessError(\"failed to find archive the archive\")\n\n print(\"Archive for notary: {0}\".format(zip_path))\n return zip_path","function_tokens":["def","create_zip_archive","(","path",")",":","zip_path","=","os",".","path",".","join","(","TEMP_DIR",",","\"to_notarize.zip\"",")","# Create a ZIP archive suitable for altool.","result","=","subprocess",".","run","(","[","\"\/usr\/bin\/ditto\"",",","\"-c\"",",","\"-k\"",",","\"--keepParent\"",",","path",",","zip_path","]",",","stdout","=","subprocess",".","PIPE",",","stderr","=","subprocess",".","PIPE",")","if","result",".","returncode","!=","0",":","print","(","\"out: {0}\"",".","format","(","result",".","stdout",")",")","print","(","\"out: {0}\"",".","format","(","result",".","stderr",")",")","raise","ChildProcessError","(","\"failed to find archive the archive\"",")","print","(","\"Archive for notary: {0}\"",".","format","(","zip_path",")",")","return","zip_path"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/notarize.py#L41-L59"}
3
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/notarize.py","language":"python","identifier":"get_notarization_info","parameters":"(request_uuid)","argument_list":"","return_statement":"","docstring":"Checks the status of the submission to the notary service\n\n Arguments:\n request_uuid -- ID of the submission","docstring_summary":"Checks the status of the submission to the notary service","docstring_tokens":["Checks","the","status","of","the","submission","to","the","notary","service"],"function":"def get_notarization_info(request_uuid):\n \"\"\"Checks the status of the submission to the notary service\n\n Arguments:\n request_uuid -- ID of the submission\n \"\"\"\n\n (account, keychain_record) = get_user_configuration()\n\n result = subprocess.run([\n \"xcrun\",\n \"altool\",\n \"--notarization-info\",\n request_uuid,\n \"-u\",\n account,\n \"-p\",\n \"@keychain:{0}\".format(keychain_record)\n ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n if result.returncode != 0:\n print(\"out: {0}\".format(result.stdout))\n raise ChildProcessError(\"failed to check the submission status\")\n\n for line_bytes in result.stdout.splitlines():\n line = line_bytes.decode(\"utf-8\").strip()\n if line.startswith(\"Status:\"):\n parts = line.split(\":\", 2)\n status = parts[1].strip()\n return status\n\n print(\"out: {0}\".format(result.stdout.decode(\"utf-8\")))\n raise ChildProcessError(\"got invalid response from the notary service\")","function_tokens":["def","get_notarization_info","(","request_uuid",")",":","(","account",",","keychain_record",")","=","get_user_configuration","(",")","result","=","subprocess",".","run","(","[","\"xcrun\"",",","\"altool\"",",","\"--notarization-info\"",",","request_uuid",",","\"-u\"",",","account",",","\"-p\"",",","\"@keychain:{0}\"",".","format","(","keychain_record",")","]",",","stdout","=","subprocess",".","PIPE",",","stderr","=","subprocess",".","STDOUT",")","if","result",".","returncode","!=","0",":","print","(","\"out: {0}\"",".","format","(","result",".","stdout",")",")","raise","ChildProcessError","(","\"failed to check the submission status\"",")","for","line_bytes","in","result",".","stdout",".","splitlines","(",")",":","line","=","line_bytes",".","decode","(","\"utf-8\"",")",".","strip","(",")","if","line",".","startswith","(","\"Status:\"",")",":","parts","=","line",".","split","(","\":\"",",","2",")","status","=","parts","[","1","]",".","strip","(",")","return","status","print","(","\"out: {0}\"",".","format","(","result",".","stdout",".","decode","(","\"utf-8\"",")",")",")","raise","ChildProcessError","(","\"got invalid response from the notary service\"",")"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/notarize.py#L80-L111"}
4
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/notarize.py","language":"python","identifier":"submit_to_notary","parameters":"(path, bundle_id)","argument_list":"","return_statement":"","docstring":"Submits the zip archive to the notary service.\n\n Returns RequestUUID that is necessary to staple the app once\n the notarization process is completed.","docstring_summary":"Submits the zip archive to the notary service.","docstring_tokens":["Submits","the","zip","archive","to","the","notary","service","."],"function":"def submit_to_notary(path, bundle_id):\n \"\"\"Submits the zip archive to the notary service.\n\n Returns RequestUUID that is necessary to staple the app once\n the notarization process is completed.\n \"\"\"\n print(\"Submitting {0} to the notary service\".format(path))\n (account, keychain_record) = get_user_configuration()\n\n result = subprocess.run([\n \"xcrun\",\n \"altool\",\n \"--notarize-app\",\n \"--primary-bundle-id\",\n bundle_id,\n \"--asc-provider\",\n DEVELOPMENT_TEAM,\n \"-u\",\n account,\n \"-p\",\n \"@keychain:{0}\".format(keychain_record),\n \"-f\",\n path,\n \"-t\",\n \"osx\"\n ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n if result.returncode != 0:\n print(\"out: {0}\".format(result.stdout))\n raise ChildProcessError(\"failed to submit the archive\")\n\n for line_bytes in result.stdout.splitlines():\n line = line_bytes.decode(\"utf-8\").strip()\n if line.startswith(\"RequestUUID\"):\n parts = line.split(\"=\", 2)\n request_uuid = parts[1].strip()\n return request_uuid\n\n print(\"out: {0}\".format(result.stdout.decode(\"utf-8\")))\n raise ChildProcessError(\"cannot find RequestUUID in the notary service response\")","function_tokens":["def","submit_to_notary","(","path",",","bundle_id",")",":","print","(","\"Submitting {0} to the notary service\"",".","format","(","path",")",")","(","account",",","keychain_record",")","=","get_user_configuration","(",")","result","=","subprocess",".","run","(","[","\"xcrun\"",",","\"altool\"",",","\"--notarize-app\"",",","\"--primary-bundle-id\"",",","bundle_id",",","\"--asc-provider\"",",","DEVELOPMENT_TEAM",",","\"-u\"",",","account",",","\"-p\"",",","\"@keychain:{0}\"",".","format","(","keychain_record",")",",","\"-f\"",",","path",",","\"-t\"",",","\"osx\"","]",",","stdout","=","subprocess",".","PIPE",",","stderr","=","subprocess",".","STDOUT",")","if","result",".","returncode","!=","0",":","print","(","\"out: {0}\"",".","format","(","result",".","stdout",")",")","raise","ChildProcessError","(","\"failed to submit the archive\"",")","for","line_bytes","in","result",".","stdout",".","splitlines","(",")",":","line","=","line_bytes",".","decode","(","\"utf-8\"",")",".","strip","(",")","if","line",".","startswith","(","\"RequestUUID\"",")",":","parts","=","line",".","split","(","\"=\"",",","2",")","request_uuid","=","parts","[","1","]",".","strip","(",")","return","request_uuid","print","(","\"out: {0}\"",".","format","(","result",".","stdout",".","decode","(","\"utf-8\"",")",")",")","raise","ChildProcessError","(","\"cannot find RequestUUID in the notary service response\"",")"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/notarize.py#L114-L152"}
5
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/notarize.py","language":"python","identifier":"notarize","parameters":"(path, bundle_id)","argument_list":"","return_statement":"return","docstring":"This function does the actual notary process\n\n Arguments:\n path -- path to the file or app to notarize","docstring_summary":"This function does the actual notary process","docstring_tokens":["This","function","does","the","actual","notary","process"],"function":"def notarize(path, bundle_id):\n \"\"\"This function does the actual notary process\n\n Arguments:\n path -- path to the file or app to notarize\n \"\"\"\n\n print(\"Start notarizing {0}\".format(path))\n\n path_for_notary = path\n if os.path.isdir(path):\n path_for_notary = create_zip_archive(path)\n\n request_uuid = submit_to_notary(path_for_notary, bundle_id)\n print(\"Request UUID is {0}, now we wait for the notarization to complete\".format(request_uuid))\n wait_until_success(request_uuid)\n\n print(\"Notarization is complete, now staple the app or file\")\n\n result = subprocess.run([\n \"xcrun\",\n \"stapler\",\n \"staple\",\n path\n ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n\n print(\"out: {0}\".format(result.stdout.decode(\"utf-8\")))\n\n if result.returncode != 0:\n raise ChildProcessError(\"failed to staple the archive\")\n\n return","function_tokens":["def","notarize","(","path",",","bundle_id",")",":","print","(","\"Start notarizing {0}\"",".","format","(","path",")",")","path_for_notary","=","path","if","os",".","path",".","isdir","(","path",")",":","path_for_notary","=","create_zip_archive","(","path",")","request_uuid","=","submit_to_notary","(","path_for_notary",",","bundle_id",")","print","(","\"Request UUID is {0}, now we wait for the notarization to complete\"",".","format","(","request_uuid",")",")","wait_until_success","(","request_uuid",")","print","(","\"Notarization is complete, now staple the app or file\"",")","result","=","subprocess",".","run","(","[","\"xcrun\"",",","\"stapler\"",",","\"staple\"",",","path","]",",","stdout","=","subprocess",".","PIPE",",","stderr","=","subprocess",".","STDOUT",")","print","(","\"out: {0}\"",".","format","(","result",".","stdout",".","decode","(","\"utf-8\"",")",")",")","if","result",".","returncode","!=","0",":","raise","ChildProcessError","(","\"failed to staple the archive\"",")","return"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/notarize.py#L155-L186"}
6
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/localization.py","language":"python","identifier":"changeEncoding","parameters":"(file)","argument_list":"","return_statement":"","docstring":"Changes encoding of file from UTF-16 to UTF-8","docstring_summary":"Changes encoding of file from UTF-16 to UTF-8","docstring_tokens":["Changes","encoding","of","file","from","UTF","-","16","to","UTF","-","8"],"function":"def changeEncoding(file):\n print(\"change encoding of file {0} from utf-16 to utf-8\".format(file))\n \"\"\" Changes encoding of file from UTF-16 to UTF-8\n \"\"\"\n with open(file, \"rb\") as f:\n with open(\"temp.strings\", \"wb\") as f2:\n content = f.read().decode('utf-16')\n f2.write(content.lstrip().encode('utf-8'))\n shutil.move(\"temp.strings\", file)","function_tokens":["def","changeEncoding","(","file",")",":","print","(","\"change encoding of file {0} from utf-16 to utf-8\"",".","format","(","file",")",")","with","open","(","file",",","\"rb\"",")","as","f",":","with","open","(","\"temp.strings\"",",","\"wb\"",")","as","f2",":","content","=","f",".","read","(",")",".","decode","(","'utf-16'",")","f2",".","write","(","content",".","lstrip","(",")",".","encode","(","'utf-8'",")",")","shutil",".","move","(","\"temp.strings\"",",","file",")"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/localization.py#L75-L83"}
7
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/localization.py","language":"python","identifier":"upload_file","parameters":"(path, format, language, file_name)","argument_list":"","return_statement":"return","docstring":"Uploads the specified file to the translation API\n\n Arguments:\n path -- path to the file to upload\n format -- format of the file (for instance, 'strings' or 'json')\n language -- file language\n file_name -- name of the file in the translation system","docstring_summary":"Uploads the specified file to the translation API","docstring_tokens":["Uploads","the","specified","file","to","the","translation","API"],"function":"def upload_file(path, format, language, file_name):\n \"\"\"Uploads the specified file to the translation API\n\n Arguments:\n path -- path to the file to upload\n format -- format of the file (for instance, 'strings' or 'json')\n language -- file language\n file_name -- name of the file in the translation system\n \"\"\"\n files = {\"file\": open(path, \"rb\")}\n values = {\n \"format\": format,\n \"language\": language,\n \"filename\": file_name,\n \"project\": TWOSKY_CONFIG[\"project_id\"]\n }\n\n print(\"Uploading {0}\/{1} to the translation system\".format(language, file_name))\n result = requests.post(API_UPLOAD_URL, files=files, data=values)\n result_text = result.text\n\n if result.status_code != 200:\n raise ConnectionError(\"Could not upload. Response status={0}\\n{1}\".format(result.status_code, result_text))\n\n print(\"Response: {0}\".format(result_text))\n result_json = json.loads(result_text)\n if result_json['ok'] != True:\n raise ConnectionError(\"Could not upload. Response status={0}\\n{1}\".format(result.status_code, result_text))\n return","function_tokens":["def","upload_file","(","path",",","format",",","language",",","file_name",")",":","files","=","{","\"file\"",":","open","(","path",",","\"rb\"",")","}","values","=","{","\"format\"",":","format",",","\"language\"",":","language",",","\"filename\"",":","file_name",",","\"project\"",":","TWOSKY_CONFIG","[","\"project_id\"","]","}","print","(","\"Uploading {0}\/{1} to the translation system\"",".","format","(","language",",","file_name",")",")","result","=","requests",".","post","(","API_UPLOAD_URL",",","files","=","files",",","data","=","values",")","result_text","=","result",".","text","if","result",".","status_code","!=","200",":","raise","ConnectionError","(","\"Could not upload. Response status={0}\\n{1}\"",".","format","(","result",".","status_code",",","result_text",")",")","print","(","\"Response: {0}\"",".","format","(","result_text",")",")","result_json","=","json",".","loads","(","result_text",")","if","result_json","[","'ok'","]","!=","True",":","raise","ConnectionError","(","\"Could not upload. Response status={0}\\n{1}\"",".","format","(","result",".","status_code",",","result_text",")",")","return"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/localization.py#L85-L113"}
8
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/localization.py","language":"python","identifier":"download_file","parameters":"(file_name, language, format, path)","argument_list":"","return_statement":"return","docstring":"Downloads the specified file from the translations system\n\n Arguments:\n file_name -- name of the file in the translations system\n language -- language to download\n format -- format of the file (for instance, 'strings' or 'json')\n path -- destination path where the file is to be written","docstring_summary":"Downloads the specified file from the translations system","docstring_tokens":["Downloads","the","specified","file","from","the","translations","system"],"function":"def download_file(file_name, language, format, path):\n \"\"\"Downloads the specified file from the translations system\n\n Arguments:\n file_name -- name of the file in the translations system\n language -- language to download\n format -- format of the file (for instance, 'strings' or 'json')\n path -- destination path where the file is to be written\n \"\"\"\n print(\"Downloading {0}\/{1} from the translation system\".format(language, file_name))\n\n params = {\n \"filename\": file_name,\n \"format\": format,\n \"project\": TWOSKY_CONFIG[\"project_id\"],\n \"language\": language\n }\n result = requests.get(API_DOWNLOAD_URL, params=params)\n if result.status_code != 200:\n raise ConnectionError(\"Could not download. Response status={0}\\n{1}\".format(result.status_code, result.text))\n\n target_dir = os.path.dirname(path)\n if not os.path.exists(target_dir):\n raise ValueError(\n \"Target directory does not exist: {0}, make sure that you've added this language in XCode\".format(target_dir))\n\n file = open(path, \"wb\")\n file.write(result.content)\n file.close()\n print(\"The file was downloaded to {0}\".format(path))\n return","function_tokens":["def","download_file","(","file_name",",","language",",","format",",","path",")",":","print","(","\"Downloading {0}\/{1} from the translation system\"",".","format","(","language",",","file_name",")",")","params","=","{","\"filename\"",":","file_name",",","\"format\"",":","format",",","\"project\"",":","TWOSKY_CONFIG","[","\"project_id\"","]",",","\"language\"",":","language","}","result","=","requests",".","get","(","API_DOWNLOAD_URL",",","params","=","params",")","if","result",".","status_code","!=","200",":","raise","ConnectionError","(","\"Could not download. Response status={0}\\n{1}\"",".","format","(","result",".","status_code",",","result",".","text",")",")","target_dir","=","os",".","path",".","dirname","(","path",")","if","not","os",".","path",".","exists","(","target_dir",")",":","raise","ValueError","(","\"Target directory does not exist: {0}, make sure that you've added this language in XCode\"",".","format","(","target_dir",")",")","file","=","open","(","path",",","\"wb\"",")","file",".","write","(","result",".","content",")","file",".","close","(",")","print","(","\"The file was downloaded to {0}\"",".","format","(","path",")",")","return"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/localization.py#L116-L146"}
9
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/localization.py","language":"python","identifier":"xib_to_strings","parameters":"(xib_path, strings_path)","argument_list":"","return_statement":"return","docstring":"Generates a strings file from the specified xib","docstring_summary":"Generates a strings file from the specified xib","docstring_tokens":["Generates","a","strings","file","from","the","specified","xib"],"function":"def xib_to_strings(xib_path, strings_path):\n \"\"\"Generates a strings file from the specified xib\"\"\"\n print(\"Generating {0} file from {1}\".format(strings_path, xib_path))\n result = subprocess.run([\n \"ibtool\",\n \"--generate-strings-file\",\n strings_path,\n xib_path\n ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n if len(result.stdout) > 0:\n print(\"ibtool stdout:\\n{0}\".format(result.stdout))\n\n if len(result.stderr) > 0:\n print(\"ibtool stderr:\\n{0}\".format(result.stderr))\n\n if result.returncode != 0:\n raise ChildProcessError(\n \"failed to generate the .strings file from {0}. Return code {1}.\".format(xib_path, result.returncode))\n\n if not os.path.exists(strings_path):\n raise FileNotFoundError(strings_path)\n\n changeEncoding(strings_path)\n\n # Finished generating strings\n return","function_tokens":["def","xib_to_strings","(","xib_path",",","strings_path",")",":","print","(","\"Generating {0} file from {1}\"",".","format","(","strings_path",",","xib_path",")",")","result","=","subprocess",".","run","(","[","\"ibtool\"",",","\"--generate-strings-file\"",",","strings_path",",","xib_path","]",",","stdout","=","subprocess",".","PIPE",",","stderr","=","subprocess",".","PIPE",")","if","len","(","result",".","stdout",")",">","0",":","print","(","\"ibtool stdout:\\n{0}\"",".","format","(","result",".","stdout",")",")","if","len","(","result",".","stderr",")",">","0",":","print","(","\"ibtool stderr:\\n{0}\"",".","format","(","result",".","stderr",")",")","if","result",".","returncode","!=","0",":","raise","ChildProcessError","(","\"failed to generate the .strings file from {0}. Return code {1}.\"",".","format","(","xib_path",",","result",".","returncode",")",")","if","not","os",".","path",".","exists","(","strings_path",")",":","raise","FileNotFoundError","(","strings_path",")","changeEncoding","(","strings_path",")","# Finished generating strings","return"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/localization.py#L149-L175"}
10
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/localization.py","language":"python","identifier":"strings_to_xib","parameters":"(strings_path, xib_path)","argument_list":"","return_statement":"return","docstring":"Imports strings from the .strings file to the specified .xib","docstring_summary":"Imports strings from the .strings file to the specified .xib","docstring_tokens":["Imports","strings","from","the",".","strings","file","to","the","specified",".","xib"],"function":"def strings_to_xib(strings_path, xib_path):\n \"\"\"Imports strings from the .strings file to the specified .xib\"\"\"\n print(\"Importing strings from {0} to {1}\".format(strings_path, xib_path))\n\n result = subprocess.run([\n \"ibtool\",\n \"--import-strings-file\",\n strings_path,\n xib_path,\n \"--write\",\n xib_path\n ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n if len(result.stdout) > 0:\n print(\"ibtool stdout:\\n{0}\".format(result.stdout))\n\n if len(result.stderr) > 0:\n print(\"ibtool stderr:\\n{0}\".format(result.stderr))\n\n if result.returncode != 0:\n raise ChildProcessError(\n \"failed to import strings from {0}. Return code {1}.\".format(strings_path, result.returncode))\n\n # Finished importing strings\n return","function_tokens":["def","strings_to_xib","(","strings_path",",","xib_path",")",":","print","(","\"Importing strings from {0} to {1}\"",".","format","(","strings_path",",","xib_path",")",")","result","=","subprocess",".","run","(","[","\"ibtool\"",",","\"--import-strings-file\"",",","strings_path",",","xib_path",",","\"--write\"",",","xib_path","]",",","stdout","=","subprocess",".","PIPE",",","stderr","=","subprocess",".","PIPE",")","if","len","(","result",".","stdout",")",">","0",":","print","(","\"ibtool stdout:\\n{0}\"",".","format","(","result",".","stdout",")",")","if","len","(","result",".","stderr",")",">","0",":","print","(","\"ibtool stderr:\\n{0}\"",".","format","(","result",".","stderr",")",")","if","result",".","returncode","!=","0",":","raise","ChildProcessError","(","\"failed to import strings from {0}. Return code {1}.\"",".","format","(","strings_path",",","result",".","returncode",")",")","# Finished importing strings","return"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/localization.py#L178-L202"}
11
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/localization.py","language":"python","identifier":"export_xib","parameters":"(path)","argument_list":"","return_statement":"return","docstring":"Uploads the specified XIB file to the translation system.\n This method first converts the file to the .strings format,\n and then uploads it to the translation system.","docstring_summary":"Uploads the specified XIB file to the translation system.\n This method first converts the file to the .strings format,\n and then uploads it to the translation system.","docstring_tokens":["Uploads","the","specified","XIB","file","to","the","translation","system",".","This","method","first","converts","the","file","to","the",".","strings","format","and","then","uploads","it","to","the","translation","system","."],"function":"def export_xib(path):\n \"\"\"Uploads the specified XIB file to the translation system.\n This method first converts the file to the .strings format,\n and then uploads it to the translation system.\n \"\"\"\n print(\"Exporting {0}\".format(path))\n\n if not os.path.exists(path):\n raise FileNotFoundError(path)\n\n file_name = os.path.basename(path)\n file_name_noext = os.path.splitext(file_name)[0]\n strings_file_name = \"{0}.strings\".format(file_name_noext)\n strings_path = os.path.join(TEMP_DIR, strings_file_name)\n\n # Now we should generate a `.strings` file from this XIB\n xib_to_strings(path, strings_path)\n\n # Now that strings file is generated, we can upload it\n upload_file(strings_path, \"strings\", API_BASELOCALE, strings_file_name)\n return","function_tokens":["def","export_xib","(","path",")",":","print","(","\"Exporting {0}\"",".","format","(","path",")",")","if","not","os",".","path",".","exists","(","path",")",":","raise","FileNotFoundError","(","path",")","file_name","=","os",".","path",".","basename","(","path",")","file_name_noext","=","os",".","path",".","splitext","(","file_name",")","[","0","]","strings_file_name","=","\"{0}.strings\"",".","format","(","file_name_noext",")","strings_path","=","os",".","path",".","join","(","TEMP_DIR",",","strings_file_name",")","# Now we should generate a `.strings` file from this XIB","xib_to_strings","(","path",",","strings_path",")","# Now that strings file is generated, we can upload it","upload_file","(","strings_path",",","\"strings\"",",","API_BASELOCALE",",","strings_file_name",")","return"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/localization.py#L205-L225"}
12
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/localization.py","language":"python","identifier":"export_localizable_file","parameters":"(path, locale, dir_name)","argument_list":"","return_statement":"return","docstring":"Uploads the specified localizable file to the translation system","docstring_summary":"Uploads the specified localizable file to the translation system","docstring_tokens":["Uploads","the","specified","localizable","file","to","the","translation","system"],"function":"def export_localizable_file(path, locale, dir_name):\n \"\"\"Uploads the specified localizable file to the translation system\"\"\"\n print(\"Exporting {0}\".format(path))\n\n if not os.path.exists(path):\n raise FileNotFoundError(path)\n\n file_name = os.path.basename(path)\n file_ext = os.path.splitext(file_name)[1][1:]\n\n if file_name == \"InfoPlist.strings\":\n file_name = INFO_PLIST_DICTIONARY[dir_name]\n\n # Now upload the file\n upload_file(path, file_ext, locale, file_name)\n return","function_tokens":["def","export_localizable_file","(","path",",","locale",",","dir_name",")",":","print","(","\"Exporting {0}\"",".","format","(","path",")",")","if","not","os",".","path",".","exists","(","path",")",":","raise","FileNotFoundError","(","path",")","file_name","=","os",".","path",".","basename","(","path",")","file_ext","=","os",".","path",".","splitext","(","file_name",")","[","1","]","[","1",":","]","if","file_name","==","\"InfoPlist.strings\"",":","file_name","=","INFO_PLIST_DICTIONARY","[","dir_name","]","# Now upload the file","upload_file","(","path",",","file_ext",",","locale",",","file_name",")","return"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/localization.py#L228-L243"}
13
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/localization.py","language":"python","identifier":"export_json_file","parameters":"(path, locale)","argument_list":"","return_statement":"return","docstring":"Uploads the specified json file to the translation system","docstring_summary":"Uploads the specified json file to the translation system","docstring_tokens":["Uploads","the","specified","json","file","to","the","translation","system"],"function":"def export_json_file(path, locale):\n \"\"\"Uploads the specified json file to the translation system\"\"\"\n print(\"Exporting {0}\".format(path))\n\n if not os.path.exists(path):\n raise FileNotFoundError(path)\n\n file_name = \"en.json\"\n file_ext = os.path.splitext(file_name)[1][1:]\n\n # Now upload the file\n upload_file(path, file_ext, locale, file_name)\n return","function_tokens":["def","export_json_file","(","path",",","locale",")",":","print","(","\"Exporting {0}\"",".","format","(","path",")",")","if","not","os",".","path",".","exists","(","path",")",":","raise","FileNotFoundError","(","path",")","file_name","=","\"en.json\"","file_ext","=","os",".","path",".","splitext","(","file_name",")","[","1","]","[","1",":","]","# Now upload the file","upload_file","(","path",",","file_ext",",","locale",",","file_name",")","return"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/localization.py#L246-L258"}
14
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/localization.py","language":"python","identifier":"import_localizable_file","parameters":"(path, locale, dir_name)","argument_list":"","return_statement":"return","docstring":"Imports the specified localizable file from the translation system","docstring_summary":"Imports the specified localizable file from the translation system","docstring_tokens":["Imports","the","specified","localizable","file","from","the","translation","system"],"function":"def import_localizable_file(path, locale, dir_name):\n \"\"\"Imports the specified localizable file from the translation system\"\"\"\n print(\"Importing {0}\".format(path))\n\n file_name = os.path.basename(path)\n file_ext = os.path.splitext(file_name)[1][1:]\n\n if file_name == \"InfoPlist.strings\":\n file_name = INFO_PLIST_DICTIONARY[dir_name]\n\n # Download the file\n download_file(file_name, locale, file_ext, path)\n return","function_tokens":["def","import_localizable_file","(","path",",","locale",",","dir_name",")",":","print","(","\"Importing {0}\"",".","format","(","path",")",")","file_name","=","os",".","path",".","basename","(","path",")","file_ext","=","os",".","path",".","splitext","(","file_name",")","[","1","]","[","1",":","]","if","file_name","==","\"InfoPlist.strings\"",":","file_name","=","INFO_PLIST_DICTIONARY","[","dir_name","]","# Download the file","download_file","(","file_name",",","locale",",","file_ext",",","path",")","return"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/localization.py#L261-L273"}
15
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/localization.py","language":"python","identifier":"import_json_file","parameters":"(path, locale)","argument_list":"","return_statement":"return","docstring":"Imports the specified json file from the translation system","docstring_summary":"Imports the specified json file from the translation system","docstring_tokens":["Imports","the","specified","json","file","from","the","translation","system"],"function":"def import_json_file(path, locale):\n \"\"\"Imports the specified json file from the translation system\"\"\"\n print(\"Importing {0}\".format(path))\n\n file_name = \"en.json\"\n file_ext = os.path.splitext(file_name)[1][1:]\n\n # Download the file\n download_file(file_name, locale, file_ext, path)\n return","function_tokens":["def","import_json_file","(","path",",","locale",")",":","print","(","\"Importing {0}\"",".","format","(","path",")",")","file_name","=","\"en.json\"","file_ext","=","os",".","path",".","splitext","(","file_name",")","[","1","]","[","1",":","]","# Download the file","download_file","(","file_name",",","locale",",","file_ext",",","path",")","return"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/localization.py#L275-L284"}
16
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/localization.py","language":"python","identifier":"workaround_json_file","parameters":"(file_path, locale, path)","argument_list":"","return_statement":"return","docstring":"We don't have some locales in xcode, but we need it for Electron, such as zh-cn, zh-tw\n So we gonna duplicate these files\n Referenced issue: https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/issues\/256","docstring_summary":"We don't have some locales in xcode, but we need it for Electron, such as zh-cn, zh-tw\n So we gonna duplicate these files\n Referenced issue: https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/issues\/256","docstring_tokens":["We","don","t","have","some","locales","in","xcode","but","we","need","it","for","Electron","such","as","zh","-","cn","zh","-","tw","So","we","gonna","duplicate","these","files","Referenced","issue",":","https",":","\/\/","github",".","com","\/","AdguardTeam","\/","AdGuardForSafari","\/","issues","\/","256"],"function":"def workaround_json_file(file_path, locale, path):\n \"\"\"We don't have some locales in xcode, but we need it for Electron, such as zh-cn, zh-tw\n So we gonna duplicate these files\n Referenced issue: https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/issues\/256\n \"\"\"\n\n ELECTRON_LOCALES_DICTIONARY = {\n 'zh-Hans' : 'zh-cn',\n 'zh-Hant' : 'zh-tw'\n }\n\n paired_locale = ELECTRON_LOCALES_DICTIONARY.get(locale, '')\n if paired_locale != \"\":\n print(\"Duplicate json for {0} - {1}\".format(locale, paired_locale))\n copy_path = os.path.join(CURRENT_DIR, BASE_PATH, path, \"{0}.json\".format(paired_locale))\n shutil.copyfile(file_path, copy_path)\n\n return","function_tokens":["def","workaround_json_file","(","file_path",",","locale",",","path",")",":","ELECTRON_LOCALES_DICTIONARY","=","{","'zh-Hans'",":","'zh-cn'",",","'zh-Hant'",":","'zh-tw'","}","paired_locale","=","ELECTRON_LOCALES_DICTIONARY",".","get","(","locale",",","''",")","if","paired_locale","!=","\"\"",":","print","(","\"Duplicate json for {0} - {1}\"",".","format","(","locale",",","paired_locale",")",")","copy_path","=","os",".","path",".","join","(","CURRENT_DIR",",","BASE_PATH",",","path",",","\"{0}.json\"",".","format","(","paired_locale",")",")","shutil",".","copyfile","(","file_path",",","copy_path",")","return"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/localization.py#L286-L303"}
17
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/localization.py","language":"python","identifier":"get_xib_translation_path","parameters":"(path, locale)","argument_list":"","return_statement":"return path","docstring":"Gets path to the XIB file translation given it's relative path\n\n For example, if path is 'ProgramLog\/Base.lproj\/AAProgramLog.xib' and locale is 'de',\n the translation path will be 'ProgramLog\/de.lproj\/AAProgramLog.strings'","docstring_summary":"Gets path to the XIB file translation given it's relative path","docstring_tokens":["Gets","path","to","the","XIB","file","translation","given","it","s","relative","path"],"function":"def get_xib_translation_path(path, locale):\n \"\"\"Gets path to the XIB file translation given it's relative path\n\n For example, if path is 'ProgramLog\/Base.lproj\/AAProgramLog.xib' and locale is 'de',\n the translation path will be 'ProgramLog\/de.lproj\/AAProgramLog.strings'\n \"\"\"\n\n path = path.replace(\"Base.lproj\", \"{0}.lproj\".format(locale))\n path = os.path.splitext(path)[0] + \".strings\"\n return path","function_tokens":["def","get_xib_translation_path","(","path",",","locale",")",":","path","=","path",".","replace","(","\"Base.lproj\"",",","\"{0}.lproj\"",".","format","(","locale",")",")","path","=","os",".","path",".","splitext","(","path",")","[","0","]","+","\".strings\"","return","path"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/localization.py#L306-L315"}
18
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/localization.py","language":"python","identifier":"export_localizations","parameters":"()","argument_list":"","return_statement":"return","docstring":"Entry point for the exporting localizations process","docstring_summary":"Entry point for the exporting localizations process","docstring_tokens":["Entry","point","for","the","exporting","localizations","process"],"function":"def export_localizations():\n \"\"\"Entry point for the exporting localizations process\"\"\"\n print(\"Start exporting localizations\")\n\n for path in XIB_FILES:\n file_path = os.path.join(CURRENT_DIR, BASE_PATH, path)\n export_xib(file_path)\n\n for path in LOCALIZABLE_FILES:\n file_name = os.path.basename(path)\n dir_name = os.path.dirname(path)\n file_path = os.path.join(CURRENT_DIR, BASE_PATH, dir_name, \"{0}.lproj\".format(API_BASELOCALE), file_name)\n export_localizable_file(file_path, API_BASELOCALE, dir_name)\n\n for path in JSON_FILES:\n file_path = os.path.join(CURRENT_DIR, BASE_PATH, path, \"{0}.json\".format(API_BASELOCALE))\n export_json_file(file_path, API_BASELOCALE)\n\n print(\"Finished exporting localizations\")\n return","function_tokens":["def","export_localizations","(",")",":","print","(","\"Start exporting localizations\"",")","for","path","in","XIB_FILES",":","file_path","=","os",".","path",".","join","(","CURRENT_DIR",",","BASE_PATH",",","path",")","export_xib","(","file_path",")","for","path","in","LOCALIZABLE_FILES",":","file_name","=","os",".","path",".","basename","(","path",")","dir_name","=","os",".","path",".","dirname","(","path",")","file_path","=","os",".","path",".","join","(","CURRENT_DIR",",","BASE_PATH",",","dir_name",",","\"{0}.lproj\"",".","format","(","API_BASELOCALE",")",",","file_name",")","export_localizable_file","(","file_path",",","API_BASELOCALE",",","dir_name",")","for","path","in","JSON_FILES",":","file_path","=","os",".","path",".","join","(","CURRENT_DIR",",","BASE_PATH",",","path",",","\"{0}.json\"",".","format","(","API_BASELOCALE",")",")","export_json_file","(","file_path",",","API_BASELOCALE",")","print","(","\"Finished exporting localizations\"",")","return"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/localization.py#L318-L337"}
19
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/localization.py","language":"python","identifier":"export_translations","parameters":"(locale)","argument_list":"","return_statement":"return","docstring":"Exports all existing translations to the specified locale\n to the translation system.","docstring_summary":"Exports all existing translations to the specified locale\n to the translation system.","docstring_tokens":["Exports","all","existing","translations","to","the","specified","locale","to","the","translation","system","."],"function":"def export_translations(locale):\n \"\"\"Exports all existing translations to the specified locale\n to the translation system.\"\"\"\n print(\"Start exporting translations to {0}\".format(locale))\n\n for path in XIB_FILES:\n translation_path = get_xib_translation_path(path, locale)\n file_path = os.path.join(CURRENT_DIR, BASE_PATH, translation_path)\n export_localizable_file(file_path, locale)\n\n for path in LOCALIZABLE_FILES:\n file_path = os.path.join(CURRENT_DIR, BASE_PATH, \"{0}.lproj\".format(locale), path)\n export_localizable_file(file_path, locale)\n\n for path in JSON_FILES:\n file_path = os.path.join(CURRENT_DIR, BASE_PATH, path, \"{0}.json\".format(locale))\n export_json_file(file_path, locale)\n\n print(\"Finished exporting translations to {0}\".format(locale))\n return","function_tokens":["def","export_translations","(","locale",")",":","print","(","\"Start exporting translations to {0}\"",".","format","(","locale",")",")","for","path","in","XIB_FILES",":","translation_path","=","get_xib_translation_path","(","path",",","locale",")","file_path","=","os",".","path",".","join","(","CURRENT_DIR",",","BASE_PATH",",","translation_path",")","export_localizable_file","(","file_path",",","locale",")","for","path","in","LOCALIZABLE_FILES",":","file_path","=","os",".","path",".","join","(","CURRENT_DIR",",","BASE_PATH",",","\"{0}.lproj\"",".","format","(","locale",")",",","path",")","export_localizable_file","(","file_path",",","locale",")","for","path","in","JSON_FILES",":","file_path","=","os",".","path",".","join","(","CURRENT_DIR",",","BASE_PATH",",","path",",","\"{0}.json\"",".","format","(","locale",")",")","export_json_file","(","file_path",",","locale",")","print","(","\"Finished exporting translations to {0}\"",".","format","(","locale",")",")","return"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/localization.py#L340-L359"}
20
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/localization.py","language":"python","identifier":"export_all_translations","parameters":"()","argument_list":"","return_statement":"return","docstring":"Entry point for the exporting ALL translations process","docstring_summary":"Entry point for the exporting ALL translations process","docstring_tokens":["Entry","point","for","the","exporting","ALL","translations","process"],"function":"def export_all_translations():\n \"\"\"Entry point for the exporting ALL translations process\"\"\"\n print(\"Start exporting ALL translations\")\n for locale in TWOSKY_CONFIG[\"languages\"]:\n export_translations(locale)\n print(\"Finished exporting ALL translations\")\n return","function_tokens":["def","export_all_translations","(",")",":","print","(","\"Start exporting ALL translations\"",")","for","locale","in","TWOSKY_CONFIG","[","\"languages\"","]",":","export_translations","(","locale",")","print","(","\"Finished exporting ALL translations\"",")","return"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/localization.py#L362-L368"}
21
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/localization.py","language":"python","identifier":"import_localization","parameters":"(locale)","argument_list":"","return_statement":"return","docstring":"Imports translations to the specified language","docstring_summary":"Imports translations to the specified language","docstring_tokens":["Imports","translations","to","the","specified","language"],"function":"def import_localization(locale):\n \"\"\"Imports translations to the specified language\"\"\"\n print(\"Start importing translations to {0}\".format(locale))\n\n for path in XIB_FILES:\n translation_path = get_xib_translation_path(path, locale)\n file_path = os.path.join(CURRENT_DIR, BASE_PATH, translation_path)\n import_localizable_file(file_path, locale, \"\")\n\n for path in LOCALIZABLE_FILES:\n file_name = os.path.basename(path)\n dir_name = os.path.dirname(path)\n file_path = os.path.join(CURRENT_DIR, BASE_PATH, dir_name, \"{0}.lproj\".format(locale), file_name)\n import_localizable_file(file_path, locale, dir_name)\n\n for path in JSON_FILES:\n file_path = os.path.join(CURRENT_DIR, BASE_PATH, path, \"{0}.json\".format(locale))\n import_json_file(file_path, locale)\n workaround_json_file(file_path, locale, path)\n\n print(\"Finished importing translations to {0}\".format(locale))\n return","function_tokens":["def","import_localization","(","locale",")",":","print","(","\"Start importing translations to {0}\"",".","format","(","locale",")",")","for","path","in","XIB_FILES",":","translation_path","=","get_xib_translation_path","(","path",",","locale",")","file_path","=","os",".","path",".","join","(","CURRENT_DIR",",","BASE_PATH",",","translation_path",")","import_localizable_file","(","file_path",",","locale",",","\"\"",")","for","path","in","LOCALIZABLE_FILES",":","file_name","=","os",".","path",".","basename","(","path",")","dir_name","=","os",".","path",".","dirname","(","path",")","file_path","=","os",".","path",".","join","(","CURRENT_DIR",",","BASE_PATH",",","dir_name",",","\"{0}.lproj\"",".","format","(","locale",")",",","file_name",")","import_localizable_file","(","file_path",",","locale",",","dir_name",")","for","path","in","JSON_FILES",":","file_path","=","os",".","path",".","join","(","CURRENT_DIR",",","BASE_PATH",",","path",",","\"{0}.json\"",".","format","(","locale",")",")","import_json_file","(","file_path",",","locale",")","workaround_json_file","(","file_path",",","locale",",","path",")","print","(","\"Finished importing translations to {0}\"",".","format","(","locale",")",")","return"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/localization.py#L371-L392"}
22
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/localization.py","language":"python","identifier":"import_localizations","parameters":"()","argument_list":"","return_statement":"return","docstring":"Entry point for the importing localizations process","docstring_summary":"Entry point for the importing localizations process","docstring_tokens":["Entry","point","for","the","importing","localizations","process"],"function":"def import_localizations():\n \"\"\"Entry point for the importing localizations process\"\"\"\n print(\"Start importing localizations\")\n for locale in TWOSKY_CONFIG[\"languages\"]:\n import_localization(locale)\n print(\"Finished importing localizations\")\n return","function_tokens":["def","import_localizations","(",")",":","print","(","\"Start importing localizations\"",")","for","locale","in","TWOSKY_CONFIG","[","\"languages\"","]",":","import_localization","(","locale",")","print","(","\"Finished importing localizations\"",")","return"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/localization.py#L395-L401"}
23
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/localization.py","language":"python","identifier":"update_strings","parameters":"()","argument_list":"","return_statement":"return","docstring":"Entry point for the updating strings from xibs process","docstring_summary":"Entry point for the updating strings from xibs process","docstring_tokens":["Entry","point","for","the","updating","strings","from","xibs","process"],"function":"def update_strings():\n \"\"\"Entry point for the updating strings from xibs process\"\"\"\n print(\"Start updating .strings files\")\n\n for path in XIB_FILES:\n strings_rel_path = get_xib_translation_path(path, API_BASELOCALE)\n strings_path = os.path.join(CURRENT_DIR, BASE_PATH, strings_rel_path)\n xib_path = os.path.join(CURRENT_DIR, BASE_PATH, path)\n xib_to_strings(xib_path, strings_path)\n\n print(\"Finished updating .strings files\")\n return","function_tokens":["def","update_strings","(",")",":","print","(","\"Start updating .strings files\"",")","for","path","in","XIB_FILES",":","strings_rel_path","=","get_xib_translation_path","(","path",",","API_BASELOCALE",")","strings_path","=","os",".","path",".","join","(","CURRENT_DIR",",","BASE_PATH",",","strings_rel_path",")","xib_path","=","os",".","path",".","join","(","CURRENT_DIR",",","BASE_PATH",",","path",")","xib_to_strings","(","xib_path",",","strings_path",")","print","(","\"Finished updating .strings files\"",")","return"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/localization.py#L404-L415"}
24
+ {"nwo":"AdguardTeam\/AdGuardForSafari","sha":"24c86196548d7d60cda17b54fd64b0478d6a9068","path":"Scripts\/localization.py","language":"python","identifier":"update_xibs","parameters":"()","argument_list":"","return_statement":"return","docstring":"Entry point for the updating xibs from strings process","docstring_summary":"Entry point for the updating xibs from strings process","docstring_tokens":["Entry","point","for","the","updating","xibs","from","strings","process"],"function":"def update_xibs():\n \"\"\"Entry point for the updating xibs from strings process\"\"\"\n print(\"Start updating .xib files\")\n\n for path in XIB_FILES:\n strings_rel_path = get_xib_translation_path(path, API_BASELOCALE)\n strings_path = os.path.join(CURRENT_DIR, BASE_PATH, strings_rel_path)\n xib_path = os.path.join(CURRENT_DIR, BASE_PATH, path)\n strings_to_xib(strings_path, xib_path)\n\n print(\"Finished updating .xib files\")\n return","function_tokens":["def","update_xibs","(",")",":","print","(","\"Start updating .xib files\"",")","for","path","in","XIB_FILES",":","strings_rel_path","=","get_xib_translation_path","(","path",",","API_BASELOCALE",")","strings_path","=","os",".","path",".","join","(","CURRENT_DIR",",","BASE_PATH",",","strings_rel_path",")","xib_path","=","os",".","path",".","join","(","CURRENT_DIR",",","BASE_PATH",",","path",")","strings_to_xib","(","strings_path",",","xib_path",")","print","(","\"Finished updating .xib files\"",")","return"],"url":"https:\/\/github.com\/AdguardTeam\/AdGuardForSafari\/blob\/24c86196548d7d60cda17b54fd64b0478d6a9068\/Scripts\/localization.py#L418-L429"}
AdguardTeam__AdguardBrowserExtension.jsonl ADDED
@@ -0,0 +1,2 @@
 
 
1
+ {"nwo":"AdguardTeam\/AdguardBrowserExtension","sha":"3304ba0ad4fe2f1c887f29bb580b801ea6b5363e","path":"changelog.py","language":"python","identifier":"get_args","parameters":"()","argument_list":"","return_statement":"return args","docstring":"Parses, validates and returns arguments, passed to the script","docstring_summary":"Parses, validates and returns arguments, passed to the script","docstring_tokens":["Parses","validates","and","returns","arguments","passed","to","the","script"],"function":"def get_args():\n \"\"\"Parses, validates and returns arguments, passed to the script\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--repo', dest='repo', action='store')\n parser.add_argument('--after_date', dest='after_date', action='store')\n parser.add_argument('--output', dest='output', action='store')\n parser.add_argument('--token', dest='token', action='store')\n args = parser.parse_args()\n if not args.repo:\n print 'Repo is not specified'\n sys.exit(1)\n\n if not args.after_date:\n print 'After date is not specified'\n sys.exit(1)\n\n if not args.output:\n print 'Output path is not specified'\n sys.exit(1)\n\n if not args.token:\n print 'Github token is not specified'\n sys.exit(1)\n\n print 'Args are: %s' %args\n return args","function_tokens":["def","get_args","(",")",":","parser","=","argparse",".","ArgumentParser","(",")","parser",".","add_argument","(","'--repo'",",","dest","=","'repo'",",","action","=","'store'",")","parser",".","add_argument","(","'--after_date'",",","dest","=","'after_date'",",","action","=","'store'",")","parser",".","add_argument","(","'--output'",",","dest","=","'output'",",","action","=","'store'",")","parser",".","add_argument","(","'--token'",",","dest","=","'token'",",","action","=","'store'",")","args","=","parser",".","parse_args","(",")","if","not","args",".","repo",":","print","'Repo is not specified'","sys",".","exit","(","1",")","if","not","args",".","after_date",":","print","'After date is not specified'","sys",".","exit","(","1",")","if","not","args",".","output",":","print","'Output path is not specified'","sys",".","exit","(","1",")","if","not","args",".","token",":","print","'Github token is not specified'","sys",".","exit","(","1",")","print","'Args are: %s'","%","args","return","args"],"url":"https:\/\/github.com\/AdguardTeam\/AdguardBrowserExtension\/blob\/3304ba0ad4fe2f1c887f29bb580b801ea6b5363e\/changelog.py#L21-L46"}
2
+ {"nwo":"AdguardTeam\/AdguardBrowserExtension","sha":"3304ba0ad4fe2f1c887f29bb580b801ea6b5363e","path":"changelog.py","language":"python","identifier":"get_gh_issue_summary","parameters":"(branch_name_parts, repo, token)","argument_list":"","return_statement":"return text","docstring":"Gets short summary for the specified branch_id, which is related to the github issue from the specified repo","docstring_summary":"Gets short summary for the specified branch_id, which is related to the github issue from the specified repo","docstring_tokens":["Gets","short","summary","for","the","specified","branch_id","which","is","related","to","the","github","issue","from","the","specified","repo"],"function":"def get_gh_issue_summary(branch_name_parts, repo, token):\n \"\"\"Gets short summary for the specified branch_id, which is related to the github issue from the specified repo\"\"\"\n issue_url = BASE_URL + repo + \"\/issues\/\" + branch_name_parts.group(3)\n req = urllib2.Request(\n url=issue_url,\n headers={\n 'User-Agent' : \"Mozilla\/5.0 (Windows NT 10.0) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/56.0.2924.87 Safari\/537.36\",\n 'Authorization' : 'token ' + token\n }\n )\n response = urllib2.urlopen(req)\n issue = json.loads(response.read())\n issue_type = ISSUE_TYPES.get(branch_name_parts.group(1), 'Fix')\n patch_name = branch_name_parts.group(4)\n\n text = '* [%s%s] %s: #%s\\r\\n' %(\n issue_type,\n '(regression)' if patch_name != '' else '',\n issue[\"title\"],\n issue[\"number\"]\n )\n return text","function_tokens":["def","get_gh_issue_summary","(","branch_name_parts",",","repo",",","token",")",":","issue_url","=","BASE_URL","+","repo","+","\"\/issues\/\"","+","branch_name_parts",".","group","(","3",")","req","=","urllib2",".","Request","(","url","=","issue_url",",","headers","=","{","'User-Agent'",":","\"Mozilla\/5.0 (Windows NT 10.0) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/56.0.2924.87 Safari\/537.36\"",",","'Authorization'",":","'token '","+","token","}",")","response","=","urllib2",".","urlopen","(","req",")","issue","=","json",".","loads","(","response",".","read","(",")",")","issue_type","=","ISSUE_TYPES",".","get","(","branch_name_parts",".","group","(","1",")",",","'Fix'",")","patch_name","=","branch_name_parts",".","group","(","4",")","text","=","'* [%s%s] %s: #%s\\r\\n'","%","(","issue_type",",","'(regression)'","if","patch_name","!=","''","else","''",",","issue","[","\"title\"","]",",","issue","[","\"number\"","]",")","return","text"],"url":"https:\/\/github.com\/AdguardTeam\/AdguardBrowserExtension\/blob\/3304ba0ad4fe2f1c887f29bb580b801ea6b5363e\/changelog.py#L48-L69"}
Alem__django-jfu.jsonl ADDED
@@ -0,0 +1,2 @@
 
 
1
+ {"nwo":"Alem\/django-jfu","sha":"f45025f0a6d4cbc8d7f4933a77da8468cd296159","path":"jfu\/http.py","language":"python","identifier":"upload_receive","parameters":"( request )","argument_list":"","return_statement":"return request.FILES['files[]'] if request.FILES else None","docstring":"Returns the file(s) uploaded by the user.","docstring_summary":"Returns the file(s) uploaded by the user.","docstring_tokens":["Returns","the","file","(","s",")","uploaded","by","the","user","."],"function":"def upload_receive( request ):\n \"\"\"\n Returns the file(s) uploaded by the user.\n \"\"\"\n return request.FILES['files[]'] if request.FILES else None","function_tokens":["def","upload_receive","(","request",")",":","return","request",".","FILES","[","'files[]'","]","if","request",".","FILES","else","None"],"url":"https:\/\/github.com\/Alem\/django-jfu\/blob\/f45025f0a6d4cbc8d7f4933a77da8468cd296159\/jfu\/http.py#L5-L9"}
2
+ {"nwo":"Alem\/django-jfu","sha":"f45025f0a6d4cbc8d7f4933a77da8468cd296159","path":"jfu\/templatetags\/jfutags.py","language":"python","identifier":"jfu","parameters":"(\n context,\n template_name = 'jfu\/upload_form.html',\n upload_handler_name = 'jfu_upload',\n *args, **kwargs\n )","argument_list":"","return_statement":"return t.render( Context( context ) )","docstring":"Displays a form for uploading files using jQuery File Upload.\n\n A user may use both a custom template or a custom upload-handling URL\n name by supplying values for template_name and upload_handler_name\n respectively.\n\n Any additionally supplied positional and keyword arguments are directly\n forwarded to the named custom upload-handling URL.","docstring_summary":"Displays a form for uploading files using jQuery File Upload.","docstring_tokens":["Displays","a","form","for","uploading","files","using","jQuery","File","Upload","."],"function":"def jfu(\n context,\n template_name = 'jfu\/upload_form.html',\n upload_handler_name = 'jfu_upload',\n *args, **kwargs\n ):\n \"\"\"\n Displays a form for uploading files using jQuery File Upload.\n\n A user may use both a custom template or a custom upload-handling URL\n name by supplying values for template_name and upload_handler_name\n respectively.\n\n Any additionally supplied positional and keyword arguments are directly\n forwarded to the named custom upload-handling URL.\n \"\"\"\n context.update( { \n 'JQ_OPEN' : '{%',\n 'JQ_CLOSE' : '%}',\n 'upload_handler_url': reverse(\n upload_handler_name, args = args, kwargs = kwargs\n ),\n } )\n\n # Use the request context variable, injected\n # by django.core.context_processors.request,\n # to generate the CSRF token.\n context.update( csrf( context.get('request') ) )\n\n t = loader.get_template( template_name )\n\n return t.render( Context( context ) )","function_tokens":["def","jfu","(","context",",","template_name","=","'jfu\/upload_form.html'",",","upload_handler_name","=","'jfu_upload'",",","*","args",",","*","*","kwargs",")",":","context",".","update","(","{","'JQ_OPEN'",":","'{%'",",","'JQ_CLOSE'",":","'%}'",",","'upload_handler_url'",":","reverse","(","upload_handler_name",",","args","=","args",",","kwargs","=","kwargs",")",",","}",")","# Use the request context variable, injected","# by django.core.context_processors.request,","# to generate the CSRF token.","context",".","update","(","csrf","(","context",".","get","(","'request'",")",")",")","t","=","loader",".","get_template","(","template_name",")","return","t",".","render","(","Context","(","context",")",")"],"url":"https:\/\/github.com\/Alem\/django-jfu\/blob\/f45025f0a6d4cbc8d7f4933a77da8468cd296159\/jfu\/templatetags\/jfutags.py#L8-L39"}
AlexAltea__unicorn.js.jsonl ADDED
@@ -0,0 +1,2 @@
 
 
1
+ {"nwo":"AlexAltea\/unicorn.js","sha":"6e998393d863a37659c09046d4835003e6554a35","path":"build.py","language":"python","identifier":"patchUnicornTCI","parameters":"()","argument_list":"","return_statement":"","docstring":"Patches Unicorn's QEMU fork to add the TCG Interpreter backend","docstring_summary":"Patches Unicorn's QEMU fork to add the TCG Interpreter backend","docstring_tokens":["Patches","Unicorn","s","QEMU","fork","to","add","the","TCG","Interpreter","backend"],"function":"def patchUnicornTCI():\n \"\"\"\n Patches Unicorn's QEMU fork to add the TCG Interpreter backend\n \"\"\"\n # Enable TCI\n replace(os.path.join(UNICORN_QEMU_DIR, \"configure\"), {\n \"strip_opt=\\\"yes\\\"\": \"strip_opt=\\\"yes\\\"\\ntcg_interpreter=\\\"yes\\\"\",\n \"# XXX: suppress that\": \"if test \\\"$tcg_interpreter\\\" = \\\"yes\\\" ; then\\n echo \\\"CONFIG_TCG_INTERPRETER=y\\\" >> $config_host_mak\\nfi\\n# XXX: suppress that\",\n \"if test \\\"$ARCH\\\" = \\\"sparc64\\\" ; then\": \"if test \\\"$tcg_interpreter\\\" = \\\"yes\\\"; then\\n QEMU_INCLUDES=\\\"-I\\$(SRC_PATH)\/tcg\/tci $QEMU_INCLUDES\\\"\\nelif test \\\"$ARCH\\\" = \\\"sparc64\\\" ; then\"\n })\n # Add executable permissions for the new configure file\n path = os.path.join(UNICORN_QEMU_DIR, \"configure\")\n st = os.stat(path)\n os.chmod(path, st.st_mode | stat.S_IEXEC)\n # Copy missing TCI source files and patch them with Unicorn updates\n copytree(ORIGINAL_QEMU_DIR, UNICORN_QEMU_DIR)\n replace(os.path.join(UNICORN_QEMU_DIR, \"tcg\/tci\/tcg-target.c\"), {\n \"tcg_target_available_regs\": \"s->tcg_target_available_regs\",\n \"tcg_target_call_clobber_regs\": \"s->tcg_target_call_clobber_regs\",\n \"tcg_add_target_add_op_defs(\": \"tcg_add_target_add_op_defs(s, \",\n })\n replace(os.path.join(UNICORN_QEMU_DIR, \"tcg\/tci\/tcg-target.h\"), {\n \"#define tcg_qemu_tb_exec\": \"\/\/#define tcg_qemu_tb_exec\",\n })\n # Add TCI to Makefile.targets\n insert(os.path.join(UNICORN_QEMU_DIR, \"Makefile.target\"),\n \"obj-y += tcg\/tcg.o tcg\/optimize.o\", [\n \"obj-$(CONFIG_TCG_INTERPRETER) += tci.o\"\n ]\n )\n # Add TCI symbols\n insert(os.path.join(UNICORN_QEMU_DIR, \"header_gen.py\"),\n \"symbols = (\", [\n \" 'tci_tb_ptr',\",\n \" 'tcg_qemu_tb_exec',\",\n ]\n )\n # Update platform headers with new symbols\n cmd = \"bash -c \\\"cd \" + UNICORN_QEMU_DIR + \" && .\/gen_all_header.sh\\\"\"\n os.system(cmd)","function_tokens":["def","patchUnicornTCI","(",")",":","# Enable TCI","replace","(","os",".","path",".","join","(","UNICORN_QEMU_DIR",",","\"configure\"",")",",","{","\"strip_opt=\\\"yes\\\"\"",":","\"strip_opt=\\\"yes\\\"\\ntcg_interpreter=\\\"yes\\\"\"",",","\"# XXX: suppress that\"",":","\"if test \\\"$tcg_interpreter\\\" = \\\"yes\\\" ; then\\n echo \\\"CONFIG_TCG_INTERPRETER=y\\\" >> $config_host_mak\\nfi\\n# XXX: suppress that\"",",","\"if test \\\"$ARCH\\\" = \\\"sparc64\\\" ; then\"",":","\"if test \\\"$tcg_interpreter\\\" = \\\"yes\\\"; then\\n QEMU_INCLUDES=\\\"-I\\$(SRC_PATH)\/tcg\/tci $QEMU_INCLUDES\\\"\\nelif test \\\"$ARCH\\\" = \\\"sparc64\\\" ; then\"","}",")","# Add executable permissions for the new configure file","path","=","os",".","path",".","join","(","UNICORN_QEMU_DIR",",","\"configure\"",")","st","=","os",".","stat","(","path",")","os",".","chmod","(","path",",","st",".","st_mode","|","stat",".","S_IEXEC",")","# Copy missing TCI source files and patch them with Unicorn updates","copytree","(","ORIGINAL_QEMU_DIR",",","UNICORN_QEMU_DIR",")","replace","(","os",".","path",".","join","(","UNICORN_QEMU_DIR",",","\"tcg\/tci\/tcg-target.c\"",")",",","{","\"tcg_target_available_regs\"",":","\"s->tcg_target_available_regs\"",",","\"tcg_target_call_clobber_regs\"",":","\"s->tcg_target_call_clobber_regs\"",",","\"tcg_add_target_add_op_defs(\"",":","\"tcg_add_target_add_op_defs(s, \"",",","}",")","replace","(","os",".","path",".","join","(","UNICORN_QEMU_DIR",",","\"tcg\/tci\/tcg-target.h\"",")",",","{","\"#define tcg_qemu_tb_exec\"",":","\"\/\/#define tcg_qemu_tb_exec\"",",","}",")","# Add TCI to Makefile.targets","insert","(","os",".","path",".","join","(","UNICORN_QEMU_DIR",",","\"Makefile.target\"",")",",","\"obj-y += tcg\/tcg.o tcg\/optimize.o\"",",","[","\"obj-$(CONFIG_TCG_INTERPRETER) += tci.o\"","]",")","# Add TCI symbols","insert","(","os",".","path",".","join","(","UNICORN_QEMU_DIR",",","\"header_gen.py\"",")",",","\"symbols = (\"",",","[","\" 'tci_tb_ptr',\"",",","\" 'tcg_qemu_tb_exec',\"",",","]",")","# Update platform headers with new symbols","cmd","=","\"bash -c \\\"cd \"","+","UNICORN_QEMU_DIR","+","\" && .\/gen_all_header.sh\\\"\"","os",".","system","(","cmd",")"],"url":"https:\/\/github.com\/AlexAltea\/unicorn.js\/blob\/6e998393d863a37659c09046d4835003e6554a35\/build.py#L340-L379"}
2
+ {"nwo":"AlexAltea\/unicorn.js","sha":"6e998393d863a37659c09046d4835003e6554a35","path":"build.py","language":"python","identifier":"patchUnicornJS","parameters":"()","argument_list":"","return_statement":"","docstring":"Patches Unicorn files to target JavaScript","docstring_summary":"Patches Unicorn files to target JavaScript","docstring_tokens":["Patches","Unicorn","files","to","target","JavaScript"],"function":"def patchUnicornJS():\n \"\"\"\n Patches Unicorn files to target JavaScript\n \"\"\"\n # Disable unnecessary options\n replace(os.path.join(UNICORN_DIR, \"config.mk\"), {\n \"UNICORN_DEBUG ?= yes\": \"UNICORN_DEBUG ?= no\",\n \"UNICORN_SHARED ?= yes\": \"UNICORN_SHARED ?= no\",\n })\n # Ensure QEMU's object files have different base names\n name = \"rename_objects.py\"\n with open(os.path.join(UNICORN_DIR, name), \"wt\") as f:\n f.write(\"\")\n replace(os.path.join(UNICORN_DIR, \"Makefile\"), {\n \"$(MAKE) -C qemu $(SMP_MFLAGS)\":\n \"$(MAKE) -C qemu $(SMP_MFLAGS)\\r\\n\\t@python \" + name,\n '\t.\/configure --cc=\"${CC}\" --extra-cflags=\"$(UNICORN_CFLAGS)\" --target-list=\"$(UNICORN_TARGETS)\" ${UNICORN_QEMU_FLAGS}':\n '\t.\/configure --cc=\"${CC}\" --extra-cflags=\"$(UNICORN_CFLAGS)\" --target-list=\"$(UNICORN_TARGETS)\" ${UNICORN_QEMU_FLAGS} --disable-stack-protector --cpu=i386',\n })\n # Replace sigsetjmp\/siglongjump with setjmp\/longjmp\n replace(os.path.join(UNICORN_QEMU_DIR, \"cpu-exec.c\"), {\n \"sigsetjmp(cpu->jmp_env, 0)\": \"setjmp(cpu->jmp_env)\",\n \"siglongjmp(cpu->jmp_env, 1)\": \"longjmp(cpu->jmp_env, 1)\",\n })\n # Fix Glib function pointer issues\n replace(os.path.join(UNICORN_QEMU_DIR, \"glib_compat.c\"), {\n \"(GCompareDataFunc) compare_func) (l1->data, l2->data, user_data)\":\n \"(GCompareFunc) compare_func) (l1->data, l2->data)\",\n })\n # Fix QEMU function pointer issues\n replace(os.path.join(UNICORN_QEMU_DIR, \"include\/exec\/helper-proto.h\"), {\n # Adapter helpers\n \"#include <exec\/helper-head.h>\":\n \"#include <exec\/helper-head.h>\\n\" + PATCH_HELPER_ADAPTER_PROTO,\n # Declare adapters\n \"#define DEF_HELPER_FLAGS_0(name, flags, ret) \\\\\":\"\"\"\n #define DEF_HELPER_FLAGS_0(name, flags, ret) \\\\\n GEN_ADAPTER_DECLARE(name) \\\\\"\"\",\n \"#define DEF_HELPER_FLAGS_1(name, flags, ret, t1) \\\\\":\"\"\"\n #define DEF_HELPER_FLAGS_1(name, flags, ret, t1) \\\\\n GEN_ADAPTER_DECLARE(name) \\\\\"\"\",\n \"#define DEF_HELPER_FLAGS_2(name, flags, ret, t1, t2) \\\\\":\"\"\"\n #define DEF_HELPER_FLAGS_2(name, flags, ret, t1, t2) \\\\\n GEN_ADAPTER_DECLARE(name) \\\\\"\"\",\n \"#define DEF_HELPER_FLAGS_3(name, flags, ret, t1, t2, t3) \\\\\":\"\"\"\n #define DEF_HELPER_FLAGS_3(name, flags, ret, t1, t2, t3) \\\\\n GEN_ADAPTER_DECLARE(name) \\\\\"\"\",\n \"#define DEF_HELPER_FLAGS_4(name, flags, ret, t1, t2, t3, t4) \\\\\":\"\"\"\n #define DEF_HELPER_FLAGS_4(name, flags, ret, t1, t2, t3, t4) \\\\\n GEN_ADAPTER_DECLARE(name) \\\\\"\"\",\n \"#define DEF_HELPER_FLAGS_5(name, flags, ret, t1, t2, t3, t4, t5) \\\\\":\"\"\"\n #define DEF_HELPER_FLAGS_5(name, flags, ret, t1, t2, t3, t4, t5) \\\\\n GEN_ADAPTER_DECLARE(name) \\\\\"\"\",\n })\n replace(os.path.join(UNICORN_QEMU_DIR, \"include\/exec\/helper-gen.h\"), {\n # Adapter helpers\n \"#include <exec\/helper-head.h>\":\n \"#include <exec\/helper-head.h>\\n\" + PATCH_HELPER_ADAPTER_GEN,\n # Generate calls to adapters instead\n \"tcg_gen_callN(tcg_ctx, HELPER(name)\":\n \"tcg_gen_callN(tcg_ctx, glue(adapter_helper_, name)\",\n # Define adapters\n \"#define DEF_HELPER_FLAGS_0(name, flags, ret) \\\\\":\"\"\"\n #define DEF_HELPER_FLAGS_0(name, flags, ret) \\\\\n GEN_ADAPTER_0(name, ret) \\\\\"\"\",\n \"#define DEF_HELPER_FLAGS_1(name, flags, ret, t1) \\\\\":\"\"\"\n #define DEF_HELPER_FLAGS_1(name, flags, ret, t1) \\\\\n GEN_ADAPTER_1(name, ret, t1) \\\\\"\"\",\n \"#define DEF_HELPER_FLAGS_2(name, flags, ret, t1, t2) \\\\\":\"\"\"\n #define DEF_HELPER_FLAGS_2(name, flags, ret, t1, t2) \\\\\n GEN_ADAPTER_2(name, ret, t1, t2) \\\\\"\"\",\n \"#define DEF_HELPER_FLAGS_3(name, flags, ret, t1, t2, t3) \\\\\":\"\"\"\n #define DEF_HELPER_FLAGS_3(name, flags, ret, t1, t2, t3) \\\\\n GEN_ADAPTER_3(name, ret, t1, t2, t3) \\\\\"\"\",\n \"#define DEF_HELPER_FLAGS_4(name, flags, ret, t1, t2, t3, t4) \\\\\":\"\"\"\n #define DEF_HELPER_FLAGS_4(name, flags, ret, t1, t2, t3, t4) \\\\\n GEN_ADAPTER_4(name, ret, t1, t2, t3, t4) \\\\\"\"\",\n \"#define DEF_HELPER_FLAGS_5(name, flags, ret, t1, t2, t3, t4, t5) \\\\\":\"\"\"\n #define DEF_HELPER_FLAGS_5(name, flags, ret, t1, t2, t3, t4, t5) \\\\\n GEN_ADAPTER_5(name, ret, t1, t2, t3, t4, t5) \\\\\"\"\",\n })\n replace(os.path.join(UNICORN_QEMU_DIR, \"tcg-runtime.c\"), {\n # Adapter helpers\n '#include \"exec\/helper-head.h\"':\n '#include \"exec\/helper-head.h\"\\n' +\n PATCH_HELPER_ADAPTER_GEN,\n # Add uc_tracecode to globals\n '#include \"tcg-runtime.h\"':\"\"\"\n #undef DEF_HELPER_FLAGS_2\n #define DEF_HELPER_FLAGS_2(name, flags, ret, t1, t2) \\\\\n dh_ctype(ret) HELPER(name) (dh_ctype(t1), dh_ctype(t2)); \\\\\n uint64_t glue(adapter_helper_, name)(GEN_ADAPTER_ARGS); \\\\\n GEN_ADAPTER_2_DEFINE(name, ret, t1, t2)\n #define DEF_HELPER_FLAGS_4(name, flags, ret, t1, t2, t3, t4) \\\\\n dh_ctype(ret) HELPER(name) (dh_ctype(t1), dh_ctype(t2), dh_ctype(t3), dh_ctype(t4)); \\\\\n uint64_t glue(adapter_helper_, name)(GEN_ADAPTER_ARGS); \\\\\n GEN_ADAPTER_4_DEFINE(name, ret, t1, t2, t3, t4)\n DEF_HELPER_4(uc_tracecode, void, i32, i32, ptr, i64)\n #include \"tcg-runtime.h\"\n \"\"\",\n })\n replace(os.path.join(UNICORN_QEMU_DIR, \"include\/exec\/helper-tcg.h\"), {\n \"func = HELPER(NAME)\":\n \"func = glue(adapter_helper_, NAME)\"\n })\n # Add arch-suffixes to adapters\n header_gen_patched = False\n with open(os.path.join(UNICORN_QEMU_DIR, \"header_gen.py\"), 'r') as f:\n if 'adapter_' in f.read():\n header_gen_patched = True\n if header_gen_patched == False:\n os.remove(os.path.join(UNICORN_QEMU_DIR, \"header_gen.py.bak\"))\n replace(os.path.join(UNICORN_QEMU_DIR, \"header_gen.py\"), {\n ' print(\"#define %s %s_%s\" %(s, s, arch))':\n ' print(\"#define %s %s_%s\" %(s, s, arch))\\n'\n ' if s.startswith(\"helper_\"):\\n'\n ' s = \"adapter_\" + s\\n'\n ' print(\"#define %s %s_%s\" %(s, s, arch))',\n })\n # Define adapters\n translate_pat = os.path.join(UNICORN_QEMU_DIR, \"target-*\/translate.c\")\n for fpath in glob.glob(translate_pat):\n prepend(fpath, '#define GEN_ADAPTER_DEFINE\\n')\n # Fix register allocation for arguments\n replace(os.path.join(UNICORN_QEMU_DIR, \"tcg\/tcg.c\"), {\n \"int is_64bit = \":\n \"int is_64bit = 1;\/\/\",\n # Explicit casts of non-64bit arguments in tcg_gen_callN\n \"sizemask = info->sizemask;\":\"\"\"\n sizemask = info->sizemask;\n\n for (i = 0; i < nargs; i++) {\n int is_64bit = sizemask & (1 << (i+1)*2);\n if (!is_64bit) {\n TCGArg ext_arg = tcg_temp_new_i64(s);\n tcg_gen_ext32u_i64(s, ext_arg, args[i]);\n args[i] = GET_TCGV_I64(ext_arg);\n }\n }\n \"\"\"\n })\n # Fix unaligned reads\n append(os.path.join(UNICORN_QEMU_DIR, \"include\/qemu-common.h\"),\n PATCH_UNALIGNED_MEMACCESS)\n replace(os.path.join(UNICORN_QEMU_DIR, \"include\/exec\/exec-all.h\"), {\n \" *(uint32_t *)jmp_addr = addr - (jmp_addr + 4);\":\n \" UNALIGNED_WRITE32_LE(jmp_addr, addr - (jmp_addr + 4));\"\n })\n replace(os.path.join(UNICORN_QEMU_DIR, \"tci.c\"), {\n \"*(tcg_target_ulong *)(*tb_ptr)\":\n \"UNALIGNED_READ32_LE(*tb_ptr)\",\n \"*(uint32_t *)(*tb_ptr)\":\n \"UNALIGNED_READ32_LE(*tb_ptr)\",\n \"*(int32_t *)(*tb_ptr)\":\n \"UNALIGNED_READ32_LE(*tb_ptr)\",\n \"*(uint64_t *)tb_ptr\":\n \"UNALIGNED_READ64_LE(tb_ptr)\",\n # Stores\n \"*(uint16_t *)(t1 + t2) = t0\":\n \"UNALIGNED_WRITE16_LE(t1 + t2, t0)\",\n \"*(uint32_t *)(t1 + t2) = t0\":\n \"UNALIGNED_WRITE32_LE(t1 + t2, t0)\",\n \"*(uint64_t *)(t1 + t2) = t0\":\n \"UNALIGNED_WRITE64_LE(t1 + t2, t0)\",\n # Loads\n \"*(uint32_t *)(t1 + t2)\":\n \"UNALIGNED_READ32_LE(t1 + t2)\",\n \"*(uint64_t *)(t1 + t2)\":\n \"UNALIGNED_READ64_LE(t1 + t2)\",\n \"*(int32_t *)(t1 + t2)\":\n \"(int32_t)UNALIGNED_READ32_LE(t1 + t2)\",\n })\n # Fix unsupported varargs in uc_hook_add function signature\n replace(os.path.join(UNICORN_DIR, \"include\/unicorn\/unicorn.h\"), {\n \" void *user_data, uint64_t begin, uint64_t end, ...);\":\n \" void *user_data, uint64_t begin, uint64_t end, uint32_t extra);\",\n })\n replace(os.path.join(UNICORN_DIR, \"uc.c\"), {\n \" err = uc_hook_add(uc, &uc->count_hook, UC_HOOK_CODE, hook_count_cb, NULL, 1, 0);\":\n \" err = uc_hook_add(uc, &uc->count_hook, UC_HOOK_CODE, hook_count_cb, NULL, 1, 0, 0);\",\n \" void *user_data, uint64_t begin, uint64_t end, ...)\":\n \" void *user_data, uint64_t begin, uint64_t end, uint32_t extra)\",\n \" va_list valist;\":\n \" \/\/va_list valist;\",\n \" va_start(valist, end);\":\n \" \/\/va_start(valist, end);\",\n \" hook->insn = va_arg(valist, int);\":\n \" hook->insn = extra;\",\n \" va_end(valist);\":\n \" \/\/va_end(valist);\",\n })","function_tokens":["def","patchUnicornJS","(",")",":","# Disable unnecessary options","replace","(","os",".","path",".","join","(","UNICORN_DIR",",","\"config.mk\"",")",",","{","\"UNICORN_DEBUG ?= yes\"",":","\"UNICORN_DEBUG ?= no\"",",","\"UNICORN_SHARED ?= yes\"",":","\"UNICORN_SHARED ?= no\"",",","}",")","# Ensure QEMU's object files have different base names","name","=","\"rename_objects.py\"","with","open","(","os",".","path",".","join","(","UNICORN_DIR",",","name",")",",","\"wt\"",")","as","f",":","f",".","write","(","\"\"",")","replace","(","os",".","path",".","join","(","UNICORN_DIR",",","\"Makefile\"",")",",","{","\"$(MAKE) -C qemu $(SMP_MFLAGS)\"",":","\"$(MAKE) -C qemu $(SMP_MFLAGS)\\r\\n\\t@python \"","+","name",",","'\t.\/configure --cc=\"${CC}\" --extra-cflags=\"$(UNICORN_CFLAGS)\" --target-list=\"$(UNICORN_TARGETS)\" ${UNICORN_QEMU_FLAGS}'",":","'\t.\/configure --cc=\"${CC}\" --extra-cflags=\"$(UNICORN_CFLAGS)\" --target-list=\"$(UNICORN_TARGETS)\" ${UNICORN_QEMU_FLAGS} --disable-stack-protector --cpu=i386'",",","}",")","# Replace sigsetjmp\/siglongjump with setjmp\/longjmp","replace","(","os",".","path",".","join","(","UNICORN_QEMU_DIR",",","\"cpu-exec.c\"",")",",","{","\"sigsetjmp(cpu->jmp_env, 0)\"",":","\"setjmp(cpu->jmp_env)\"",",","\"siglongjmp(cpu->jmp_env, 1)\"",":","\"longjmp(cpu->jmp_env, 1)\"",",","}",")","# Fix Glib function pointer issues","replace","(","os",".","path",".","join","(","UNICORN_QEMU_DIR",",","\"glib_compat.c\"",")",",","{","\"(GCompareDataFunc) compare_func) (l1->data, l2->data, user_data)\"",":","\"(GCompareFunc) compare_func) (l1->data, l2->data)\"",",","}",")","# Fix QEMU function pointer issues","replace","(","os",".","path",".","join","(","UNICORN_QEMU_DIR",",","\"include\/exec\/helper-proto.h\"",")",",","{","# Adapter helpers","\"#include <exec\/helper-head.h>\"",":","\"#include <exec\/helper-head.h>\\n\"","+","PATCH_HELPER_ADAPTER_PROTO",",","# Declare adapters","\"#define DEF_HELPER_FLAGS_0(name, flags, ret) \\\\\"",":","\"\"\"\n #define DEF_HELPER_FLAGS_0(name, flags, ret) \\\\\n GEN_ADAPTER_DECLARE(name) \\\\\"\"\"",",","\"#define DEF_HELPER_FLAGS_1(name, flags, ret, t1) \\\\\"",":","\"\"\"\n #define DEF_HELPER_FLAGS_1(name, flags, ret, t1) \\\\\n GEN_ADAPTER_DECLARE(name) \\\\\"\"\"",",","\"#define DEF_HELPER_FLAGS_2(name, flags, ret, t1, t2) \\\\\"",":","\"\"\"\n #define DEF_HELPER_FLAGS_2(name, flags, ret, t1, t2) \\\\\n GEN_ADAPTER_DECLARE(name) \\\\\"\"\"",",","\"#define DEF_HELPER_FLAGS_3(name, flags, ret, t1, t2, t3) \\\\\"",":","\"\"\"\n #define DEF_HELPER_FLAGS_3(name, flags, ret, t1, t2, t3) \\\\\n GEN_ADAPTER_DECLARE(name) \\\\\"\"\"",",","\"#define DEF_HELPER_FLAGS_4(name, flags, ret, t1, t2, t3, t4) \\\\\"",":","\"\"\"\n #define DEF_HELPER_FLAGS_4(name, flags, ret, t1, t2, t3, t4) \\\\\n GEN_ADAPTER_DECLARE(name) \\\\\"\"\"",",","\"#define DEF_HELPER_FLAGS_5(name, flags, ret, t1, t2, t3, t4, t5) \\\\\"",":","\"\"\"\n #define DEF_HELPER_FLAGS_5(name, flags, ret, t1, t2, t3, t4, t5) \\\\\n GEN_ADAPTER_DECLARE(name) \\\\\"\"\"",",","}",")","replace","(","os",".","path",".","join","(","UNICORN_QEMU_DIR",",","\"include\/exec\/helper-gen.h\"",")",",","{","# Adapter helpers","\"#include <exec\/helper-head.h>\"",":","\"#include <exec\/helper-head.h>\\n\"","+","PATCH_HELPER_ADAPTER_GEN",",","# Generate calls to adapters instead","\"tcg_gen_callN(tcg_ctx, HELPER(name)\"",":","\"tcg_gen_callN(tcg_ctx, glue(adapter_helper_, name)\"",",","# Define adapters","\"#define DEF_HELPER_FLAGS_0(name, flags, ret) \\\\\"",":","\"\"\"\n #define DEF_HELPER_FLAGS_0(name, flags, ret) \\\\\n GEN_ADAPTER_0(name, ret) \\\\\"\"\"",",","\"#define DEF_HELPER_FLAGS_1(name, flags, ret, t1) \\\\\"",":","\"\"\"\n #define DEF_HELPER_FLAGS_1(name, flags, ret, t1) \\\\\n GEN_ADAPTER_1(name, ret, t1) \\\\\"\"\"",",","\"#define DEF_HELPER_FLAGS_2(name, flags, ret, t1, t2) \\\\\"",":","\"\"\"\n #define DEF_HELPER_FLAGS_2(name, flags, ret, t1, t2) \\\\\n GEN_ADAPTER_2(name, ret, t1, t2) \\\\\"\"\"",",","\"#define DEF_HELPER_FLAGS_3(name, flags, ret, t1, t2, t3) \\\\\"",":","\"\"\"\n #define DEF_HELPER_FLAGS_3(name, flags, ret, t1, t2, t3) \\\\\n GEN_ADAPTER_3(name, ret, t1, t2, t3) \\\\\"\"\"",",","\"#define DEF_HELPER_FLAGS_4(name, flags, ret, t1, t2, t3, t4) \\\\\"",":","\"\"\"\n #define DEF_HELPER_FLAGS_4(name, flags, ret, t1, t2, t3, t4) \\\\\n GEN_ADAPTER_4(name, ret, t1, t2, t3, t4) \\\\\"\"\"",",","\"#define DEF_HELPER_FLAGS_5(name, flags, ret, t1, t2, t3, t4, t5) \\\\\"",":","\"\"\"\n #define DEF_HELPER_FLAGS_5(name, flags, ret, t1, t2, t3, t4, t5) \\\\\n GEN_ADAPTER_5(name, ret, t1, t2, t3, t4, t5) \\\\\"\"\"",",","}",")","replace","(","os",".","path",".","join","(","UNICORN_QEMU_DIR",",","\"tcg-runtime.c\"",")",",","{","# Adapter helpers","'#include \"exec\/helper-head.h\"'",":","'#include \"exec\/helper-head.h\"\\n'","+","PATCH_HELPER_ADAPTER_GEN",",","# Add uc_tracecode to globals","'#include \"tcg-runtime.h\"'",":","\"\"\"\n #undef DEF_HELPER_FLAGS_2\n #define DEF_HELPER_FLAGS_2(name, flags, ret, t1, t2) \\\\\n dh_ctype(ret) HELPER(name) (dh_ctype(t1), dh_ctype(t2)); \\\\\n uint64_t glue(adapter_helper_, name)(GEN_ADAPTER_ARGS); \\\\\n GEN_ADAPTER_2_DEFINE(name, ret, t1, t2)\n #define DEF_HELPER_FLAGS_4(name, flags, ret, t1, t2, t3, t4) \\\\\n dh_ctype(ret) HELPER(name) (dh_ctype(t1), dh_ctype(t2), dh_ctype(t3), dh_ctype(t4)); \\\\\n uint64_t glue(adapter_helper_, name)(GEN_ADAPTER_ARGS); \\\\\n GEN_ADAPTER_4_DEFINE(name, ret, t1, t2, t3, t4)\n DEF_HELPER_4(uc_tracecode, void, i32, i32, ptr, i64)\n #include \"tcg-runtime.h\"\n \"\"\"",",","}",")","replace","(","os",".","path",".","join","(","UNICORN_QEMU_DIR",",","\"include\/exec\/helper-tcg.h\"",")",",","{","\"func = HELPER(NAME)\"",":","\"func = glue(adapter_helper_, NAME)\"","}",")","# Add arch-suffixes to adapters","header_gen_patched","=","False","with","open","(","os",".","path",".","join","(","UNICORN_QEMU_DIR",",","\"header_gen.py\"",")",",","'r'",")","as","f",":","if","'adapter_'","in","f",".","read","(",")",":","header_gen_patched","=","True","if","header_gen_patched","==","False",":","os",".","remove","(","os",".","path",".","join","(","UNICORN_QEMU_DIR",",","\"header_gen.py.bak\"",")",")","replace","(","os",".","path",".","join","(","UNICORN_QEMU_DIR",",","\"header_gen.py\"",")",",","{","' print(\"#define %s %s_%s\" %(s, s, arch))'",":","' print(\"#define %s %s_%s\" %(s, s, arch))\\n'","' if s.startswith(\"helper_\"):\\n'","' s = \"adapter_\" + s\\n'","' print(\"#define %s %s_%s\" %(s, s, arch))'",",","}",")","# Define adapters","translate_pat","=","os",".","path",".","join","(","UNICORN_QEMU_DIR",",","\"target-*\/translate.c\"",")","for","fpath","in","glob",".","glob","(","translate_pat",")",":","prepend","(","fpath",",","'#define GEN_ADAPTER_DEFINE\\n'",")","# Fix register allocation for arguments","replace","(","os",".","path",".","join","(","UNICORN_QEMU_DIR",",","\"tcg\/tcg.c\"",")",",","{","\"int is_64bit = \"",":","\"int is_64bit = 1;\/\/\"",",","# Explicit casts of non-64bit arguments in tcg_gen_callN","\"sizemask = info->sizemask;\"",":","\"\"\"\n sizemask = info->sizemask;\n\n for (i = 0; i < nargs; i++) {\n int is_64bit = sizemask & (1 << (i+1)*2);\n if (!is_64bit) {\n TCGArg ext_arg = tcg_temp_new_i64(s);\n tcg_gen_ext32u_i64(s, ext_arg, args[i]);\n args[i] = GET_TCGV_I64(ext_arg);\n }\n }\n \"\"\"","}",")","# Fix unaligned reads","append","(","os",".","path",".","join","(","UNICORN_QEMU_DIR",",","\"include\/qemu-common.h\"",")",",","PATCH_UNALIGNED_MEMACCESS",")","replace","(","os",".","path",".","join","(","UNICORN_QEMU_DIR",",","\"include\/exec\/exec-all.h\"",")",",","{","\" *(uint32_t *)jmp_addr = addr - (jmp_addr + 4);\"",":","\" UNALIGNED_WRITE32_LE(jmp_addr, addr - (jmp_addr + 4));\"","}",")","replace","(","os",".","path",".","join","(","UNICORN_QEMU_DIR",",","\"tci.c\"",")",",","{","\"*(tcg_target_ulong *)(*tb_ptr)\"",":","\"UNALIGNED_READ32_LE(*tb_ptr)\"",",","\"*(uint32_t *)(*tb_ptr)\"",":","\"UNALIGNED_READ32_LE(*tb_ptr)\"",",","\"*(int32_t *)(*tb_ptr)\"",":","\"UNALIGNED_READ32_LE(*tb_ptr)\"",",","\"*(uint64_t *)tb_ptr\"",":","\"UNALIGNED_READ64_LE(tb_ptr)\"",",","# Stores","\"*(uint16_t *)(t1 + t2) = t0\"",":","\"UNALIGNED_WRITE16_LE(t1 + t2, t0)\"",",","\"*(uint32_t *)(t1 + t2) = t0\"",":","\"UNALIGNED_WRITE32_LE(t1 + t2, t0)\"",",","\"*(uint64_t *)(t1 + t2) = t0\"",":","\"UNALIGNED_WRITE64_LE(t1 + t2, t0)\"",",","# Loads","\"*(uint32_t *)(t1 + t2)\"",":","\"UNALIGNED_READ32_LE(t1 + t2)\"",",","\"*(uint64_t *)(t1 + t2)\"",":","\"UNALIGNED_READ64_LE(t1 + t2)\"",",","\"*(int32_t *)(t1 + t2)\"",":","\"(int32_t)UNALIGNED_READ32_LE(t1 + t2)\"",",","}",")","# Fix unsupported varargs in uc_hook_add function signature","replace","(","os",".","path",".","join","(","UNICORN_DIR",",","\"include\/unicorn\/unicorn.h\"",")",",","{","\" void *user_data, uint64_t begin, uint64_t end, ...);\"",":","\" void *user_data, uint64_t begin, uint64_t end, uint32_t extra);\"",",","}",")","replace","(","os",".","path",".","join","(","UNICORN_DIR",",","\"uc.c\"",")",",","{","\" err = uc_hook_add(uc, &uc->count_hook, UC_HOOK_CODE, hook_count_cb, NULL, 1, 0);\"",":","\" err = uc_hook_add(uc, &uc->count_hook, UC_HOOK_CODE, hook_count_cb, NULL, 1, 0, 0);\"",",","\" void *user_data, uint64_t begin, uint64_t end, ...)\"",":","\" void *user_data, uint64_t begin, uint64_t end, uint32_t extra)\"",",","\" va_list valist;\"",":","\" \/\/va_list valist;\"",",","\" va_start(valist, end);\"",":","\" \/\/va_start(valist, end);\"",",","\" hook->insn = va_arg(valist, int);\"",":","\" hook->insn = extra;\"",",","\" va_end(valist);\"",":","\" \/\/va_end(valist);\"",",","}",")"],"url":"https:\/\/github.com\/AlexAltea\/unicorn.js\/blob\/6e998393d863a37659c09046d4835003e6554a35\/build.py#L382-L572"}
AllAboutCode__EduBlocks.jsonl ADDED
The diff for this file is too large to render. See raw diff
AloneMonkey__frida-ios-dump.jsonl ADDED
@@ -0,0 +1 @@
 
1
+ {"nwo":"AloneMonkey\/frida-ios-dump","sha":"56e99b2138fc213fa759b3aeb9717a1fb4ec6a59","path":"dump.py","language":"python","identifier":"cmp_to_key","parameters":"(mycmp)","argument_list":"","return_statement":"return K","docstring":"Convert a cmp= function into a key= function","docstring_summary":"Convert a cmp= function into a key= function","docstring_tokens":["Convert","a","cmp","=","function","into","a","key","=","function"],"function":"def cmp_to_key(mycmp):\n \"\"\"Convert a cmp= function into a key= function\"\"\"\n\n class K:\n def __init__(self, obj):\n self.obj = obj\n\n def __lt__(self, other):\n return mycmp(self.obj, other.obj) < 0\n\n def __gt__(self, other):\n return mycmp(self.obj, other.obj) > 0\n\n def __eq__(self, other):\n return mycmp(self.obj, other.obj) == 0\n\n def __le__(self, other):\n return mycmp(self.obj, other.obj) <= 0\n\n def __ge__(self, other):\n return mycmp(self.obj, other.obj) >= 0\n\n def __ne__(self, other):\n return mycmp(self.obj, other.obj) != 0\n\n return K","function_tokens":["def","cmp_to_key","(","mycmp",")",":","class","K",":","def","__init__","(","self",",","obj",")",":","self",".","obj","=","obj","def","__lt__","(","self",",","other",")",":","return","mycmp","(","self",".","obj",",","other",".","obj",")","<","0","def","__gt__","(","self",",","other",")",":","return","mycmp","(","self",".","obj",",","other",".","obj",")",">","0","def","__eq__","(","self",",","other",")",":","return","mycmp","(","self",".","obj",",","other",".","obj",")","==","0","def","__le__","(","self",",","other",")",":","return","mycmp","(","self",".","obj",",","other",".","obj",")","<=","0","def","__ge__","(","self",",","other",")",":","return","mycmp","(","self",".","obj",",","other",".","obj",")",">=","0","def","__ne__","(","self",",","other",")",":","return","mycmp","(","self",".","obj",",","other",".","obj",")","!=","0","return","K"],"url":"https:\/\/github.com\/AloneMonkey\/frida-ios-dump\/blob\/56e99b2138fc213fa759b3aeb9717a1fb4ec6a59\/dump.py#L169-L194"}
Ameobea__robintrack.jsonl ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"Ameobea\/robintrack","sha":"d74acc0b8e9f360864d1606134123a9430f8c223","path":"stocktwits-bot\/src\/stocktwits_api.py","language":"python","identifier":"stocktwits_request","parameters":"(method: str, path: str, *args, headers={}, **kwargs)","argument_list":"","return_statement":"return res.json()","docstring":"Makes a request to the Stocktwits API, passing along the username and password as\n authorization headers.","docstring_summary":"Makes a request to the Stocktwits API, passing along the username and password as\n authorization headers.","docstring_tokens":["Makes","a","request","to","the","Stocktwits","API","passing","along","the","username","and","password","as","authorization","headers","."],"function":"def stocktwits_request(method: str, path: str, *args, headers={}, **kwargs) -> object:\n \"\"\" Makes a request to the Stocktwits API, passing along the username and password as\n authorization headers. \"\"\"\n\n req_function = map_method_name_to_requests_function(method)\n merged_headers = {**headers, \"Authorization\": f\"OAuth {STOCKTWITS_ACCESS_TOKEN}\"}\n url = f\"{STOCKTWITS_BASE_URL}{path}\"\n res = req_function(url, *args, headers=merged_headers, **kwargs)\n return res.json()","function_tokens":["def","stocktwits_request","(","method",":","str",",","path",":","str",",","*","args",",","headers","=","{","}",",","*","*","kwargs",")","->","object",":","req_function","=","map_method_name_to_requests_function","(","method",")","merged_headers","=","{","*","*","headers",",","\"Authorization\"",":","f\"OAuth {STOCKTWITS_ACCESS_TOKEN}\"","}","url","=","f\"{STOCKTWITS_BASE_URL}{path}\"","res","=","req_function","(","url",",","*","args",",","headers","=","merged_headers",",","*","*","kwargs",")","return","res",".","json","(",")"],"url":"https:\/\/github.com\/Ameobea\/robintrack\/blob\/d74acc0b8e9f360864d1606134123a9430f8c223\/stocktwits-bot\/src\/stocktwits_api.py#L30-L38"}
2
+ {"nwo":"Ameobea\/robintrack","sha":"d74acc0b8e9f360864d1606134123a9430f8c223","path":"scraper\/src\/db.py","language":"python","identifier":"set_update_started","parameters":"()","argument_list":"","return_statement":"","docstring":"Marks all data scraping operations as in-progress, invalidates the cache, and marks it as\n invalid until all data scrapes are completed.","docstring_summary":"Marks all data scraping operations as in-progress, invalidates the cache, and marks it as\n invalid until all data scrapes are completed.","docstring_tokens":["Marks","all","data","scraping","operations","as","in","-","progress","invalidates","the","cache","and","marks","it","as","invalid","until","all","data","scrapes","are","completed","."],"function":"def set_update_started():\n \"\"\" Marks all data scraping operations as in-progress, invalidates the cache, and marks it as\n invalid until all data scrapes are completed. \"\"\"\n\n redis_client.delete(\"INSTRUMENTS_FINISHED\")\n redis_client.delete(\"POPULARITIES_FINISHED\")\n redis_client.delete(\"QUOTES_FINISHED\")\n\n lock_cache()","function_tokens":["def","set_update_started","(",")",":","redis_client",".","delete","(","\"INSTRUMENTS_FINISHED\"",")","redis_client",".","delete","(","\"POPULARITIES_FINISHED\"",")","redis_client",".","delete","(","\"QUOTES_FINISHED\"",")","lock_cache","(",")"],"url":"https:\/\/github.com\/Ameobea\/robintrack\/blob\/d74acc0b8e9f360864d1606134123a9430f8c223\/scraper\/src\/db.py#L9-L17"}
3
+ {"nwo":"Ameobea\/robintrack","sha":"d74acc0b8e9f360864d1606134123a9430f8c223","path":"scraper\/src\/db.py","language":"python","identifier":"check_if_all_finished","parameters":"()","argument_list":"","return_statement":"","docstring":"Checks if the instrument, popularity, and quote scrapes are all finished. If they are,\n then flush, unlock, and re-enable the cache.","docstring_summary":"Checks if the instrument, popularity, and quote scrapes are all finished. If they are,\n then flush, unlock, and re-enable the cache.","docstring_tokens":["Checks","if","the","instrument","popularity","and","quote","scrapes","are","all","finished",".","If","they","are","then","flush","unlock","and","re","-","enable","the","cache","."],"function":"def check_if_all_finished():\n \"\"\" Checks if the instrument, popularity, and quote scrapes are all finished. If they are,\n then flush, unlock, and re-enable the cache. \"\"\"\n\n all_finished = (\n redis_client.get(\"INSTRUMENTS_FINISHED\")\n and redis_client.get(\"POPULARITIES_FINISHED\")\n and redis_client.get(\"QUOTES_FINISHED\")\n )\n\n if all_finished:\n print(\"All updates finished! Flushing + unlocking cache...\")\n flush_cache()\n populate_popularity_rankings(redis_client, get_db)\n unlock_cache()","function_tokens":["def","check_if_all_finished","(",")",":","all_finished","=","(","redis_client",".","get","(","\"INSTRUMENTS_FINISHED\"",")","and","redis_client",".","get","(","\"POPULARITIES_FINISHED\"",")","and","redis_client",".","get","(","\"QUOTES_FINISHED\"",")",")","if","all_finished",":","print","(","\"All updates finished! Flushing + unlocking cache...\"",")","flush_cache","(",")","populate_popularity_rankings","(","redis_client",",","get_db",")","unlock_cache","(",")"],"url":"https:\/\/github.com\/Ameobea\/robintrack\/blob\/d74acc0b8e9f360864d1606134123a9430f8c223\/scraper\/src\/db.py#L20-L34"}
4
+ {"nwo":"Ameobea\/robintrack","sha":"d74acc0b8e9f360864d1606134123a9430f8c223","path":"scraper\/src\/db.py","language":"python","identifier":"set_instruments_finished","parameters":"()","argument_list":"","return_statement":"","docstring":"This is called when the instrument scraper finishes scraping the full list of instruments.\n As soon as popularities and quotes are finished as well, the data scrape is complete and the\n cache can be re-enabled.","docstring_summary":"This is called when the instrument scraper finishes scraping the full list of instruments.\n As soon as popularities and quotes are finished as well, the data scrape is complete and the\n cache can be re-enabled.","docstring_tokens":["This","is","called","when","the","instrument","scraper","finishes","scraping","the","full","list","of","instruments",".","As","soon","as","popularities","and","quotes","are","finished","as","well","the","data","scrape","is","complete","and","the","cache","can","be","re","-","enabled","."],"function":"def set_instruments_finished():\n \"\"\" This is called when the instrument scraper finishes scraping the full list of instruments.\n As soon as popularities and quotes are finished as well, the data scrape is complete and the\n cache can be re-enabled. \"\"\"\n\n redis_client.set(\"INSTRUMENTS_FINISHED\", \"1\")\n check_if_all_finished()","function_tokens":["def","set_instruments_finished","(",")",":","redis_client",".","set","(","\"INSTRUMENTS_FINISHED\"",",","\"1\"",")","check_if_all_finished","(",")"],"url":"https:\/\/github.com\/Ameobea\/robintrack\/blob\/d74acc0b8e9f360864d1606134123a9430f8c223\/scraper\/src\/db.py#L37-L43"}
5
+ {"nwo":"Ameobea\/robintrack","sha":"d74acc0b8e9f360864d1606134123a9430f8c223","path":"scraper\/src\/db.py","language":"python","identifier":"set_popularities_finished","parameters":"()","argument_list":"","return_statement":"","docstring":"This is called when the popularity scraper finishes scraping popularities for all symbols.\n As soon as instruments and quotes are finished as well, the data scrape is complete and the\n cache can be re-enabled.","docstring_summary":"This is called when the popularity scraper finishes scraping popularities for all symbols.\n As soon as instruments and quotes are finished as well, the data scrape is complete and the\n cache can be re-enabled.","docstring_tokens":["This","is","called","when","the","popularity","scraper","finishes","scraping","popularities","for","all","symbols",".","As","soon","as","instruments","and","quotes","are","finished","as","well","the","data","scrape","is","complete","and","the","cache","can","be","re","-","enabled","."],"function":"def set_popularities_finished():\n \"\"\" This is called when the popularity scraper finishes scraping popularities for all symbols.\n As soon as instruments and quotes are finished as well, the data scrape is complete and the\n cache can be re-enabled. \"\"\"\n\n redis_client.set(\"POPULARITIES_FINISHED\", \"1\")\n check_if_all_finished()","function_tokens":["def","set_popularities_finished","(",")",":","redis_client",".","set","(","\"POPULARITIES_FINISHED\"",",","\"1\"",")","check_if_all_finished","(",")"],"url":"https:\/\/github.com\/Ameobea\/robintrack\/blob\/d74acc0b8e9f360864d1606134123a9430f8c223\/scraper\/src\/db.py#L46-L52"}
6
+ {"nwo":"Ameobea\/robintrack","sha":"d74acc0b8e9f360864d1606134123a9430f8c223","path":"scraper\/src\/db.py","language":"python","identifier":"set_quotes_finished","parameters":"()","argument_list":"","return_statement":"","docstring":"This is called when the quote scraper finishes scraping quotes for all symbols. As soon as\n instruments and popularities are finished as well, the data scrape is complete and the cache\n can be re-enabled.","docstring_summary":"This is called when the quote scraper finishes scraping quotes for all symbols. As soon as\n instruments and popularities are finished as well, the data scrape is complete and the cache\n can be re-enabled.","docstring_tokens":["This","is","called","when","the","quote","scraper","finishes","scraping","quotes","for","all","symbols",".","As","soon","as","instruments","and","popularities","are","finished","as","well","the","data","scrape","is","complete","and","the","cache","can","be","re","-","enabled","."],"function":"def set_quotes_finished():\n \"\"\" This is called when the quote scraper finishes scraping quotes for all symbols. As soon as\n instruments and popularities are finished as well, the data scrape is complete and the cache\n can be re-enabled. \"\"\"\n\n redis_client.set(\"QUOTES_FINISHED\", \"1\")\n check_if_all_finished()","function_tokens":["def","set_quotes_finished","(",")",":","redis_client",".","set","(","\"QUOTES_FINISHED\"",",","\"1\"",")","check_if_all_finished","(",")"],"url":"https:\/\/github.com\/Ameobea\/robintrack\/blob\/d74acc0b8e9f360864d1606134123a9430f8c223\/scraper\/src\/db.py#L55-L61"}
7
+ {"nwo":"Ameobea\/robintrack","sha":"d74acc0b8e9f360864d1606134123a9430f8c223","path":"scraper\/src\/db.py","language":"python","identifier":"flush_cache","parameters":"()","argument_list":"","return_statement":"","docstring":"Removes all cache hashes, removing all existing cache entries.","docstring_summary":"Removes all cache hashes, removing all existing cache entries.","docstring_tokens":["Removes","all","cache","hashes","removing","all","existing","cache","entries","."],"function":"def flush_cache():\n \"\"\" Removes all cache hashes, removing all existing cache entries. \"\"\"\n\n print(\"Flushing cache...\")\n redis_client.flushdb()","function_tokens":["def","flush_cache","(",")",":","print","(","\"Flushing cache...\"",")","redis_client",".","flushdb","(",")"],"url":"https:\/\/github.com\/Ameobea\/robintrack\/blob\/d74acc0b8e9f360864d1606134123a9430f8c223\/scraper\/src\/db.py#L64-L68"}
8
+ {"nwo":"Ameobea\/robintrack","sha":"d74acc0b8e9f360864d1606134123a9430f8c223","path":"scraper\/src\/db.py","language":"python","identifier":"lock_cache","parameters":"()","argument_list":"","return_statement":"","docstring":"Marks the cache as invalidated and clears all existing cache entries. This causes all\n requests to the backend to be served from MongoDB and prevents new insertions into the\n cache.","docstring_summary":"Marks the cache as invalidated and clears all existing cache entries. This causes all\n requests to the backend to be served from MongoDB and prevents new insertions into the\n cache.","docstring_tokens":["Marks","the","cache","as","invalidated","and","clears","all","existing","cache","entries",".","This","causes","all","requests","to","the","backend","to","be","served","from","MongoDB","and","prevents","new","insertions","into","the","cache","."],"function":"def lock_cache():\n \"\"\" Marks the cache as invalidated and clears all existing cache entries. This causes all\n requests to the backend to be served from MongoDB and prevents new insertions into the\n cache. \"\"\"\n\n redis_client.set(\"CACHE_LOCKED\", \"1\")\n print(\"Cache locked.\")","function_tokens":["def","lock_cache","(",")",":","redis_client",".","set","(","\"CACHE_LOCKED\"",",","\"1\"",")","print","(","\"Cache locked.\"",")"],"url":"https:\/\/github.com\/Ameobea\/robintrack\/blob\/d74acc0b8e9f360864d1606134123a9430f8c223\/scraper\/src\/db.py#L71-L77"}
9
+ {"nwo":"Ameobea\/robintrack","sha":"d74acc0b8e9f360864d1606134123a9430f8c223","path":"scraper\/src\/db.py","language":"python","identifier":"unlock_cache","parameters":"()","argument_list":"","return_statement":"","docstring":"Marks the cache as valid, allowing new entries to be inserted and existing values to be\n used to service requests to the API.","docstring_summary":"Marks the cache as valid, allowing new entries to be inserted and existing values to be\n used to service requests to the API.","docstring_tokens":["Marks","the","cache","as","valid","allowing","new","entries","to","be","inserted","and","existing","values","to","be","used","to","service","requests","to","the","API","."],"function":"def unlock_cache():\n \"\"\" Marks the cache as valid, allowing new entries to be inserted and existing values to be\n used to service requests to the API. \"\"\"\n\n redis_client.delete(\"CACHE_LOCKED\")\n print(\"Cache unlocked.\")","function_tokens":["def","unlock_cache","(",")",":","redis_client",".","delete","(","\"CACHE_LOCKED\"",")","print","(","\"Cache unlocked.\"",")"],"url":"https:\/\/github.com\/Ameobea\/robintrack\/blob\/d74acc0b8e9f360864d1606134123a9430f8c223\/scraper\/src\/db.py#L80-L85"}
10
+ {"nwo":"Ameobea\/robintrack","sha":"d74acc0b8e9f360864d1606134123a9430f8c223","path":"scraper\/src\/worker.py","language":"python","identifier":"store_popularities","parameters":"(popularity_map: dict, collection: pymongo.collection.Collection)","argument_list":"","return_statement":"","docstring":"Creates an entry in the database for the popularity.","docstring_summary":"Creates an entry in the database for the popularity.","docstring_tokens":["Creates","an","entry","in","the","database","for","the","popularity","."],"function":"def store_popularities(popularity_map: dict, collection: pymongo.collection.Collection):\n \"\"\" Creates an entry in the database for the popularity. \"\"\"\n\n timestamp = datetime.datetime.utcnow()\n pprint(popularity_map)\n mapped_documents = map(\n lambda key: {\n \"timestamp\": timestamp,\n \"instrument_id\": key,\n \"popularity\": popularity_map[key],\n },\n popularity_map.keys(),\n )\n\n collection.insert_many(mapped_documents)","function_tokens":["def","store_popularities","(","popularity_map",":","dict",",","collection",":","pymongo",".","collection",".","Collection",")",":","timestamp","=","datetime",".","datetime",".","utcnow","(",")","pprint","(","popularity_map",")","mapped_documents","=","map","(","lambda","key",":","{","\"timestamp\"",":","timestamp",",","\"instrument_id\"",":","key",",","\"popularity\"",":","popularity_map","[","key","]",",","}",",","popularity_map",".","keys","(",")",",",")","collection",".","insert_many","(","mapped_documents",")"],"url":"https:\/\/github.com\/Ameobea\/robintrack\/blob\/d74acc0b8e9f360864d1606134123a9430f8c223\/scraper\/src\/worker.py#L36-L50"}
11
+ {"nwo":"Ameobea\/robintrack","sha":"d74acc0b8e9f360864d1606134123a9430f8c223","path":"scraper\/src\/worker.py","language":"python","identifier":"store_quotes","parameters":"(quotes: list, collection: pymongo.collection.Collection)","argument_list":"","return_statement":"","docstring":"Creates entries in the database for the provided quotes.","docstring_summary":"Creates entries in the database for the provided quotes.","docstring_tokens":["Creates","entries","in","the","database","for","the","provided","quotes","."],"function":"def store_quotes(quotes: list, collection: pymongo.collection.Collection):\n \"\"\" Creates entries in the database for the provided quotes. \"\"\"\n\n def map_quote(quote: dict) -> dict:\n instrument_id = parse_instrument_url(quote[\"instrument\"])\n\n plucked = {\"instrument_id\": instrument_id, **pluck(DESIRED_QUOTE_KEYS, quote)}\n plucked[\"updated_at\"] = parse_updated_at(plucked[\"updated_at\"])\n return plucked\n\n quotes = list(filter(lambda quote: quote != None, quotes))\n\n def format_quote(quote: dict) -> dict:\n return {\"symbol\": quote[\"symbol\"], \"bid\": quote[\"bid_price\"], \"ask\": quote[\"ask_price\"]}\n\n pprint(list(map(format_quote, quotes)))\n\n # Update the index collection with up-to-date tradability info\n timestamp = datetime.datetime.utcnow()\n\n def update_index_symbol(datum: dict) -> pymongo.operations.UpdateOne:\n data = {\n \"timestamp\": timestamp,\n \"has_traded\": datum.get(\"has_traded\"),\n \"updated_at\": parse_updated_at(datum.get(\"updated_at\")),\n \"trading_halted\": datum.get(\"trading_halted\"),\n }\n instrument_id = parse_instrument_url(datum[\"instrument\"])\n\n return pymongo.operations.UpdateOne({\"instrument_id\": instrument_id}, {\"$set\": data})\n\n ops = list(map(update_index_symbol, quotes))\n INDEX_COL.bulk_write(ops, ordered=False)\n\n quotes = list(map(map_quote, quotes))\n try:\n collection.insert_many(quotes, ordered=False)\n except BulkWriteError as bwe:\n for err in bwe.details[\"writeErrors\"]:\n if \"duplicate key\" not in err[\"errmsg\"]:\n print(\"ERROR: Unhandled exception occured during batch write:\")\n pprint(err)","function_tokens":["def","store_quotes","(","quotes",":","list",",","collection",":","pymongo",".","collection",".","Collection",")",":","def","map_quote","(","quote",":","dict",")","->","dict",":","instrument_id","=","parse_instrument_url","(","quote","[","\"instrument\"","]",")","plucked","=","{","\"instrument_id\"",":","instrument_id",",","*","*","pluck","(","DESIRED_QUOTE_KEYS",",","quote",")","}","plucked","[","\"updated_at\"","]","=","parse_updated_at","(","plucked","[","\"updated_at\"","]",")","return","plucked","quotes","=","list","(","filter","(","lambda","quote",":","quote","!=","None",",","quotes",")",")","def","format_quote","(","quote",":","dict",")","->","dict",":","return","{","\"symbol\"",":","quote","[","\"symbol\"","]",",","\"bid\"",":","quote","[","\"bid_price\"","]",",","\"ask\"",":","quote","[","\"ask_price\"","]","}","pprint","(","list","(","map","(","format_quote",",","quotes",")",")",")","# Update the index collection with up-to-date tradability info","timestamp","=","datetime",".","datetime",".","utcnow","(",")","def","update_index_symbol","(","datum",":","dict",")","->","pymongo",".","operations",".","UpdateOne",":","data","=","{","\"timestamp\"",":","timestamp",",","\"has_traded\"",":","datum",".","get","(","\"has_traded\"",")",",","\"updated_at\"",":","parse_updated_at","(","datum",".","get","(","\"updated_at\"",")",")",",","\"trading_halted\"",":","datum",".","get","(","\"trading_halted\"",")",",","}","instrument_id","=","parse_instrument_url","(","datum","[","\"instrument\"","]",")","return","pymongo",".","operations",".","UpdateOne","(","{","\"instrument_id\"",":","instrument_id","}",",","{","\"$set\"",":","data","}",")","ops","=","list","(","map","(","update_index_symbol",",","quotes",")",")","INDEX_COL",".","bulk_write","(","ops",",","ordered","=","False",")","quotes","=","list","(","map","(","map_quote",",","quotes",")",")","try",":","collection",".","insert_many","(","quotes",",","ordered","=","False",")","except","BulkWriteError","as","bwe",":","for","err","in","bwe",".","details","[","\"writeErrors\"","]",":","if","\"duplicate key\"","not","in","err","[","\"errmsg\"","]",":","print","(","\"ERROR: Unhandled exception occured during batch write:\"",")","pprint","(","err",")"],"url":"https:\/\/github.com\/Ameobea\/robintrack\/blob\/d74acc0b8e9f360864d1606134123a9430f8c223\/scraper\/src\/worker.py#L53-L94"}
12
+ {"nwo":"Ameobea\/robintrack","sha":"d74acc0b8e9f360864d1606134123a9430f8c223","path":"scraper\/src\/common.py","language":"python","identifier":"pp_json","parameters":"(x: object)","argument_list":"","return_statement":"","docstring":"Pretty-prints the provided JSON-serializable object.","docstring_summary":"Pretty-prints the provided JSON-serializable object.","docstring_tokens":["Pretty","-","prints","the","provided","JSON","-","serializable","object","."],"function":"def pp_json(x: object) -> None:\n \"\"\" Pretty-prints the provided JSON-serializable object. \"\"\"\n print(json.dumps(x, indent=2, sort_keys=True))","function_tokens":["def","pp_json","(","x",":","object",")","->","None",":","print","(","json",".","dumps","(","x",",","indent","=","2",",","sort_keys","=","True",")",")"],"url":"https:\/\/github.com\/Ameobea\/robintrack\/blob\/d74acc0b8e9f360864d1606134123a9430f8c223\/scraper\/src\/common.py#L7-L9"}
13
+ {"nwo":"Ameobea\/robintrack","sha":"d74acc0b8e9f360864d1606134123a9430f8c223","path":"scraper\/src\/common.py","language":"python","identifier":"parse_throttle_res","parameters":"(msg: str)","argument_list":"","return_statement":"return int(float(match[1]) + 2.0)","docstring":"Given the response of a throttle message, returns the cooldown.","docstring_summary":"Given the response of a throttle message, returns the cooldown.","docstring_tokens":["Given","the","response","of","a","throttle","message","returns","the","cooldown","."],"function":"def parse_throttle_res(msg: str) -> int:\n \"\"\" Given the response of a throttle message, returns the cooldown. \"\"\"\n match = re.match(THROTTLE_RGX, msg)\n if not match:\n print(\n \"ERROR: Unable to parse throttle message. {}{}\".format(msg, \"Assuming 1.5 minutes...\")\n )\n return 120\n\n return int(float(match[1]) + 2.0)","function_tokens":["def","parse_throttle_res","(","msg",":","str",")","->","int",":","match","=","re",".","match","(","THROTTLE_RGX",",","msg",")","if","not","match",":","print","(","\"ERROR: Unable to parse throttle message. {}{}\"",".","format","(","msg",",","\"Assuming 1.5 minutes...\"",")",")","return","120","return","int","(","float","(","match","[","1","]",")","+","2.0",")"],"url":"https:\/\/github.com\/Ameobea\/robintrack\/blob\/d74acc0b8e9f360864d1606134123a9430f8c223\/scraper\/src\/common.py#L15-L24"}
14
+ {"nwo":"Ameobea\/robintrack","sha":"d74acc0b8e9f360864d1606134123a9430f8c223","path":"scraper\/src\/popularity_ranking.py","language":"python","identifier":"compute_popularity_rankings","parameters":"(get_db)","argument_list":"","return_statement":"return ret","docstring":"Returns a list of all symbols ordered by current popularity, ordered most to least\n popular.","docstring_summary":"Returns a list of all symbols ordered by current popularity, ordered most to least\n popular.","docstring_tokens":["Returns","a","list","of","all","symbols","ordered","by","current","popularity","ordered","most","to","least","popular","."],"function":"def compute_popularity_rankings(get_db) -> list:\n \"\"\" Returns a list of all symbols ordered by current popularity, ordered most to least\n popular. \"\"\"\n\n db = get_db()\n\n print(\"Performing popularity aggregation query\")\n res = list(db[\"popularity\"].aggregate(get_popularity_ranking_query()))\n\n unique_instrument_ids = [datum[\"_id\"] for datum in res]\n index_res = db[\"index\"].find({ \"instrument_id\": { \"$in\": unique_instrument_ids } })\n instrument_data = {}\n for item in index_res:\n instrument_data[item[\"instrument_id\"]] = item\n\n ret = []\n for datum in res:\n instrument_datum = instrument_data.get(datum[\"_id\"])\n if instrument_datum is None:\n continue\n\n ret.append({ \"latest_popularity\": datum[\"latest_popularity\"], \"name\": instrument_datum[\"simple_name\"], \"symbol\": instrument_datum[\"symbol\"] })\n\n return ret","function_tokens":["def","compute_popularity_rankings","(","get_db",")","->","list",":","db","=","get_db","(",")","print","(","\"Performing popularity aggregation query\"",")","res","=","list","(","db","[","\"popularity\"","]",".","aggregate","(","get_popularity_ranking_query","(",")",")",")","unique_instrument_ids","=","[","datum","[","\"_id\"","]","for","datum","in","res","]","index_res","=","db","[","\"index\"","]",".","find","(","{","\"instrument_id\"",":","{","\"$in\"",":","unique_instrument_ids","}","}",")","instrument_data","=","{","}","for","item","in","index_res",":","instrument_data","[","item","[","\"instrument_id\"","]","]","=","item","ret","=","[","]","for","datum","in","res",":","instrument_datum","=","instrument_data",".","get","(","datum","[","\"_id\"","]",")","if","instrument_datum","is","None",":","continue","ret",".","append","(","{","\"latest_popularity\"",":","datum","[","\"latest_popularity\"","]",",","\"name\"",":","instrument_datum","[","\"simple_name\"","]",",","\"symbol\"",":","instrument_datum","[","\"symbol\"","]","}",")","return","ret"],"url":"https:\/\/github.com\/Ameobea\/robintrack\/blob\/d74acc0b8e9f360864d1606134123a9430f8c223\/scraper\/src\/popularity_ranking.py#L19-L42"}
15
+ {"nwo":"Ameobea\/robintrack","sha":"d74acc0b8e9f360864d1606134123a9430f8c223","path":"scraper\/src\/popularity_ranking.py","language":"python","identifier":"set_popularity_rankings","parameters":"(redis_client, rankings: Cursor)","argument_list":"","return_statement":"","docstring":"Sets the popularity rankings for each symbol into Redis.","docstring_summary":"Sets the popularity rankings for each symbol into Redis.","docstring_tokens":["Sets","the","popularity","rankings","for","each","symbol","into","Redis","."],"function":"def set_popularity_rankings(redis_client, rankings: Cursor):\n \"\"\" Sets the popularity rankings for each symbol into Redis. \"\"\"\n\n rankings_map = {}\n rankings_list = []\n ranking = 0\n print(\"Finished fetching population data.\")\n for entry in rankings:\n symbol = entry.get(\"symbol\")\n name = entry.get(\"name\")\n if symbol is None:\n continue\n popularity = entry.get(\"latest_popularity\", 0)\n\n ranking += 1\n rankings_map[symbol] = ranking\n rankings_list.append(json.dumps({\"symbol\": symbol, \"popularity\": popularity, \"name\": name}))\n\n print(\"Setting popularity rankings hash...\")\n # Populate the popularity mapping hash used to map symbol to ranking\n redis_client.delete(\"popularity_rankings\")\n redis_client.hmset(\"popularity_rankings\", rankings_map)\n print(\"Setting popularity list...\")\n # Populate the list rankings all symbols from most to least popular in order\n redis_client.delete(\"popularity_list\")\n redis_client.rpush(\"popularity_list\", *rankings_list)\n print(\"Finished computing popularity caches\")","function_tokens":["def","set_popularity_rankings","(","redis_client",",","rankings",":","Cursor",")",":","rankings_map","=","{","}","rankings_list","=","[","]","ranking","=","0","print","(","\"Finished fetching population data.\"",")","for","entry","in","rankings",":","symbol","=","entry",".","get","(","\"symbol\"",")","name","=","entry",".","get","(","\"name\"",")","if","symbol","is","None",":","continue","popularity","=","entry",".","get","(","\"latest_popularity\"",",","0",")","ranking","+=","1","rankings_map","[","symbol","]","=","ranking","rankings_list",".","append","(","json",".","dumps","(","{","\"symbol\"",":","symbol",",","\"popularity\"",":","popularity",",","\"name\"",":","name","}",")",")","print","(","\"Setting popularity rankings hash...\"",")","# Populate the popularity mapping hash used to map symbol to ranking","redis_client",".","delete","(","\"popularity_rankings\"",")","redis_client",".","hmset","(","\"popularity_rankings\"",",","rankings_map",")","print","(","\"Setting popularity list...\"",")","# Populate the list rankings all symbols from most to least popular in order","redis_client",".","delete","(","\"popularity_list\"",")","redis_client",".","rpush","(","\"popularity_list\"",",","*","rankings_list",")","print","(","\"Finished computing popularity caches\"",")"],"url":"https:\/\/github.com\/Ameobea\/robintrack\/blob\/d74acc0b8e9f360864d1606134123a9430f8c223\/scraper\/src\/popularity_ranking.py#L45-L71"}
16
+ {"nwo":"Ameobea\/robintrack","sha":"d74acc0b8e9f360864d1606134123a9430f8c223","path":"scraper\/src\/popularity_ranking.py","language":"python","identifier":"populate_popularity_rankings","parameters":"(redis_client, get_db)","argument_list":"","return_statement":"","docstring":"Compute the popularity rankings cache and set it into Redis.","docstring_summary":"Compute the popularity rankings cache and set it into Redis.","docstring_tokens":["Compute","the","popularity","rankings","cache","and","set","it","into","Redis","."],"function":"def populate_popularity_rankings(redis_client, get_db):\n \"\"\" Compute the popularity rankings cache and set it into Redis. \"\"\"\n\n rankings = compute_popularity_rankings(get_db)\n set_popularity_rankings(redis_client, rankings)","function_tokens":["def","populate_popularity_rankings","(","redis_client",",","get_db",")",":","rankings","=","compute_popularity_rankings","(","get_db",")","set_popularity_rankings","(","redis_client",",","rankings",")"],"url":"https:\/\/github.com\/Ameobea\/robintrack\/blob\/d74acc0b8e9f360864d1606134123a9430f8c223\/scraper\/src\/popularity_ranking.py#L74-L78"}
17
+ {"nwo":"Ameobea\/robintrack","sha":"d74acc0b8e9f360864d1606134123a9430f8c223","path":"scraper\/src\/scrape_instruments.py","language":"python","identifier":"get_tradable_instruments","parameters":"(instruments: List[Dict[str, object]])","argument_list":"","return_statement":"return filter(lambda instrument: instrument.get(\"tradability\") == \"tradable\", instruments)","docstring":"Filters the provided list of instruments to only include those that are tradeable","docstring_summary":"Filters the provided list of instruments to only include those that are tradeable","docstring_tokens":["Filters","the","provided","list","of","instruments","to","only","include","those","that","are","tradeable"],"function":"def get_tradable_instruments(instruments: List[Dict[str, object]]) -> Iterable[Dict[str, object]]:\n \"\"\" Filters the provided list of instruments to only include those that are tradeable \"\"\"\n\n return filter(lambda instrument: instrument.get(\"tradability\") == \"tradable\", instruments)","function_tokens":["def","get_tradable_instruments","(","instruments",":","List","[","Dict","[","str",",","object","]","]",")","->","Iterable","[","Dict","[","str",",","object","]","]",":","return","filter","(","lambda","instrument",":","instrument",".","get","(","\"tradability\"",")","==","\"tradable\"",",","instruments",")"],"url":"https:\/\/github.com\/Ameobea\/robintrack\/blob\/d74acc0b8e9f360864d1606134123a9430f8c223\/scraper\/src\/scrape_instruments.py#L17-L20"}
18
+ {"nwo":"Ameobea\/robintrack","sha":"d74acc0b8e9f360864d1606134123a9430f8c223","path":"scripts\/aggregate_by_category.py","language":"python","identifier":"get_all_stock_fundamentals","parameters":"()","argument_list":"","return_statement":"return fundamentals_by_instrument_id","docstring":"Returns a dict mapping instrument id to stock fundamentals","docstring_summary":"Returns a dict mapping instrument id to stock fundamentals","docstring_tokens":["Returns","a","dict","mapping","instrument","id","to","stock","fundamentals"],"function":"def get_all_stock_fundamentals():\n \"\"\"\n Returns a dict mapping instrument id to stock fundamentals\n \"\"\"\n\n db = get_db()\n\n fundamentals_by_instrument_id = dict()\n all_fundamentals = list(db[\"fundamentals\"].find())\n for f in all_fundamentals:\n fundamentals_by_instrument_id[f[\"instrument_id\"]] = f\n\n return fundamentals_by_instrument_id","function_tokens":["def","get_all_stock_fundamentals","(",")",":","db","=","get_db","(",")","fundamentals_by_instrument_id","=","dict","(",")","all_fundamentals","=","list","(","db","[","\"fundamentals\"","]",".","find","(",")",")","for","f","in","all_fundamentals",":","fundamentals_by_instrument_id","[","f","[","\"instrument_id\"","]","]","=","f","return","fundamentals_by_instrument_id"],"url":"https:\/\/github.com\/Ameobea\/robintrack\/blob\/d74acc0b8e9f360864d1606134123a9430f8c223\/scripts\/aggregate_by_category.py#L14-L26"}
19
+ {"nwo":"Ameobea\/robintrack","sha":"d74acc0b8e9f360864d1606134123a9430f8c223","path":"python_common\/db.py","language":"python","identifier":"get_db","parameters":"()","argument_list":"","return_statement":"return mongo_client[\"robinhood\"]","docstring":"Returns an instance of the MongoDB database for this project.","docstring_summary":"Returns an instance of the MongoDB database for this project.","docstring_tokens":["Returns","an","instance","of","the","MongoDB","database","for","this","project","."],"function":"def get_db():\n \"\"\" Returns an instance of the MongoDB database for this project. \"\"\"\n\n return mongo_client[\"robinhood\"]","function_tokens":["def","get_db","(",")",":","return","mongo_client","[","\"robinhood\"","]"],"url":"https:\/\/github.com\/Ameobea\/robintrack\/blob\/d74acc0b8e9f360864d1606134123a9430f8c223\/python_common\/db.py#L26-L29"}
Anaconda-Platform__nb_conda.jsonl ADDED
The diff for this file is too large to render. See raw diff
AniDevTwitter__animeopenings.jsonl ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
1
+ {"nwo":"AniDevTwitter\/animeopenings","sha":"11b19a34158503a34db6995fb8b8ce3bc564a8e1","path":"encode\/fontConverter.py","language":"python","identifier":"OutputGrabber.start","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Start capturing the stream data.","docstring_summary":"Start capturing the stream data.","docstring_tokens":["Start","capturing","the","stream","data","."],"function":"def start(self):\n\t\t'''Start capturing the stream data.'''\n\t\tself.capturedtext = ''\n\t\t# Save a copy of the stream:\n\t\tself.streamfd = os.dup(self.origstreamfd)\n\t\t# Replace the original stream with our write pipe.\n\t\tos.dup2(self.pipe_in, self.origstreamfd)","function_tokens":["def","start","(","self",")",":","self",".","capturedtext","=","''","# Save a copy of the stream:","self",".","streamfd","=","os",".","dup","(","self",".","origstreamfd",")","# Replace the original stream with our write pipe.","os",".","dup2","(","self",".","pipe_in",",","self",".","origstreamfd",")"],"url":"https:\/\/github.com\/AniDevTwitter\/animeopenings\/blob\/11b19a34158503a34db6995fb8b8ce3bc564a8e1\/encode\/fontConverter.py#L28-L34"}
2
+ {"nwo":"AniDevTwitter\/animeopenings","sha":"11b19a34158503a34db6995fb8b8ce3bc564a8e1","path":"encode\/fontConverter.py","language":"python","identifier":"OutputGrabber.stop","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Stop capturing the stream data and save the text in `capturedtext`.","docstring_summary":"Stop capturing the stream data and save the text in `capturedtext`.","docstring_tokens":["Stop","capturing","the","stream","data","and","save","the","text","in","capturedtext","."],"function":"def stop(self):\n\t\t'''Stop capturing the stream data and save the text in `capturedtext`.'''\n\t\t# Print the escape character to make sure the loop in readOutput() stops.\n\t\tself.origstream.write(self.escape_char)\n\t\t# Flush the stream to make sure all our data goes in before the escape character.\n\t\tself.origstream.flush()\n\t\tself.readOutput()\n\t\t# Close the pipe.\n\t\tos.close(self.pipe_out)\n\t\t# Restore the original stream.\n\t\tos.dup2(self.streamfd, self.origstreamfd)","function_tokens":["def","stop","(","self",")",":","# Print the escape character to make sure the loop in readOutput() stops.","self",".","origstream",".","write","(","self",".","escape_char",")","# Flush the stream to make sure all our data goes in before the escape character.","self",".","origstream",".","flush","(",")","self",".","readOutput","(",")","# Close the pipe.","os",".","close","(","self",".","pipe_out",")","# Restore the original stream.","os",".","dup2","(","self",".","streamfd",",","self",".","origstreamfd",")"],"url":"https:\/\/github.com\/AniDevTwitter\/animeopenings\/blob\/11b19a34158503a34db6995fb8b8ce3bc564a8e1\/encode\/fontConverter.py#L36-L46"}
3
+ {"nwo":"AniDevTwitter\/animeopenings","sha":"11b19a34158503a34db6995fb8b8ce3bc564a8e1","path":"encode\/fontConverter.py","language":"python","identifier":"OutputGrabber.readOutput","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Read the stream data and save the text in `capturedtext`.","docstring_summary":"Read the stream data and save the text in `capturedtext`.","docstring_tokens":["Read","the","stream","data","and","save","the","text","in","capturedtext","."],"function":"def readOutput(self):\n\t\t'''Read the stream data and save the text in `capturedtext`.'''\n\t\ttry:\n\t\t\twhile True:\n\t\t\t\tdata = os.read(self.pipe_out, 1)\n\t\t\t\tif not data or self.escape_char in data:\n\t\t\t\t\tself.capturedtext += data.split(self.escape_char)[0]\n\t\t\t\t\tbreak\n\t\t\t\tself.capturedtext += data\n\t\texcept OSError:\n\t\t\tpass","function_tokens":["def","readOutput","(","self",")",":","try",":","while","True",":","data","=","os",".","read","(","self",".","pipe_out",",","1",")","if","not","data","or","self",".","escape_char","in","data",":","self",".","capturedtext","+=","data",".","split","(","self",".","escape_char",")","[","0","]","break","self",".","capturedtext","+=","data","except","OSError",":","pass"],"url":"https:\/\/github.com\/AniDevTwitter\/animeopenings\/blob\/11b19a34158503a34db6995fb8b8ce3bc564a8e1\/encode\/fontConverter.py#L48-L58"}
4
+ {"nwo":"AniDevTwitter\/animeopenings","sha":"11b19a34158503a34db6995fb8b8ce3bc564a8e1","path":"encode\/fontConverter.alt.py","language":"python","identifier":"OutputGrabber.start","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Start capturing the stream data.","docstring_summary":"Start capturing the stream data.","docstring_tokens":["Start","capturing","the","stream","data","."],"function":"def start(self):\n\t\t'''Start capturing the stream data.'''\n\t\tself.capturedtext = ''\n\t\t# Create a pipe so the stream can be captured.\n\t\tself.pipe_out, self.pipe_in = os.pipe()\n\t\t# Save a copy of the stream:\n\t\tself.streamfd = os.dup(self.origstreamfd)\n\t\t# Replace the original stream with our write pipe.\n\t\tos.dup2(self.pipe_in, self.origstreamfd)","function_tokens":["def","start","(","self",")",":","self",".","capturedtext","=","''","# Create a pipe so the stream can be captured.","self",".","pipe_out",",","self",".","pipe_in","=","os",".","pipe","(",")","# Save a copy of the stream:","self",".","streamfd","=","os",".","dup","(","self",".","origstreamfd",")","# Replace the original stream with our write pipe.","os",".","dup2","(","self",".","pipe_in",",","self",".","origstreamfd",")"],"url":"https:\/\/github.com\/AniDevTwitter\/animeopenings\/blob\/11b19a34158503a34db6995fb8b8ce3bc564a8e1\/encode\/fontConverter.alt.py#L28-L36"}
5
+ {"nwo":"AniDevTwitter\/animeopenings","sha":"11b19a34158503a34db6995fb8b8ce3bc564a8e1","path":"encode\/fontConverter.alt.py","language":"python","identifier":"OutputGrabber.stop","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Stop capturing the stream data and save the text in `capturedtext`.","docstring_summary":"Stop capturing the stream data and save the text in `capturedtext`.","docstring_tokens":["Stop","capturing","the","stream","data","and","save","the","text","in","capturedtext","."],"function":"def stop(self):\n\t\t'''Stop capturing the stream data and save the text in `capturedtext`.'''\n\t\t# Print the escape character to make sure the loop in readOutput() stops.\n\t\tself.origstream.write(self.escape_char.decode())\n\t\t# Flush the stream to make sure all our data goes in before the escape character.\n\t\tself.origstream.flush()\n\t\tself.readOutput()\n\t\t# Close the pipes.\n\t\tos.close(self.pipe_out)\n\t\tos.close(self.pipe_in)\n\t\tself.pipe_out, self.pipe_in = None, None\n\t\t# Restore the original stream.\n\t\tos.dup2(self.streamfd,self.origstreamfd)","function_tokens":["def","stop","(","self",")",":","# Print the escape character to make sure the loop in readOutput() stops.","self",".","origstream",".","write","(","self",".","escape_char",".","decode","(",")",")","# Flush the stream to make sure all our data goes in before the escape character.","self",".","origstream",".","flush","(",")","self",".","readOutput","(",")","# Close the pipes.","os",".","close","(","self",".","pipe_out",")","os",".","close","(","self",".","pipe_in",")","self",".","pipe_out",",","self",".","pipe_in","=","None",",","None","# Restore the original stream.","os",".","dup2","(","self",".","streamfd",",","self",".","origstreamfd",")"],"url":"https:\/\/github.com\/AniDevTwitter\/animeopenings\/blob\/11b19a34158503a34db6995fb8b8ce3bc564a8e1\/encode\/fontConverter.alt.py#L38-L50"}
6
+ {"nwo":"AniDevTwitter\/animeopenings","sha":"11b19a34158503a34db6995fb8b8ce3bc564a8e1","path":"encode\/fontConverter.alt.py","language":"python","identifier":"OutputGrabber.readOutput","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Read the stream data and save the text in `capturedtext`.","docstring_summary":"Read the stream data and save the text in `capturedtext`.","docstring_tokens":["Read","the","stream","data","and","save","the","text","in","capturedtext","."],"function":"def readOutput(self):\n\t\t'''Read the stream data and save the text in `capturedtext`.'''\n\t\tbyte = os.read(self.pipe_out,1)\n\t\tdata = b''\n\t\twhile byte not in (b'',self.escape_char):\n\t\t\tdata += byte\n\t\t\tbyte = os.read(self.pipe_out,1)\n\t\tself.capturedtext = data.decode(self.origstream.encoding, errors='replace')","function_tokens":["def","readOutput","(","self",")",":","byte","=","os",".","read","(","self",".","pipe_out",",","1",")","data","=","b''","while","byte","not","in","(","b''",",","self",".","escape_char",")",":","data","+=","byte","byte","=","os",".","read","(","self",".","pipe_out",",","1",")","self",".","capturedtext","=","data",".","decode","(","self",".","origstream",".","encoding",",","errors","=","'replace'",")"],"url":"https:\/\/github.com\/AniDevTwitter\/animeopenings\/blob\/11b19a34158503a34db6995fb8b8ce3bc564a8e1\/encode\/fontConverter.alt.py#L52-L59"}
Arno0x__DNSExfiltrator.jsonl ADDED
@@ -0,0 +1,2 @@
 
 
1
+ {"nwo":"Arno0x\/DNSExfiltrator","sha":"8faa972408b0384416fffd5b4d42a7aa00526ca8","path":"dnsexfiltrator.py","language":"python","identifier":"progress","parameters":"(count, total, status='')","argument_list":"","return_statement":"","docstring":"Print a progress bar - https:\/\/gist.github.com\/vladignatyev\/06860ec2040cb497f0f3","docstring_summary":"Print a progress bar - https:\/\/gist.github.com\/vladignatyev\/06860ec2040cb497f0f3","docstring_tokens":["Print","a","progress","bar","-","https",":","\/\/","gist",".","github",".","com","\/","vladignatyev","\/","06860ec2040cb497f0f3"],"function":"def progress(count, total, status=''):\n\t\"\"\"\n\tPrint a progress bar - https:\/\/gist.github.com\/vladignatyev\/06860ec2040cb497f0f3\n\t\"\"\"\n\tbar_len = 60\n\tfilled_len = int(round(bar_len * count \/ float(total)))\n\n\tpercents = round(100.0 * count \/ float(total), 1)\n\tbar = '=' * filled_len + '-' * (bar_len - filled_len)\n\tsys.stdout.write('[%s] %s%s\\t%s\\t\\r' % (bar, percents, '%', status))\n\tsys.stdout.flush()","function_tokens":["def","progress","(","count",",","total",",","status","=","''",")",":","bar_len","=","60","filled_len","=","int","(","round","(","bar_len","*","count","\/","float","(","total",")",")",")","percents","=","round","(","100.0","*","count","\/","float","(","total",")",",","1",")","bar","=","'='","*","filled_len","+","'-'","*","(","bar_len","-","filled_len",")","sys",".","stdout",".","write","(","'[%s] %s%s\\t%s\\t\\r'","%","(","bar",",","percents",",","'%'",",","status",")",")","sys",".","stdout",".","flush","(",")"],"url":"https:\/\/github.com\/Arno0x\/DNSExfiltrator\/blob\/8faa972408b0384416fffd5b4d42a7aa00526ca8\/dnsexfiltrator.py#L43-L53"}
2
+ {"nwo":"Arno0x\/DNSExfiltrator","sha":"8faa972408b0384416fffd5b4d42a7aa00526ca8","path":"dnsexfiltrator.py","language":"python","identifier":"color","parameters":"(string, color=None)","argument_list":"","return_statement":"","docstring":"Author: HarmJ0y, borrowed from Empire\n Change text color for the Linux terminal.","docstring_summary":"Author: HarmJ0y, borrowed from Empire\n Change text color for the Linux terminal.","docstring_tokens":["Author",":","HarmJ0y","borrowed","from","Empire","Change","text","color","for","the","Linux","terminal","."],"function":"def color(string, color=None):\n \"\"\"\n Author: HarmJ0y, borrowed from Empire\n Change text color for the Linux terminal.\n \"\"\"\n \n attr = []\n # bold\n attr.append('1')\n \n if color:\n if color.lower() == \"red\":\n attr.append('31')\n elif color.lower() == \"green\":\n attr.append('32')\n elif color.lower() == \"blue\":\n attr.append('34')\n return '\\x1b[%sm%s\\x1b[0m' % (';'.join(attr), string)\n\n else:\n if string.strip().startswith(\"[!]\"):\n attr.append('31')\n return '\\x1b[%sm%s\\x1b[0m' % (';'.join(attr), string)\n elif string.strip().startswith(\"[+]\"):\n attr.append('32')\n return '\\x1b[%sm%s\\x1b[0m' % (';'.join(attr), string)\n elif string.strip().startswith(\"[?]\"):\n attr.append('33')\n return '\\x1b[%sm%s\\x1b[0m' % (';'.join(attr), string)\n elif string.strip().startswith(\"[*]\"):\n attr.append('34')\n return '\\x1b[%sm%s\\x1b[0m' % (';'.join(attr), string)\n else:\n return string","function_tokens":["def","color","(","string",",","color","=","None",")",":","attr","=","[","]","# bold","attr",".","append","(","'1'",")","if","color",":","if","color",".","lower","(",")","==","\"red\"",":","attr",".","append","(","'31'",")","elif","color",".","lower","(",")","==","\"green\"",":","attr",".","append","(","'32'",")","elif","color",".","lower","(",")","==","\"blue\"",":","attr",".","append","(","'34'",")","return","'\\x1b[%sm%s\\x1b[0m'","%","(","';'",".","join","(","attr",")",",","string",")","else",":","if","string",".","strip","(",")",".","startswith","(","\"[!]\"",")",":","attr",".","append","(","'31'",")","return","'\\x1b[%sm%s\\x1b[0m'","%","(","';'",".","join","(","attr",")",",","string",")","elif","string",".","strip","(",")",".","startswith","(","\"[+]\"",")",":","attr",".","append","(","'32'",")","return","'\\x1b[%sm%s\\x1b[0m'","%","(","';'",".","join","(","attr",")",",","string",")","elif","string",".","strip","(",")",".","startswith","(","\"[?]\"",")",":","attr",".","append","(","'33'",")","return","'\\x1b[%sm%s\\x1b[0m'","%","(","';'",".","join","(","attr",")",",","string",")","elif","string",".","strip","(",")",".","startswith","(","\"[*]\"",")",":","attr",".","append","(","'34'",")","return","'\\x1b[%sm%s\\x1b[0m'","%","(","';'",".","join","(","attr",")",",","string",")","else",":","return","string"],"url":"https:\/\/github.com\/Arno0x\/DNSExfiltrator\/blob\/8faa972408b0384416fffd5b4d42a7aa00526ca8\/dnsexfiltrator.py#L85-L118"}
AudiusProject__audius-protocol.jsonl ADDED
The diff for this file is too large to render. See raw diff
BE-Kits__xe-crawler.jsonl ADDED
@@ -0,0 +1,2 @@
 
 
1
+ {"nwo":"wx-chevalier\/sentinel-crawler","sha":"8f0e11dc690e34902fe801f29062e3b73c571094","path":"adapters\/scrapy-crawler\/api-crawler\/pipelines\/distinct_pipeline.py","language":"python","identifier":"DistinctPipeline.is_similar","parameters":"(self, sourceUrl, targetUrl)","argument_list":"","return_statement":"","docstring":"\u5224\u65ad\u4e24\u4e2a Url \u662f\u5426\u76f8\u4f3c\uff0c\u5982\u679c\u76f8\u4f3c\u5219\u5ffd\u7565\uff0c\u5426\u5219\u4fdd\u7559","docstring_summary":"\u5224\u65ad\u4e24\u4e2a Url \u662f\u5426\u76f8\u4f3c\uff0c\u5982\u679c\u76f8\u4f3c\u5219\u5ffd\u7565\uff0c\u5426\u5219\u4fdd\u7559","docstring_tokens":["\u5224\u65ad\u4e24\u4e2a","Url","\u662f\u5426\u76f8\u4f3c\uff0c\u5982\u679c\u76f8\u4f3c\u5219\u5ffd\u7565\uff0c\u5426\u5219\u4fdd\u7559"],"function":"def is_similar(self, sourceUrl, targetUrl):\n '''\n \u5224\u65ad\u4e24\u4e2a Url \u662f\u5426\u76f8\u4f3c\uff0c\u5982\u679c\u76f8\u4f3c\u5219\u5ffd\u7565\uff0c\u5426\u5219\u4fdd\u7559\n '''\n pass","function_tokens":["def","is_similar","(","self",",","sourceUrl",",","targetUrl",")",":","pass"],"url":"https:\/\/github.com\/wx-chevalier\/sentinel-crawler\/blob\/8f0e11dc690e34902fe801f29062e3b73c571094\/adapters\/scrapy-crawler\/api-crawler\/pipelines\/distinct_pipeline.py#L7-L11"}
2
+ {"nwo":"wx-chevalier\/sentinel-crawler","sha":"8f0e11dc690e34902fe801f29062e3b73c571094","path":"adapters\/scrapy-crawler\/api-crawler\/spiders\/extract_api.py","language":"python","identifier":"GetallurlsSpider.Filter_similar_url","parameters":"(self, url)","argument_list":"","return_statement":"","docstring":"URL\u76f8\u4f3c\u5ea6\u8fc7\u6ee4\n \u591a\u4e2a\u76f8\u4f3curl\u4fdd\u7559\u4e00\u4e2a\u5373\u53ef","docstring_summary":"URL\u76f8\u4f3c\u5ea6\u8fc7\u6ee4\n \u591a\u4e2a\u76f8\u4f3curl\u4fdd\u7559\u4e00\u4e2a\u5373\u53ef","docstring_tokens":["URL\u76f8\u4f3c\u5ea6\u8fc7\u6ee4","\u591a\u4e2a\u76f8\u4f3curl\u4fdd\u7559\u4e00\u4e2a\u5373\u53ef"],"function":"def Filter_similar_url (self, url):\n '''\n URL\u76f8\u4f3c\u5ea6\u8fc7\u6ee4\n \u591a\u4e2a\u76f8\u4f3curl\u4fdd\u7559\u4e00\u4e2a\u5373\u53ef\n '''\n pass","function_tokens":["def","Filter_similar_url","(","self",",","url",")",":","pass"],"url":"https:\/\/github.com\/wx-chevalier\/sentinel-crawler\/blob\/8f0e11dc690e34902fe801f29062e3b73c571094\/adapters\/scrapy-crawler\/api-crawler\/spiders\/extract_api.py#L70-L75"}
BelaPlatform__Bela.jsonl ADDED
@@ -0,0 +1,4 @@
 
 
 
 
1
+ {"nwo":"BelaPlatform\/Bela","sha":"b6491178b859eb8977f494eb9ba4806920eea4b0","path":"scripts\/hvresources\/uploader.py","language":"python","identifier":"__zip_dir","parameters":"(in_dir, zip_path, file_filter=None)","argument_list":"","return_statement":"return zip_path","docstring":"Recursively zip an entire directory with an optional file filter","docstring_summary":"Recursively zip an entire directory with an optional file filter","docstring_tokens":["Recursively","zip","an","entire","directory","with","an","optional","file","filter"],"function":"def __zip_dir(in_dir, zip_path, file_filter=None):\n \"\"\" Recursively zip an entire directory with an optional file filter\n \"\"\"\n zf = zipfile.ZipFile(zip_path, mode=\"w\", compression=zipfile.ZIP_DEFLATED)\n for subdir, dirs, files in os.walk(in_dir):\n for f in files:\n if (file_filter is None) or (f.lower().split(\".\")[-1] in file_filter):\n zf.write(\n filename=os.path.join(subdir,f),\n arcname=os.path.relpath(os.path.join(subdir,f), start=in_dir))\n return zip_path","function_tokens":["def","__zip_dir","(","in_dir",",","zip_path",",","file_filter","=","None",")",":","zf","=","zipfile",".","ZipFile","(","zip_path",",","mode","=","\"w\"",",","compression","=","zipfile",".","ZIP_DEFLATED",")","for","subdir",",","dirs",",","files","in","os",".","walk","(","in_dir",")",":","for","f","in","files",":","if","(","file_filter","is","None",")","or","(","f",".","lower","(",")",".","split","(","\".\"",")","[","-","1","]","in","file_filter",")",":","zf",".","write","(","filename","=","os",".","path",".","join","(","subdir",",","f",")",",","arcname","=","os",".","path",".","relpath","(","os",".","path",".","join","(","subdir",",","f",")",",","start","=","in_dir",")",")","return","zip_path"],"url":"https:\/\/github.com\/BelaPlatform\/Bela\/blob\/b6491178b859eb8977f494eb9ba4806920eea4b0\/scripts\/hvresources\/uploader.py#L92-L102"}
2
+ {"nwo":"BelaPlatform\/Bela","sha":"b6491178b859eb8977f494eb9ba4806920eea4b0","path":"scripts\/hvresources\/uploader.py","language":"python","identifier":"__unzip","parameters":"(zip_path, target_dir)","argument_list":"","return_statement":"","docstring":"Unzip a file to a given directory. All destination files are overwritten.","docstring_summary":"Unzip a file to a given directory. All destination files are overwritten.","docstring_tokens":["Unzip","a","file","to","a","given","directory",".","All","destination","files","are","overwritten","."],"function":"def __unzip(zip_path, target_dir):\n \"\"\" Unzip a file to a given directory. All destination files are overwritten.\n \"\"\"\n zipfile.ZipFile(zip_path).extractall(target_dir)","function_tokens":["def","__unzip","(","zip_path",",","target_dir",")",":","zipfile",".","ZipFile","(","zip_path",")",".","extractall","(","target_dir",")"],"url":"https:\/\/github.com\/BelaPlatform\/Bela\/blob\/b6491178b859eb8977f494eb9ba4806920eea4b0\/scripts\/hvresources\/uploader.py#L104-L107"}
3
+ {"nwo":"BelaPlatform\/Bela","sha":"b6491178b859eb8977f494eb9ba4806920eea4b0","path":"scripts\/hvresources\/uploader.py","language":"python","identifier":"__get_file_url_stub_for_generator","parameters":"(json_api, g)","argument_list":"","return_statement":"return None","docstring":"Returns the file link for a specific generator.\n Returns None if no link could be found.","docstring_summary":"Returns the file link for a specific generator.\n Returns None if no link could be found.","docstring_tokens":["Returns","the","file","link","for","a","specific","generator",".","Returns","None","if","no","link","could","be","found","."],"function":"def __get_file_url_stub_for_generator(json_api, g):\n \"\"\" Returns the file link for a specific generator.\n Returns None if no link could be found.\n \"\"\"\n for i in json_api[\"included\"]:\n if (i[\"type\"] == \"file\") and (g == i[\"data\"][\"buildId\"]):\n return i[\"links\"][\"self\"]\n return None","function_tokens":["def","__get_file_url_stub_for_generator","(","json_api",",","g",")",":","for","i","in","json_api","[","\"included\"","]",":","if","(","i","[","\"type\"","]","==","\"file\"",")","and","(","g","==","i","[","\"data\"","]","[","\"buildId\"","]",")",":","return","i","[","\"links\"","]","[","\"self\"","]","return","None"],"url":"https:\/\/github.com\/BelaPlatform\/Bela\/blob\/b6491178b859eb8977f494eb9ba4806920eea4b0\/scripts\/hvresources\/uploader.py#L109-L116"}
4
+ {"nwo":"BelaPlatform\/Bela","sha":"b6491178b859eb8977f494eb9ba4806920eea4b0","path":"scripts\/hvresources\/uploader.py","language":"python","identifier":"upload","parameters":"(input_dir, output_dirs=None, name=None, owner=None, generators=None, b=False, y=False, release=None, release_override=False, domain=None, verbose=False, token=None, clear_token=False, service_token=None, force_new_patch=False, archive_only=False)","argument_list":"","return_statement":"return exit_code, reply_json","docstring":"Upload a directory to the Heavy Cloud Service.\n\n Parameters\n ----------\n input_dir : str\n Directory containing _main.pd file.\n\n output_dirs : list, optional\n List of directories where the output should be placed. Usually the output directory list has only one element.\n If no argument is given, the input directory will be used.\n\n name : str, optional\n The name of the patch.\n If no argument is given, the name \"heavy\" is used.\n\n owner : str, optional\n The name of the owner of the patch. Usually this is an organisation.\n If no argument is given, the submitting user name is used.\n\n generators : list, optional\n A list of generators e.g. 'c', 'unity', or 'vst2-x86'\n\n b : bool, optional\n If True, puts the results of each generator into its own directory.\n False by default in which case all files are put into the same directory.\n\n y : bool, optional\n If True, extract only generated C files, static files are deleted. False by default.\n\n release : str, optional\n The name of the release to use for compiling.\n\n release_override : bool, optional\n Disable the validity check for a requested release. Forces sending a\n release request to the server.\n\n verbose : bool, optional\n False by default.\n\n token : str, optional\n The token used to identify the user to Heavy Cloud Service.\n By default the stored token will be used.\n\n clear_token : bool, optional\n Clears and ignores any existing stored tokens. Requests a new one from the command line.\n\n service_token : str, optional\n Pass an optional service token to be used instead of the default heavy_uploader.\n\n force_new_patch : bool, optional\n Indicate that a new patch should be created with the given name, if it does not yet exist.\n\n archive_only : bool, optional\n Only retrieve the archive from the server and place it in the destination folder without unzipping it.","docstring_summary":"Upload a directory to the Heavy Cloud Service.","docstring_tokens":["Upload","a","directory","to","the","Heavy","Cloud","Service","."],"function":"def upload(input_dir, output_dirs=None, name=None, owner=None, generators=None, b=False, y=False, release=None, release_override=False, domain=None, verbose=False, token=None, clear_token=False, service_token=None, force_new_patch=False, archive_only=False):\n \"\"\" Upload a directory to the Heavy Cloud Service.\n\n Parameters\n ----------\n input_dir : str\n Directory containing _main.pd file.\n\n output_dirs : list, optional\n List of directories where the output should be placed. Usually the output directory list has only one element.\n If no argument is given, the input directory will be used.\n\n name : str, optional\n The name of the patch.\n If no argument is given, the name \"heavy\" is used.\n\n owner : str, optional\n The name of the owner of the patch. Usually this is an organisation.\n If no argument is given, the submitting user name is used.\n\n generators : list, optional\n A list of generators e.g. 'c', 'unity', or 'vst2-x86'\n\n b : bool, optional\n If True, puts the results of each generator into its own directory.\n False by default in which case all files are put into the same directory.\n\n y : bool, optional\n If True, extract only generated C files, static files are deleted. False by default.\n\n release : str, optional\n The name of the release to use for compiling.\n\n release_override : bool, optional\n Disable the validity check for a requested release. Forces sending a\n release request to the server.\n\n verbose : bool, optional\n False by default.\n\n token : str, optional\n The token used to identify the user to Heavy Cloud Service.\n By default the stored token will be used.\n\n clear_token : bool, optional\n Clears and ignores any existing stored tokens. Requests a new one from the command line.\n\n service_token : str, optional\n Pass an optional service token to be used instead of the default heavy_uploader.\n\n force_new_patch : bool, optional\n Indicate that a new patch should be created with the given name, if it does not yet exist.\n\n archive_only : bool, optional\n Only retrieve the archive from the server and place it in the destination folder without unzipping it.\n \"\"\"\n # https:\/\/github.com\/numpy\/numpy\/blob\/master\/doc\/HOWTO_DOCUMENT.rst.txt\n\n try:\n # set default values\n name = name or \"heavy\"\n domain = domain or \"https:\/\/enzienaudio.com\"\n exit_code = ErrorCodes.CODE_OK\n reply_json = {}\n temp_dir = None\n post_data = {}\n\n # token should be stored in ~\/.heavy\/token\n token_path = os.path.expanduser(os.path.join(\"~\/\", \".heavy\", \"token\"))\n\n if token is None:\n if os.path.exists(token_path):\n if clear_token:\n os.remove(token_path)\n else:\n with open(token_path, \"r\") as f:\n token = f.read().strip()\n\n if token is None:\n print \"Please provide a user token from enzienaudio.com. \" \\\n \"Create or copy one from https:\/\/enzienaudio.com\/getmytokens\/.\"\n token = getpass.getpass(\"Enter user token: \")\n token = token.strip()\n\n # write token to file\n if not os.path.exists(os.path.dirname(token_path)):\n # ensure that the .heavy directory exists\n os.makedirs(os.path.dirname(token_path))\n with open(token_path, \"w\") as f:\n f.write(token)\n os.chmod(token_path, stat.S_IRUSR | stat.S_IWUSR) # force rw------- permissions on the file\n\n tick = time.time()\n\n # check the validity of the token\n try:\n # check the valifity of the token\n payload = json.loads(base64.urlsafe_b64decode(token.split(\".\")[1]))\n payload[\"startDate\"] = datetime.datetime.strptime(payload[\"startDate\"], \"%Y-%m-%dT%H:%M:%S.%f\")\n\n # ensure that the token is valid\n now = datetime.datetime.utcnow()\n assert payload[\"startDate\"] <= now\n\n if owner is None:\n # if an owner is not supplied, default to the user name in the token\n owner = payload[\"name\"]\n except Exception as e:\n print \"The user token is invalid. Generate a new one at https:\/\/enzienaudio.com\/getmytokens\/.\"\n os.remove(token_path)\n exit_code = ErrorCodes.CODE_INVALID_TOKEN\n raise e\n\n # if there is a user-supplied service token, do a basic validity check\n if service_token:\n try:\n # check the valifity of the token\n payload = json.loads(base64.urlsafe_b64decode(token.split(\".\")[1]))\n payload[\"startDate\"] = datetime.datetime.strptime(payload[\"startDate\"], \"%Y-%m-%dT%H:%M:%S.%f\")\n\n # ensure that the token is valid\n now = datetime.datetime.utcnow()\n assert payload[\"startDate\"] <= now\n\n assert \"service\" in payload, \"'service' field required in service token payload.\"\n except Exception as e:\n print \"The supplied service token is invalid. A default token will be used.\"\n service_token = __HV_UPLOADER_SERVICE_TOKEN\n else:\n service_token = __HV_UPLOADER_SERVICE_TOKEN\n\n # create the session to pool all requests\n s = requests.Session()\n\n # parse the optional release argument\n if release:\n if not release_override:\n # check the validity of the current release\n releases_json = s.get(urlparse.urljoin(domain, \"\/a\/releases\/\")).json()\n if release in releases_json:\n today = datetime.datetime.now()\n valid_until = datetime.datetime.strptime(releases_json[release][\"validUntil\"], \"%Y-%m-%d\")\n if today > valid_until:\n print \"{0}Warning:{1} The release \\\"{2}\\\" expired on {3}. It may be removed at any time!\".format(\n Colours.yellow, Colours.end,\n release,\n releases_json[release][\"validUntil\"])\n elif (valid_until - today) <= datetime.timedelta(weeks=4):\n print \"{0}Warning:{1} The release \\\"{2}\\\" will expire soon on {3}.\".format(\n Colours.yellow, Colours.end,\n release,\n releases_json[release][\"validUntil\"])\n else:\n print \"{0}Error:{1} The release \\\"{2}\\\" is not available. Available releases are:\".format(\n Colours.red, Colours.end,\n release)\n for k,v in releases_json.items():\n print \"* {0} ({1})\".format(\n k,\n v[\"releaseDate\"])\n raise UploaderException(ErrorCodes.CODE_RELEASE_NOT_AVAILABLE)\n\n post_data[\"release\"] = release\n\n # make a temporary directory\n temp_dir = tempfile.mkdtemp(prefix=\"lroyal-\")\n\n # zip up the pd directory into the temporary directory\n if not os.path.exists(os.path.join(input_dir, \"_main.pd\")):\n raise UploaderException(\n ErrorCodes.CODE_MAIN_NOT_FOUND,\n \"Root Pd directory does not contain a file named _main.pd.\")\n zip_path = __zip_dir(\n input_dir,\n os.path.join(temp_dir, \"archive.zip\"),\n file_filter={\"pd\"})\n if os.stat(zip_path).st_size > __HV_MAX_UPLOAD_SIZE:\n raise UploaderException(\n ErrorCodes.CODE_UPLOAD_ASSET_TOO_LARGE,\n \"The target directory, zipped, is {0} bytes. The maximum upload size of 1MB.\".format(\n os.stat(zip_path).st_size))\n\n # the outputs to generate\n generators = list({s.lower() for s in set(generators or [])} & __SUPPORTED_GENERATOR_SET)\n\n # check if the patch exists already. Ask to create it if it doesn't exist\n r = s.get(\n urlparse.urljoin(domain, \"\/a\/patches\/{0}\/{1}\/\".format(owner, name)),\n headers={\n \"Accept\": \"application\/json\",\n \"Authorization\": \"Bearer \" + token,\n \"X-Heavy-Service-Token\": service_token\n })\n r.raise_for_status()\n reply_json = r.json()\n if \"errors\" in reply_json:\n if reply_json[\"errors\"][0][\"status\"] == \"404\":\n # the patch does not exist\n if force_new_patch:\n create_new_patch = True\n else:\n create_new_patch = raw_input(\"A patch called \\\"{0}\\\" does not exist for owner \\\"{1}\\\". Create it? (y\/n):\".format(name, owner))\n create_new_patch = (create_new_patch == \"y\")\n if create_new_patch:\n r = s.post(\n urlparse.urljoin(domain, \"\/a\/patches\/\"),\n data={\"owner_name\":owner, \"name\":name, \"public\":\"true\"},\n headers={\n \"Accept\": \"application\/json\",\n \"Authorization\": \"Bearer \" + token,\n \"X-Heavy-Service-Token\": service_token\n })\n r.raise_for_status()\n reply_json = r.json()\n if \"errors\" in reply_json:\n raise UploaderException(\n ErrorCodes.CODE_NEW_PATCH_FAIL,\n reply_json[\"errors\"][0][\"detail\"])\n else:\n pass # no errors? everything is cool! Proceed.\n else:\n UploaderException(\n ErrorCodes.CODE_NEW_PATCH_FAIL,\n \"A patch called \\\"{0}\\\" does not exist for owner \\\"{1}\\\"\".format(owner, name))\n else:\n raise UploaderException(\n ErrorCodes.CODE_NEW_PATCH_FAIL,\n reply_json[\"errors\"][0][\"detail\"])\n else:\n pass # the patch exists, move on\n\n # upload the job, get the response back\n r = s.post(\n urlparse.urljoin(domain, \"\/a\/patches\/{0}\/{1}\/jobs\/\".format(owner, name)),\n data=post_data,\n headers={\n \"Accept\": \"application\/json\",\n \"Authorization\": \"Bearer \" + token,\n \"X-Heavy-Service-Token\": service_token\n },\n timeout=None, # some builds can take a very long time\n files={\"file\": (os.path.basename(zip_path), open(zip_path, \"rb\"), \"application\/zip\")})\n r.raise_for_status()\n\n # decode the JSON API response (See below for an example response)\n reply_json = r.json()\n if verbose:\n print json.dumps(reply_json, sort_keys=True, indent=2, separators=(\",\", \": \"))\n\n # print any warnings\n for i,x in enumerate(reply_json.get(\"warnings\",[])):\n print \"{3}) {0}Warning:{1} {2}\".format(\n Colours.yellow, Colours.end, x[\"detail\"], i+1)\n\n # check for errors\n if len(reply_json.get(\"errors\",[])) > 0:\n for i,x in enumerate(reply_json[\"errors\"]):\n print \"{3}) {0}Error:{1} {2}\".format(\n Colours.red, Colours.end, x[\"detail\"], i+1)\n raise UploaderException(ErrorCodes.CODE_HEAVY_COMPILE_ERRORS)\n\n print \"Job URL:\", urlparse.urljoin(domain, reply_json[\"data\"][\"links\"][\"html\"])\n print \"Heavy release:\", reply_json[\"data\"][\"attributes\"][\"release\"]\n\n if len(generators) > 0:\n print \"Downloaded files placed in:\"\n\n # retrieve all requested files\n for i,g in enumerate(generators):\n file_url = urlparse.urljoin(\n domain,\n \"\/\".join([\n reply_json[\"data\"][\"links\"][\"html\"],\n g.replace(\"-\", \"\/\"),\n \"archive.zip\"\n ])\n )\n if file_url and (len(output_dirs) > i or b):\n r = s.get(\n file_url,\n headers={\n \"Authorization\": \"Bearer \" + token,\n \"X-Heavy-Service-Token\": service_token\n },\n timeout=None # some builds can take a very long time\n )\n r.raise_for_status()\n\n # prepare the target directory for the files\n if b:\n target_dir = os.path.join(os.path.abspath(os.path.expanduser(output_dirs[0])), g)\n else:\n target_dir = os.path.abspath(os.path.expanduser(output_dirs[i]))\n if not os.path.exists(target_dir):\n os.makedirs(target_dir) # ensure that the output directory exists\n\n # write the reply to file to the final destination if archive_only, else temporary\n c_zip_path = os.path.join(target_dir if archive_only else temp_dir, \"archive.{0}.zip\".format(g))\n with open(c_zip_path, \"wb\") as f:\n f.write(r.content)\n\n if not archive_only:\n # unzip the files to where they belong\n __unzip(c_zip_path, target_dir)\n\n if g == \"c-src\" and y:\n keep_files = (\"_{0}.h\".format(name), \"_{0}.hpp\".format(name), \"_{0}.cpp\".format(name))\n for f in os.listdir(target_dir):\n if not f.endswith(keep_files):\n os.remove(os.path.join(target_dir, f))\n\n print \" * {0}: {1}\".format(g, target_dir)\n else:\n print \" * {0}Warning:{1} {2} files could not be retrieved.\".format(\n Colours.yellow, Colours.end,\n g)\n\n print \"Total request time: {0}ms\".format(int(1000.0*(time.time()-tick)))\n\n except UploaderException as e:\n exit_code = e.code\n if e.message:\n print \"{0}Error:{1} {2}\".format(Colours.red, Colours.end, e.message)\n except requests.ConnectionError as e:\n print \"{0}Error:{1} Could not connect to server. Is the server down? Is the internet down?\\n{2}\".format(Colours.red, Colours.end, e)\n exit_code = ErrorCodes.CODE_CONNECTION_ERROR\n except requests.Timeout as e:\n print \"{0}Error:{1} Connection to server timed out. The server might be overloaded. Try again later?\\n{2}\".format(Colours.red, Colours.end, e)\n exit_code = ErrorCodes.CODE_CONNECTION_TIMEOUT\n except requests.HTTPError as e:\n if e.response.status_code == requests.status_codes.codes.unauthorized:\n print \"{0}Error:{1} Unknown username or password.\".format(Colours.red, Colours.end)\n else:\n print \"{0}Error:{1} An HTTP error has occurred with URL {2}\\n{3}\".format(Colours.red, Colours.end, e.request.path_url, e)\n exit_code = ErrorCodes.CODE_CONNECTION_400_500\n except Exception as e:\n # a generic catch for any other exception\n exit_code = exit_code if exit_code != ErrorCodes.CODE_OK else ErrorCodes.CODE_EXCEPTION\n print \"{0}Error:{1} ({2}) {3}\".format(Colours.red, Colours.end, e.__class__, e)\n print \"Getting a weird error? Get the latest version with 'pip install hv-uploader -U', or check for issues at https:\/\/github.com\/enzienaudio\/heavy\/issues.\"\n finally:\n if temp_dir:\n shutil.rmtree(temp_dir) # delete the temporary directory no matter what\n\n return exit_code, reply_json","function_tokens":["def","upload","(","input_dir",",","output_dirs","=","None",",","name","=","None",",","owner","=","None",",","generators","=","None",",","b","=","False",",","y","=","False",",","release","=","None",",","release_override","=","False",",","domain","=","None",",","verbose","=","False",",","token","=","None",",","clear_token","=","False",",","service_token","=","None",",","force_new_patch","=","False",",","archive_only","=","False",")",":","# https:\/\/github.com\/numpy\/numpy\/blob\/master\/doc\/HOWTO_DOCUMENT.rst.txt","try",":","# set default values","name","=","name","or","\"heavy\"","domain","=","domain","or","\"https:\/\/enzienaudio.com\"","exit_code","=","ErrorCodes",".","CODE_OK","reply_json","=","{","}","temp_dir","=","None","post_data","=","{","}","# token should be stored in ~\/.heavy\/token","token_path","=","os",".","path",".","expanduser","(","os",".","path",".","join","(","\"~\/\"",",","\".heavy\"",",","\"token\"",")",")","if","token","is","None",":","if","os",".","path",".","exists","(","token_path",")",":","if","clear_token",":","os",".","remove","(","token_path",")","else",":","with","open","(","token_path",",","\"r\"",")","as","f",":","token","=","f",".","read","(",")",".","strip","(",")","if","token","is","None",":","print","\"Please provide a user token from enzienaudio.com. \"","\"Create or copy one from https:\/\/enzienaudio.com\/getmytokens\/.\"","token","=","getpass",".","getpass","(","\"Enter user token: \"",")","token","=","token",".","strip","(",")","# write token to file","if","not","os",".","path",".","exists","(","os",".","path",".","dirname","(","token_path",")",")",":","# ensure that the .heavy directory exists","os",".","makedirs","(","os",".","path",".","dirname","(","token_path",")",")","with","open","(","token_path",",","\"w\"",")","as","f",":","f",".","write","(","token",")","os",".","chmod","(","token_path",",","stat",".","S_IRUSR","|","stat",".","S_IWUSR",")","# force rw------- permissions on the file","tick","=","time",".","time","(",")","# check the validity of the token","try",":","# check the valifity of the token","payload","=","json",".","loads","(","base64",".","urlsafe_b64decode","(","token",".","split","(","\".\"",")","[","1","]",")",")","payload","[","\"startDate\"","]","=","datetime",".","datetime",".","strptime","(","payload","[","\"startDate\"","]",",","\"%Y-%m-%dT%H:%M:%S.%f\"",")","# ensure that the token is valid","now","=","datetime",".","datetime",".","utcnow","(",")","assert","payload","[","\"startDate\"","]","<=","now","if","owner","is","None",":","# if an owner is not supplied, default to the user name in the token","owner","=","payload","[","\"name\"","]","except","Exception","as","e",":","print","\"The user token is invalid. Generate a new one at https:\/\/enzienaudio.com\/getmytokens\/.\"","os",".","remove","(","token_path",")","exit_code","=","ErrorCodes",".","CODE_INVALID_TOKEN","raise","e","# if there is a user-supplied service token, do a basic validity check","if","service_token",":","try",":","# check the valifity of the token","payload","=","json",".","loads","(","base64",".","urlsafe_b64decode","(","token",".","split","(","\".\"",")","[","1","]",")",")","payload","[","\"startDate\"","]","=","datetime",".","datetime",".","strptime","(","payload","[","\"startDate\"","]",",","\"%Y-%m-%dT%H:%M:%S.%f\"",")","# ensure that the token is valid","now","=","datetime",".","datetime",".","utcnow","(",")","assert","payload","[","\"startDate\"","]","<=","now","assert","\"service\"","in","payload",",","\"'service' field required in service token payload.\"","except","Exception","as","e",":","print","\"The supplied service token is invalid. A default token will be used.\"","service_token","=","__HV_UPLOADER_SERVICE_TOKEN","else",":","service_token","=","__HV_UPLOADER_SERVICE_TOKEN","# create the session to pool all requests","s","=","requests",".","Session","(",")","# parse the optional release argument","if","release",":","if","not","release_override",":","# check the validity of the current release","releases_json","=","s",".","get","(","urlparse",".","urljoin","(","domain",",","\"\/a\/releases\/\"",")",")",".","json","(",")","if","release","in","releases_json",":","today","=","datetime",".","datetime",".","now","(",")","valid_until","=","datetime",".","datetime",".","strptime","(","releases_json","[","release","]","[","\"validUntil\"","]",",","\"%Y-%m-%d\"",")","if","today",">","valid_until",":","print","\"{0}Warning:{1} The release \\\"{2}\\\" expired on {3}. It may be removed at any time!\"",".","format","(","Colours",".","yellow",",","Colours",".","end",",","release",",","releases_json","[","release","]","[","\"validUntil\"","]",")","elif","(","valid_until","-","today",")","<=","datetime",".","timedelta","(","weeks","=","4",")",":","print","\"{0}Warning:{1} The release \\\"{2}\\\" will expire soon on {3}.\"",".","format","(","Colours",".","yellow",",","Colours",".","end",",","release",",","releases_json","[","release","]","[","\"validUntil\"","]",")","else",":","print","\"{0}Error:{1} The release \\\"{2}\\\" is not available. Available releases are:\"",".","format","(","Colours",".","red",",","Colours",".","end",",","release",")","for","k",",","v","in","releases_json",".","items","(",")",":","print","\"* {0} ({1})\"",".","format","(","k",",","v","[","\"releaseDate\"","]",")","raise","UploaderException","(","ErrorCodes",".","CODE_RELEASE_NOT_AVAILABLE",")","post_data","[","\"release\"","]","=","release","# make a temporary directory","temp_dir","=","tempfile",".","mkdtemp","(","prefix","=","\"lroyal-\"",")","# zip up the pd directory into the temporary directory","if","not","os",".","path",".","exists","(","os",".","path",".","join","(","input_dir",",","\"_main.pd\"",")",")",":","raise","UploaderException","(","ErrorCodes",".","CODE_MAIN_NOT_FOUND",",","\"Root Pd directory does not contain a file named _main.pd.\"",")","zip_path","=","__zip_dir","(","input_dir",",","os",".","path",".","join","(","temp_dir",",","\"archive.zip\"",")",",","file_filter","=","{","\"pd\"","}",")","if","os",".","stat","(","zip_path",")",".","st_size",">","__HV_MAX_UPLOAD_SIZE",":","raise","UploaderException","(","ErrorCodes",".","CODE_UPLOAD_ASSET_TOO_LARGE",",","\"The target directory, zipped, is {0} bytes. The maximum upload size of 1MB.\"",".","format","(","os",".","stat","(","zip_path",")",".","st_size",")",")","# the outputs to generate","generators","=","list","(","{","s",".","lower","(",")","for","s","in","set","(","generators","or","[","]",")","}","&","__SUPPORTED_GENERATOR_SET",")","# check if the patch exists already. Ask to create it if it doesn't exist","r","=","s",".","get","(","urlparse",".","urljoin","(","domain",",","\"\/a\/patches\/{0}\/{1}\/\"",".","format","(","owner",",","name",")",")",",","headers","=","{","\"Accept\"",":","\"application\/json\"",",","\"Authorization\"",":","\"Bearer \"","+","token",",","\"X-Heavy-Service-Token\"",":","service_token","}",")","r",".","raise_for_status","(",")","reply_json","=","r",".","json","(",")","if","\"errors\"","in","reply_json",":","if","reply_json","[","\"errors\"","]","[","0","]","[","\"status\"","]","==","\"404\"",":","# the patch does not exist","if","force_new_patch",":","create_new_patch","=","True","else",":","create_new_patch","=","raw_input","(","\"A patch called \\\"{0}\\\" does not exist for owner \\\"{1}\\\". Create it? (y\/n):\"",".","format","(","name",",","owner",")",")","create_new_patch","=","(","create_new_patch","==","\"y\"",")","if","create_new_patch",":","r","=","s",".","post","(","urlparse",".","urljoin","(","domain",",","\"\/a\/patches\/\"",")",",","data","=","{","\"owner_name\"",":","owner",",","\"name\"",":","name",",","\"public\"",":","\"true\"","}",",","headers","=","{","\"Accept\"",":","\"application\/json\"",",","\"Authorization\"",":","\"Bearer \"","+","token",",","\"X-Heavy-Service-Token\"",":","service_token","}",")","r",".","raise_for_status","(",")","reply_json","=","r",".","json","(",")","if","\"errors\"","in","reply_json",":","raise","UploaderException","(","ErrorCodes",".","CODE_NEW_PATCH_FAIL",",","reply_json","[","\"errors\"","]","[","0","]","[","\"detail\"","]",")","else",":","pass","# no errors? everything is cool! Proceed.","else",":","UploaderException","(","ErrorCodes",".","CODE_NEW_PATCH_FAIL",",","\"A patch called \\\"{0}\\\" does not exist for owner \\\"{1}\\\"\"",".","format","(","owner",",","name",")",")","else",":","raise","UploaderException","(","ErrorCodes",".","CODE_NEW_PATCH_FAIL",",","reply_json","[","\"errors\"","]","[","0","]","[","\"detail\"","]",")","else",":","pass","# the patch exists, move on","# upload the job, get the response back","r","=","s",".","post","(","urlparse",".","urljoin","(","domain",",","\"\/a\/patches\/{0}\/{1}\/jobs\/\"",".","format","(","owner",",","name",")",")",",","data","=","post_data",",","headers","=","{","\"Accept\"",":","\"application\/json\"",",","\"Authorization\"",":","\"Bearer \"","+","token",",","\"X-Heavy-Service-Token\"",":","service_token","}",",","timeout","=","None",",","# some builds can take a very long time","files","=","{","\"file\"",":","(","os",".","path",".","basename","(","zip_path",")",",","open","(","zip_path",",","\"rb\"",")",",","\"application\/zip\"",")","}",")","r",".","raise_for_status","(",")","# decode the JSON API response (See below for an example response)","reply_json","=","r",".","json","(",")","if","verbose",":","print","json",".","dumps","(","reply_json",",","sort_keys","=","True",",","indent","=","2",",","separators","=","(","\",\"",",","\": \"",")",")","# print any warnings","for","i",",","x","in","enumerate","(","reply_json",".","get","(","\"warnings\"",",","[","]",")",")",":","print","\"{3}) {0}Warning:{1} {2}\"",".","format","(","Colours",".","yellow",",","Colours",".","end",",","x","[","\"detail\"","]",",","i","+","1",")","# check for errors","if","len","(","reply_json",".","get","(","\"errors\"",",","[","]",")",")",">","0",":","for","i",",","x","in","enumerate","(","reply_json","[","\"errors\"","]",")",":","print","\"{3}) {0}Error:{1} {2}\"",".","format","(","Colours",".","red",",","Colours",".","end",",","x","[","\"detail\"","]",",","i","+","1",")","raise","UploaderException","(","ErrorCodes",".","CODE_HEAVY_COMPILE_ERRORS",")","print","\"Job URL:\"",",","urlparse",".","urljoin","(","domain",",","reply_json","[","\"data\"","]","[","\"links\"","]","[","\"html\"","]",")","print","\"Heavy release:\"",",","reply_json","[","\"data\"","]","[","\"attributes\"","]","[","\"release\"","]","if","len","(","generators",")",">","0",":","print","\"Downloaded files placed in:\"","# retrieve all requested files","for","i",",","g","in","enumerate","(","generators",")",":","file_url","=","urlparse",".","urljoin","(","domain",",","\"\/\"",".","join","(","[","reply_json","[","\"data\"","]","[","\"links\"","]","[","\"html\"","]",",","g",".","replace","(","\"-\"",",","\"\/\"",")",",","\"archive.zip\"","]",")",")","if","file_url","and","(","len","(","output_dirs",")",">","i","or","b",")",":","r","=","s",".","get","(","file_url",",","headers","=","{","\"Authorization\"",":","\"Bearer \"","+","token",",","\"X-Heavy-Service-Token\"",":","service_token","}",",","timeout","=","None","# some builds can take a very long time",")","r",".","raise_for_status","(",")","# prepare the target directory for the files","if","b",":","target_dir","=","os",".","path",".","join","(","os",".","path",".","abspath","(","os",".","path",".","expanduser","(","output_dirs","[","0","]",")",")",",","g",")","else",":","target_dir","=","os",".","path",".","abspath","(","os",".","path",".","expanduser","(","output_dirs","[","i","]",")",")","if","not","os",".","path",".","exists","(","target_dir",")",":","os",".","makedirs","(","target_dir",")","# ensure that the output directory exists","# write the reply to file to the final destination if archive_only, else temporary","c_zip_path","=","os",".","path",".","join","(","target_dir","if","archive_only","else","temp_dir",",","\"archive.{0}.zip\"",".","format","(","g",")",")","with","open","(","c_zip_path",",","\"wb\"",")","as","f",":","f",".","write","(","r",".","content",")","if","not","archive_only",":","# unzip the files to where they belong","__unzip","(","c_zip_path",",","target_dir",")","if","g","==","\"c-src\"","and","y",":","keep_files","=","(","\"_{0}.h\"",".","format","(","name",")",",","\"_{0}.hpp\"",".","format","(","name",")",",","\"_{0}.cpp\"",".","format","(","name",")",")","for","f","in","os",".","listdir","(","target_dir",")",":","if","not","f",".","endswith","(","keep_files",")",":","os",".","remove","(","os",".","path",".","join","(","target_dir",",","f",")",")","print","\" * {0}: {1}\"",".","format","(","g",",","target_dir",")","else",":","print","\" * {0}Warning:{1} {2} files could not be retrieved.\"",".","format","(","Colours",".","yellow",",","Colours",".","end",",","g",")","print","\"Total request time: {0}ms\"",".","format","(","int","(","1000.0","*","(","time",".","time","(",")","-","tick",")",")",")","except","UploaderException","as","e",":","exit_code","=","e",".","code","if","e",".","message",":","print","\"{0}Error:{1} {2}\"",".","format","(","Colours",".","red",",","Colours",".","end",",","e",".","message",")","except","requests",".","ConnectionError","as","e",":","print","\"{0}Error:{1} Could not connect to server. Is the server down? Is the internet down?\\n{2}\"",".","format","(","Colours",".","red",",","Colours",".","end",",","e",")","exit_code","=","ErrorCodes",".","CODE_CONNECTION_ERROR","except","requests",".","Timeout","as","e",":","print","\"{0}Error:{1} Connection to server timed out. The server might be overloaded. Try again later?\\n{2}\"",".","format","(","Colours",".","red",",","Colours",".","end",",","e",")","exit_code","=","ErrorCodes",".","CODE_CONNECTION_TIMEOUT","except","requests",".","HTTPError","as","e",":","if","e",".","response",".","status_code","==","requests",".","status_codes",".","codes",".","unauthorized",":","print","\"{0}Error:{1} Unknown username or password.\"",".","format","(","Colours",".","red",",","Colours",".","end",")","else",":","print","\"{0}Error:{1} An HTTP error has occurred with URL {2}\\n{3}\"",".","format","(","Colours",".","red",",","Colours",".","end",",","e",".","request",".","path_url",",","e",")","exit_code","=","ErrorCodes",".","CODE_CONNECTION_400_500","except","Exception","as","e",":","# a generic catch for any other exception","exit_code","=","exit_code","if","exit_code","!=","ErrorCodes",".","CODE_OK","else","ErrorCodes",".","CODE_EXCEPTION","print","\"{0}Error:{1} ({2}) {3}\"",".","format","(","Colours",".","red",",","Colours",".","end",",","e",".","__class__",",","e",")","print","\"Getting a weird error? Get the latest version with 'pip install hv-uploader -U', or check for issues at https:\/\/github.com\/enzienaudio\/heavy\/issues.\"","finally",":","if","temp_dir",":","shutil",".","rmtree","(","temp_dir",")","# delete the temporary directory no matter what","return","exit_code",",","reply_json"],"url":"https:\/\/github.com\/BelaPlatform\/Bela\/blob\/b6491178b859eb8977f494eb9ba4806920eea4b0\/scripts\/hvresources\/uploader.py#L120-L464"}
Blizzard__node-rdkafka.jsonl ADDED
The diff for this file is too large to render. See raw diff
BlocklyDuino__BlocklyDuino.jsonl ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"arduino_web_server.py","language":"python","identifier":"get_arduino_command","parameters":"()","argument_list":"","return_statement":"return arduino_cmd","docstring":"Attempt to find or guess the path to the Arduino binary.","docstring_summary":"Attempt to find or guess the path to the Arduino binary.","docstring_tokens":["Attempt","to","find","or","guess","the","path","to","the","Arduino","binary","."],"function":"def get_arduino_command():\n \"\"\"Attempt to find or guess the path to the Arduino binary.\"\"\"\n global arduino_cmd\n if not arduino_cmd:\n if platform.system() == \"Darwin\":\n arduino_cmd_guesses = [\"\/Applications\/Arduino.app\/Contents\/MacOS\/Arduino\"]\n elif platform.system() == \"Windows\":\n arduino_cmd_guesses = [\n \"c:\\Program Files\\Arduino\\Arduino_debug.exe\",\n \"c:\\Program Files\\Arduino\\Arduino.exe\",\n \"c:\\Program Files (x86)\\Arduino\\Arduino_debug.exe\",\n \"c:\\Program Files (x86)\\Arduino\\Arduino.exe\"\n ]\n else:\n arduino_cmd_guesses = []\n\n for guess in arduino_cmd_guesses:\n if os.path.exists(guess):\n logging.info(\"Found Arduino command at %s\", guess)\n arduino_cmd = guess\n break\n else:\n logging.info(\"Couldn't find Arduino command; hoping it's on the path!\")\n arduino_cmd = \"arduino\"\n return arduino_cmd","function_tokens":["def","get_arduino_command","(",")",":","global","arduino_cmd","if","not","arduino_cmd",":","if","platform",".","system","(",")","==","\"Darwin\"",":","arduino_cmd_guesses","=","[","\"\/Applications\/Arduino.app\/Contents\/MacOS\/Arduino\"","]","elif","platform",".","system","(",")","==","\"Windows\"",":","arduino_cmd_guesses","=","[","\"c:\\Program Files\\Arduino\\Arduino_debug.exe\"",",","\"c:\\Program Files\\Arduino\\Arduino.exe\"",",","\"c:\\Program Files (x86)\\Arduino\\Arduino_debug.exe\"",",","\"c:\\Program Files (x86)\\Arduino\\Arduino.exe\"","]","else",":","arduino_cmd_guesses","=","[","]","for","guess","in","arduino_cmd_guesses",":","if","os",".","path",".","exists","(","guess",")",":","logging",".","info","(","\"Found Arduino command at %s\"",",","guess",")","arduino_cmd","=","guess","break","else",":","logging",".","info","(","\"Couldn't find Arduino command; hoping it's on the path!\"",")","arduino_cmd","=","\"arduino\"","return","arduino_cmd"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/arduino_web_server.py#L24-L48"}
2
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"arduino_web_server.py","language":"python","identifier":"guess_port_name","parameters":"()","argument_list":"","return_statement":"return portname","docstring":"Attempt to guess a port name that we might find an Arduino on.","docstring_summary":"Attempt to guess a port name that we might find an Arduino on.","docstring_tokens":["Attempt","to","guess","a","port","name","that","we","might","find","an","Arduino","on","."],"function":"def guess_port_name():\n \"\"\"Attempt to guess a port name that we might find an Arduino on.\"\"\"\n portname = None\n if platform.system() == \"Windows\":\n import _winreg as winreg\n key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, \"HARDWARE\\\\DEVICEMAP\\\\SERIALCOMM\")\n # We'll guess it's the last COM port.\n for i in itertools.count():\n try:\n portname = winreg.EnumValue(key, i)[1]\n except WindowsError:\n break\n else:\n # We'll guess it's the first non-bluetooth tty. or cu. prefixed device\n ttys = [filename for filename in os.listdir(\"\/dev\")\n if (filename.startswith(\"tty.\") or filename.startswith(\"cu.\"))\n and not \"luetooth\" in filename]\n ttys.sort(key=lambda k:(k.startswith(\"cu.\"), k))\n if ttys:\n portname = \"\/dev\/\" + ttys[0]\n logging.info(\"Guessing port name as %s\", portname)\n return portname","function_tokens":["def","guess_port_name","(",")",":","portname","=","None","if","platform",".","system","(",")","==","\"Windows\"",":","import","_winreg","as","winreg","key","=","winreg",".","OpenKey","(","winreg",".","HKEY_LOCAL_MACHINE",",","\"HARDWARE\\\\DEVICEMAP\\\\SERIALCOMM\"",")","# We'll guess it's the last COM port.","for","i","in","itertools",".","count","(",")",":","try",":","portname","=","winreg",".","EnumValue","(","key",",","i",")","[","1","]","except","WindowsError",":","break","else",":","# We'll guess it's the first non-bluetooth tty. or cu. prefixed device","ttys","=","[","filename","for","filename","in","os",".","listdir","(","\"\/dev\"",")","if","(","filename",".","startswith","(","\"tty.\"",")","or","filename",".","startswith","(","\"cu.\"",")",")","and","not","\"luetooth\"","in","filename","]","ttys",".","sort","(","key","=","lambda","k",":","(","k",".","startswith","(","\"cu.\"",")",",","k",")",")","if","ttys",":","portname","=","\"\/dev\/\"","+","ttys","[","0","]","logging",".","info","(","\"Guessing port name as %s\"",",","portname",")","return","portname"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/arduino_web_server.py#L51-L72"}
3
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"arduino_web_server.py","language":"python","identifier":"Handler.do_HEAD","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Send response headers","docstring_summary":"Send response headers","docstring_tokens":["Send","response","headers"],"function":"def do_HEAD(self):\n \"\"\"Send response headers\"\"\"\n if self.path != \"\/\":\n return SimpleHTTPServer.SimpleHTTPRequestHandler.do_HEAD(self)\n self.send_response(200)\n self.send_header(\"content-type\", \"text\/html;charset=utf-8\")\n self.send_header('Access-Control-Allow-Origin', '*')\n self.end_headers()","function_tokens":["def","do_HEAD","(","self",")",":","if","self",".","path","!=","\"\/\"",":","return","SimpleHTTPServer",".","SimpleHTTPRequestHandler",".","do_HEAD","(","self",")","self",".","send_response","(","200",")","self",".","send_header","(","\"content-type\"",",","\"text\/html;charset=utf-8\"",")","self",".","send_header","(","'Access-Control-Allow-Origin'",",","'*'",")","self",".","end_headers","(",")"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/arduino_web_server.py#L82-L89"}
4
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"arduino_web_server.py","language":"python","identifier":"Handler.do_GET","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Send page text","docstring_summary":"Send page text","docstring_tokens":["Send","page","text"],"function":"def do_GET(self):\n \"\"\"Send page text\"\"\"\n if self.path != \"\/\":\n return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)\n else:\n self.send_response(302)\n self.send_header(\"Location\", \"\/blockly\/apps\/blocklyduino\/index.html\")\n self.end_headers()","function_tokens":["def","do_GET","(","self",")",":","if","self",".","path","!=","\"\/\"",":","return","SimpleHTTPServer",".","SimpleHTTPRequestHandler",".","do_GET","(","self",")","else",":","self",".","send_response","(","302",")","self",".","send_header","(","\"Location\"",",","\"\/blockly\/apps\/blocklyduino\/index.html\"",")","self",".","end_headers","(",")"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/arduino_web_server.py#L91-L98"}
5
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"arduino_web_server.py","language":"python","identifier":"Handler.do_POST","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Save new page text and display it","docstring_summary":"Save new page text and display it","docstring_tokens":["Save","new","page","text","and","display","it"],"function":"def do_POST(self):\n \"\"\"Save new page text and display it\"\"\"\n if self.path != \"\/\":\n return SimpleHTTPServer.SimpleHTTPRequestHandler.do_POST(self)\n\n options, args = parser.parse_args()\n\n length = int(self.headers.getheader('content-length'))\n if length:\n text = self.rfile.read(length)\n \n print \"sketch to upload: \" + text\n\n dirname = tempfile.mkdtemp()\n sketchname = os.path.join(dirname, os.path.basename(dirname)) + \".ino\"\n f = open(sketchname, \"wb\")\n f.write(text + \"\\n\")\n f.close()\n\n print \"created sketch at %s\" % (sketchname,)\n \n # invoke arduino to build\/upload\n compile_args = [\n options.cmd or get_arduino_command(),\n \"--upload\",\n \"--port\",\n options.port or guess_port_name(),\n ]\n if options.board:\n compile_args.extend([\n \"--board\",\n options.board\n ])\n compile_args.append(sketchname)\n\n print \"Uploading with %s\" % (\" \".join(compile_args))\n rc = subprocess.call(compile_args)\n\n if not rc == 0:\n print \"arduino --upload returned \" + `rc` \n self.send_response(400)\n else:\n self.send_response(200)\n self.send_header('Access-Control-Allow-Origin', '*')\n self.end_headers()\n else:\n self.send_response(400)","function_tokens":["def","do_POST","(","self",")",":","if","self",".","path","!=","\"\/\"",":","return","SimpleHTTPServer",".","SimpleHTTPRequestHandler",".","do_POST","(","self",")","options",",","args","=","parser",".","parse_args","(",")","length","=","int","(","self",".","headers",".","getheader","(","'content-length'",")",")","if","length",":","text","=","self",".","rfile",".","read","(","length",")","print","\"sketch to upload: \"","+","text","dirname","=","tempfile",".","mkdtemp","(",")","sketchname","=","os",".","path",".","join","(","dirname",",","os",".","path",".","basename","(","dirname",")",")","+","\".ino\"","f","=","open","(","sketchname",",","\"wb\"",")","f",".","write","(","text","+","\"\\n\"",")","f",".","close","(",")","print","\"created sketch at %s\"","%","(","sketchname",",",")","# invoke arduino to build\/upload","compile_args","=","[","options",".","cmd","or","get_arduino_command","(",")",",","\"--upload\"",",","\"--port\"",",","options",".","port","or","guess_port_name","(",")",",","]","if","options",".","board",":","compile_args",".","extend","(","[","\"--board\"",",","options",".","board","]",")","compile_args",".","append","(","sketchname",")","print","\"Uploading with %s\"","%","(","\" \"",".","join","(","compile_args",")",")","rc","=","subprocess",".","call","(","compile_args",")","if","not","rc","==","0",":","print","\"arduino --upload returned \"","+","`rc`","self",".","send_response","(","400",")","else",":","self",".","send_response","(","200",")","self",".","send_header","(","'Access-Control-Allow-Origin'",",","'*'",")","self",".","end_headers","(",")","else",":","self",".","send_response","(","400",")"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/arduino_web_server.py#L100-L146"}
6
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"blockly\/build.py","language":"python","identifier":"import_path","parameters":"(fullpath)","argument_list":"","return_statement":"return module","docstring":"Import a file with full path specification.\n Allows one to import from any directory, something __import__ does not do.\n\n Args:\n fullpath: Path and filename of import.\n\n Returns:\n An imported module.","docstring_summary":"Import a file with full path specification.\n Allows one to import from any directory, something __import__ does not do.","docstring_tokens":["Import","a","file","with","full","path","specification",".","Allows","one","to","import","from","any","directory","something","__import__","does","not","do","."],"function":"def import_path(fullpath):\n \"\"\"Import a file with full path specification.\n Allows one to import from any directory, something __import__ does not do.\n\n Args:\n fullpath: Path and filename of import.\n\n Returns:\n An imported module.\n \"\"\"\n path, filename = os.path.split(fullpath)\n filename, ext = os.path.splitext(filename)\n sys.path.append(path)\n module = __import__(filename)\n reload(module) # Might be out of date.\n del sys.path[-1]\n return module","function_tokens":["def","import_path","(","fullpath",")",":","path",",","filename","=","os",".","path",".","split","(","fullpath",")","filename",",","ext","=","os",".","path",".","splitext","(","filename",")","sys",".","path",".","append","(","path",")","module","=","__import__","(","filename",")","reload","(","module",")","# Might be out of date.","del","sys",".","path","[","-","1","]","return","module"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/blockly\/build.py#L46-L62"}
7
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"blockly\/i18n\/create_messages.py","language":"python","identifier":"main","parameters":"()","argument_list":"","return_statement":"","docstring":"Generate .js files defining Blockly core and language messages.","docstring_summary":"Generate .js files defining Blockly core and language messages.","docstring_tokens":["Generate",".","js","files","defining","Blockly","core","and","language","messages","."],"function":"def main():\n \"\"\"Generate .js files defining Blockly core and language messages.\"\"\"\n\n # Process command-line arguments.\n parser = argparse.ArgumentParser(description='Convert JSON files to JS.')\n parser.add_argument('--source_lang', default='en',\n help='ISO 639-1 source language code')\n parser.add_argument('--source_lang_file',\n default=os.path.join('json', 'en.json'),\n help='Path to .json file for source language')\n parser.add_argument('--source_synonym_file',\n default=os.path.join('json', 'synonyms.json'),\n help='Path to .json file with synonym definitions')\n parser.add_argument('--output_dir', default='js\/',\n help='relative directory for output files')\n parser.add_argument('--key_file', default='keys.json',\n help='relative path to input keys file')\n parser.add_argument('--quiet', action='store_true', default=False,\n help='do not write anything to standard output')\n parser.add_argument('files', nargs='+', help='input files')\n args = parser.parse_args()\n if not args.output_dir.endswith(os.path.sep):\n args.output_dir += os.path.sep\n\n # Read in source language .json file, which provides any values missing\n # in target languages' .json files.\n source_defs = read_json_file(os.path.join(os.curdir, args.source_lang_file))\n # Make sure the source file doesn't contain a newline or carriage return.\n for key, value in source_defs.items():\n if _NEWLINE_PATTERN.search(value):\n print('ERROR: definition of {0} in {1} contained a newline character.'.\n format(key, args.source_lang_file))\n sys.exit(1)\n sorted_keys = source_defs.keys()\n sorted_keys.sort()\n\n # Read in synonyms file, which must be output in every language.\n synonym_defs = read_json_file(os.path.join(\n os.curdir, args.source_synonym_file))\n synonym_text = '\\n'.join(['Blockly.Msg.{0} = Blockly.Msg.{1};'.format(\n key, synonym_defs[key]) for key in synonym_defs])\n\n # Create each output file.\n for arg_file in args.files:\n (_, filename) = os.path.split(arg_file)\n target_lang = filename[:filename.index('.')]\n if target_lang not in ('qqq', 'keys', 'synonyms'):\n target_defs = read_json_file(os.path.join(os.curdir, arg_file))\n\n # Verify that keys are 'ascii'\n bad_keys = [key for key in target_defs if not string_is_ascii(key)]\n if bad_keys:\n print(u'These keys in {0} contain non ascii characters: {1}'.format(\n filename, ', '.join(bad_keys)))\n\n # If there's a '\\n' or '\\r', remove it and print a warning.\n for key, value in target_defs.items():\n if _NEWLINE_PATTERN.search(value):\n print(u'WARNING: definition of {0} in {1} contained '\n 'a newline character.'.\n format(key, arg_file))\n target_defs[key] = _NEWLINE_PATTERN.sub(' ', value)\n\n # Output file.\n outname = os.path.join(os.curdir, args.output_dir, target_lang + '.js')\n with codecs.open(outname, 'w', 'utf-8') as outfile:\n outfile.write(\n \"\"\"\/\/ This file was automatically generated. Do not modify.\n\n'use strict';\n\ngoog.provide('Blockly.Msg.{0}');\n\ngoog.require('Blockly.Msg');\n\n\"\"\".format(target_lang.replace('-', '.')))\n # For each key in the source language file, output the target value\n # if present; otherwise, output the source language value with a\n # warning comment.\n for key in sorted_keys:\n if key in target_defs:\n value = target_defs[key]\n comment = ''\n del target_defs[key]\n else:\n value = source_defs[key]\n comment = ' \/\/ untranslated'\n value = value.replace('\"', '\\\\\"')\n outfile.write(u'Blockly.Msg.{0} = \"{1}\";{2}\\n'.format(\n key, value, comment))\n\n # Announce any keys defined only for target language.\n if target_defs:\n extra_keys = [key for key in target_defs if key not in synonym_defs]\n synonym_keys = [key for key in target_defs if key in synonym_defs]\n if not args.quiet:\n if extra_keys:\n print(u'These extra keys appeared in {0}: {1}'.format(\n filename, ', '.join(extra_keys)))\n if synonym_keys:\n print(u'These synonym keys appeared in {0}: {1}'.format(\n filename, ', '.join(synonym_keys)))\n\n outfile.write(synonym_text)\n\n if not args.quiet:\n print('Created {0}.'.format(outname))","function_tokens":["def","main","(",")",":","# Process command-line arguments.","parser","=","argparse",".","ArgumentParser","(","description","=","'Convert JSON files to JS.'",")","parser",".","add_argument","(","'--source_lang'",",","default","=","'en'",",","help","=","'ISO 639-1 source language code'",")","parser",".","add_argument","(","'--source_lang_file'",",","default","=","os",".","path",".","join","(","'json'",",","'en.json'",")",",","help","=","'Path to .json file for source language'",")","parser",".","add_argument","(","'--source_synonym_file'",",","default","=","os",".","path",".","join","(","'json'",",","'synonyms.json'",")",",","help","=","'Path to .json file with synonym definitions'",")","parser",".","add_argument","(","'--output_dir'",",","default","=","'js\/'",",","help","=","'relative directory for output files'",")","parser",".","add_argument","(","'--key_file'",",","default","=","'keys.json'",",","help","=","'relative path to input keys file'",")","parser",".","add_argument","(","'--quiet'",",","action","=","'store_true'",",","default","=","False",",","help","=","'do not write anything to standard output'",")","parser",".","add_argument","(","'files'",",","nargs","=","'+'",",","help","=","'input files'",")","args","=","parser",".","parse_args","(",")","if","not","args",".","output_dir",".","endswith","(","os",".","path",".","sep",")",":","args",".","output_dir","+=","os",".","path",".","sep","# Read in source language .json file, which provides any values missing","# in target languages' .json files.","source_defs","=","read_json_file","(","os",".","path",".","join","(","os",".","curdir",",","args",".","source_lang_file",")",")","# Make sure the source file doesn't contain a newline or carriage return.","for","key",",","value","in","source_defs",".","items","(",")",":","if","_NEWLINE_PATTERN",".","search","(","value",")",":","print","(","'ERROR: definition of {0} in {1} contained a newline character.'",".","format","(","key",",","args",".","source_lang_file",")",")","sys",".","exit","(","1",")","sorted_keys","=","source_defs",".","keys","(",")","sorted_keys",".","sort","(",")","# Read in synonyms file, which must be output in every language.","synonym_defs","=","read_json_file","(","os",".","path",".","join","(","os",".","curdir",",","args",".","source_synonym_file",")",")","synonym_text","=","'\\n'",".","join","(","[","'Blockly.Msg.{0} = Blockly.Msg.{1};'",".","format","(","key",",","synonym_defs","[","key","]",")","for","key","in","synonym_defs","]",")","# Create each output file.","for","arg_file","in","args",".","files",":","(","_",",","filename",")","=","os",".","path",".","split","(","arg_file",")","target_lang","=","filename","[",":","filename",".","index","(","'.'",")","]","if","target_lang","not","in","(","'qqq'",",","'keys'",",","'synonyms'",")",":","target_defs","=","read_json_file","(","os",".","path",".","join","(","os",".","curdir",",","arg_file",")",")","# Verify that keys are 'ascii'","bad_keys","=","[","key","for","key","in","target_defs","if","not","string_is_ascii","(","key",")","]","if","bad_keys",":","print","(","u'These keys in {0} contain non ascii characters: {1}'",".","format","(","filename",",","', '",".","join","(","bad_keys",")",")",")","# If there's a '\\n' or '\\r', remove it and print a warning.","for","key",",","value","in","target_defs",".","items","(",")",":","if","_NEWLINE_PATTERN",".","search","(","value",")",":","print","(","u'WARNING: definition of {0} in {1} contained '","'a newline character.'",".","format","(","key",",","arg_file",")",")","target_defs","[","key","]","=","_NEWLINE_PATTERN",".","sub","(","' '",",","value",")","# Output file.","outname","=","os",".","path",".","join","(","os",".","curdir",",","args",".","output_dir",",","target_lang","+","'.js'",")","with","codecs",".","open","(","outname",",","'w'",",","'utf-8'",")","as","outfile",":","outfile",".","write","(","\"\"\"\/\/ This file was automatically generated. Do not modify.\n\n'use strict';\n\ngoog.provide('Blockly.Msg.{0}');\n\ngoog.require('Blockly.Msg');\n\n\"\"\"",".","format","(","target_lang",".","replace","(","'-'",",","'.'",")",")",")","# For each key in the source language file, output the target value","# if present; otherwise, output the source language value with a","# warning comment.","for","key","in","sorted_keys",":","if","key","in","target_defs",":","value","=","target_defs","[","key","]","comment","=","''","del","target_defs","[","key","]","else",":","value","=","source_defs","[","key","]","comment","=","' \/\/ untranslated'","value","=","value",".","replace","(","'\"'",",","'\\\\\"'",")","outfile",".","write","(","u'Blockly.Msg.{0} = \"{1}\";{2}\\n'",".","format","(","key",",","value",",","comment",")",")","# Announce any keys defined only for target language.","if","target_defs",":","extra_keys","=","[","key","for","key","in","target_defs","if","key","not","in","synonym_defs","]","synonym_keys","=","[","key","for","key","in","target_defs","if","key","in","synonym_defs","]","if","not","args",".","quiet",":","if","extra_keys",":","print","(","u'These extra keys appeared in {0}: {1}'",".","format","(","filename",",","', '",".","join","(","extra_keys",")",")",")","if","synonym_keys",":","print","(","u'These synonym keys appeared in {0}: {1}'",".","format","(","filename",",","', '",".","join","(","synonym_keys",")",")",")","outfile",".","write","(","synonym_text",")","if","not","args",".","quiet",":","print","(","'Created {0}.'",".","format","(","outname",")",")"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/blockly\/i18n\/create_messages.py#L39-L145"}
8
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"blockly\/i18n\/dedup_json.py","language":"python","identifier":"main","parameters":"()","argument_list":"","return_statement":"","docstring":"Parses arguments and iterates over files.\n\n Raises:\n IOError: An I\/O error occurred with an input or output file.\n InputError: Input JSON could not be parsed.","docstring_summary":"Parses arguments and iterates over files.","docstring_tokens":["Parses","arguments","and","iterates","over","files","."],"function":"def main():\n \"\"\"Parses arguments and iterates over files.\n\n Raises:\n IOError: An I\/O error occurred with an input or output file.\n InputError: Input JSON could not be parsed.\n \"\"\"\n\n # Set up argument parser.\n parser = argparse.ArgumentParser(\n description='Removes duplicate key-value pairs from JSON files.')\n parser.add_argument('--suffix', default='',\n help='optional suffix for output files; '\n 'if empty, files will be changed in place')\n parser.add_argument('files', nargs='+', help='input files')\n args = parser.parse_args()\n\n # Iterate over files.\n for filename in args.files:\n # Read in json using Python libraries. This eliminates duplicates.\n print('Processing ' + filename + '...')\n try:\n with codecs.open(filename, 'r', 'utf-8') as infile:\n j = json.load(infile)\n except ValueError, e:\n print('Error reading ' + filename)\n raise InputError(file, str(e))\n\n # Built up output strings as an array to make output of delimiters easier.\n output = []\n for key in j:\n if key != '@metadata':\n output.append('\\t\"' + key + '\": \"' +\n j[key].replace('\\n', '\\\\n') + '\"')\n\n # Output results.\n with codecs.open(filename + args.suffix, 'w', 'utf-8') as outfile:\n outfile.write('{\\n')\n outfile.write(',\\n'.join(output))\n outfile.write('\\n}\\n')","function_tokens":["def","main","(",")",":","# Set up argument parser.","parser","=","argparse",".","ArgumentParser","(","description","=","'Removes duplicate key-value pairs from JSON files.'",")","parser",".","add_argument","(","'--suffix'",",","default","=","''",",","help","=","'optional suffix for output files; '","'if empty, files will be changed in place'",")","parser",".","add_argument","(","'files'",",","nargs","=","'+'",",","help","=","'input files'",")","args","=","parser",".","parse_args","(",")","# Iterate over files.","for","filename","in","args",".","files",":","# Read in json using Python libraries. This eliminates duplicates.","print","(","'Processing '","+","filename","+","'...'",")","try",":","with","codecs",".","open","(","filename",",","'r'",",","'utf-8'",")","as","infile",":","j","=","json",".","load","(","infile",")","except","ValueError",",","e",":","print","(","'Error reading '","+","filename",")","raise","InputError","(","file",",","str","(","e",")",")","# Built up output strings as an array to make output of delimiters easier.","output","=","[","]","for","key","in","j",":","if","key","!=","'@metadata'",":","output",".","append","(","'\\t\"'","+","key","+","'\": \"'","+","j","[","key","]",".","replace","(","'\\n'",",","'\\\\n'",")","+","'\"'",")","# Output results.","with","codecs",".","open","(","filename","+","args",".","suffix",",","'w'",",","'utf-8'",")","as","outfile",":","outfile",".","write","(","'{\\n'",")","outfile",".","write","(","',\\n'",".","join","(","output",")",")","outfile",".","write","(","'\\n}\\n'",")"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/blockly\/i18n\/dedup_json.py#L30-L69"}
9
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"blockly\/i18n\/json_to_js.py","language":"python","identifier":"_create_xlf","parameters":"(target_lang)","argument_list":"","return_statement":"return out_file","docstring":"Creates a <target_lang>.xlf file for Soy.\n\n Args:\n target_lang: The ISO 639 language code for the target language.\n This is used in the name of the file and in the metadata.\n\n Returns:\n A pointer to a file to which the metadata has been written.\n\n Raises:\n IOError: An error occurred while opening or writing the file.","docstring_summary":"Creates a <target_lang>.xlf file for Soy.","docstring_tokens":["Creates","a","<target_lang",">",".","xlf","file","for","Soy","."],"function":"def _create_xlf(target_lang):\n \"\"\"Creates a <target_lang>.xlf file for Soy.\n\n Args:\n target_lang: The ISO 639 language code for the target language.\n This is used in the name of the file and in the metadata.\n\n Returns:\n A pointer to a file to which the metadata has been written.\n\n Raises:\n IOError: An error occurred while opening or writing the file.\n \"\"\"\n filename = os.path.join(os.curdir, args.output_dir, target_lang + '.xlf')\n out_file = codecs.open(filename, 'w', 'utf-8')\n out_file.write(\"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\">\n <file original=\"SoyMsgBundle\"\n datatype=\"x-soy-msg-bundle\"\n xml:space=\"preserve\"\n source-language=\"{0}\"\n target-language=\"{1}\">\n <body>\"\"\".format(args.source_lang, target_lang))\n return out_file","function_tokens":["def","_create_xlf","(","target_lang",")",":","filename","=","os",".","path",".","join","(","os",".","curdir",",","args",".","output_dir",",","target_lang","+","'.xlf'",")","out_file","=","codecs",".","open","(","filename",",","'w'",",","'utf-8'",")","out_file",".","write","(","\"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\">\n <file original=\"SoyMsgBundle\"\n datatype=\"x-soy-msg-bundle\"\n xml:space=\"preserve\"\n source-language=\"{0}\"\n target-language=\"{1}\">\n <body>\"\"\"",".","format","(","args",".","source_lang",",","target_lang",")",")","return","out_file"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/blockly\/i18n\/json_to_js.py#L34-L57"}
10
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"blockly\/i18n\/json_to_js.py","language":"python","identifier":"_close_xlf","parameters":"(xlf_file)","argument_list":"","return_statement":"","docstring":"Closes a <target_lang>.xlf file created with create_xlf().\n\n This includes writing the terminating XML.\n\n Args:\n xlf_file: A pointer to a file created by _create_xlf().\n\n Raises:\n IOError: An error occurred while writing to or closing the file.","docstring_summary":"Closes a <target_lang>.xlf file created with create_xlf().","docstring_tokens":["Closes","a","<target_lang",">",".","xlf","file","created","with","create_xlf","()","."],"function":"def _close_xlf(xlf_file):\n \"\"\"Closes a <target_lang>.xlf file created with create_xlf().\n\n This includes writing the terminating XML.\n\n Args:\n xlf_file: A pointer to a file created by _create_xlf().\n\n Raises:\n IOError: An error occurred while writing to or closing the file.\n \"\"\"\n xlf_file.write(\"\"\"\n <\/body>\n <\/file>\n<\/xliff>\n\"\"\")\n xlf_file.close()","function_tokens":["def","_close_xlf","(","xlf_file",")",":","xlf_file",".","write","(","\"\"\"\n <\/body>\n <\/file>\n<\/xliff>\n\"\"\"",")","xlf_file",".","close","(",")"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/blockly\/i18n\/json_to_js.py#L60-L76"}
11
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"blockly\/i18n\/json_to_js.py","language":"python","identifier":"_process_file","parameters":"(path_to_json, target_lang, key_dict)","argument_list":"","return_statement":"","docstring":"Creates an .xlf file corresponding to the specified .json input file.\n\n The name of the input file must be target_lang followed by '.json'.\n The name of the output file will be target_lang followed by '.js'.\n\n Args:\n path_to_json: Path to the directory of xx.json files.\n target_lang: A IETF language code (RFC 4646), such as 'es' or 'pt-br'.\n key_dict: Dictionary mapping Blockly keys (e.g., Maze.turnLeft) to\n Closure keys (hash numbers).\n\n Raises:\n IOError: An I\/O error occurred with an input or output file.\n InputError: Input JSON could not be parsed.\n KeyError: Key found in input file but not in key file.","docstring_summary":"Creates an .xlf file corresponding to the specified .json input file.","docstring_tokens":["Creates","an",".","xlf","file","corresponding","to","the","specified",".","json","input","file","."],"function":"def _process_file(path_to_json, target_lang, key_dict):\n \"\"\"Creates an .xlf file corresponding to the specified .json input file.\n\n The name of the input file must be target_lang followed by '.json'.\n The name of the output file will be target_lang followed by '.js'.\n\n Args:\n path_to_json: Path to the directory of xx.json files.\n target_lang: A IETF language code (RFC 4646), such as 'es' or 'pt-br'.\n key_dict: Dictionary mapping Blockly keys (e.g., Maze.turnLeft) to\n Closure keys (hash numbers).\n\n Raises:\n IOError: An I\/O error occurred with an input or output file.\n InputError: Input JSON could not be parsed.\n KeyError: Key found in input file but not in key file.\n \"\"\"\n keyfile = os.path.join(path_to_json, target_lang + '.json')\n j = read_json_file(keyfile)\n out_file = _create_xlf(target_lang)\n for key in j:\n if key != '@metadata':\n try:\n identifier = key_dict[key]\n except KeyError, e:\n print('Key \"%s\" is in %s but not in %s' %\n (key, keyfile, args.key_file))\n raise e\n target = j.get(key)\n out_file.write(u\"\"\"\n <trans-unit id=\"{0}\" datatype=\"html\">\n <target>{1}<\/target>\n <\/trans-unit>\"\"\".format(identifier, target))\n _close_xlf(out_file)","function_tokens":["def","_process_file","(","path_to_json",",","target_lang",",","key_dict",")",":","keyfile","=","os",".","path",".","join","(","path_to_json",",","target_lang","+","'.json'",")","j","=","read_json_file","(","keyfile",")","out_file","=","_create_xlf","(","target_lang",")","for","key","in","j",":","if","key","!=","'@metadata'",":","try",":","identifier","=","key_dict","[","key","]","except","KeyError",",","e",":","print","(","'Key \"%s\" is in %s but not in %s'","%","(","key",",","keyfile",",","args",".","key_file",")",")","raise","e","target","=","j",".","get","(","key",")","out_file",".","write","(","u\"\"\"\n <trans-unit id=\"{0}\" datatype=\"html\">\n <target>{1}<\/target>\n <\/trans-unit>\"\"\"",".","format","(","identifier",",","target",")",")","_close_xlf","(","out_file",")"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/blockly\/i18n\/json_to_js.py#L79-L112"}
12
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"blockly\/i18n\/json_to_js.py","language":"python","identifier":"main","parameters":"()","argument_list":"","return_statement":"","docstring":"Parses arguments and iterates over files.","docstring_summary":"Parses arguments and iterates over files.","docstring_tokens":["Parses","arguments","and","iterates","over","files","."],"function":"def main():\n \"\"\"Parses arguments and iterates over files.\"\"\"\n\n # Set up argument parser.\n parser = argparse.ArgumentParser(description='Convert JSON files to JS.')\n parser.add_argument('--source_lang', default='en',\n help='ISO 639-1 source language code')\n parser.add_argument('--output_dir', default='generated',\n help='relative directory for output files')\n parser.add_argument('--key_file', default='json' + os.path.sep + 'keys.json',\n help='relative path to input keys file')\n parser.add_argument('--template', default='template.soy')\n parser.add_argument('--path_to_jar',\n default='..' + os.path.sep + 'apps' + os.path.sep\n + '_soy',\n help='relative path from working directory to '\n 'SoyToJsSrcCompiler.jar')\n parser.add_argument('files', nargs='+', help='input files')\n\n # Initialize global variables.\n global args\n args = parser.parse_args()\n\n # Make sure output_dir ends with slash.\n if (not args.output_dir.endswith(os.path.sep)):\n args.output_dir += os.path.sep\n\n # Read in keys.json, mapping descriptions (e.g., Maze.turnLeft) to\n # Closure keys (long hash numbers).\n key_file = open(args.key_file)\n key_dict = json.load(key_file)\n key_file.close()\n\n # Process each input file.\n print('Creating .xlf files...')\n processed_langs = []\n if len(args.files) == 1:\n # Windows does not expand globs automatically.\n args.files = glob.glob(args.files[0])\n for arg_file in args.files:\n (path_to_json, filename) = os.path.split(arg_file)\n if not filename.endswith('.json'):\n raise InputError(filename, 'filenames must end with \".json\"')\n target_lang = filename[:filename.index('.')]\n if not target_lang in ('qqq', 'keys'):\n processed_langs.append(target_lang)\n _process_file(path_to_json, target_lang, key_dict)\n\n # Output command line for Closure compiler.\n if processed_langs:\n print('Creating .js files...')\n processed_lang_list = ','.join(processed_langs)\n subprocess.check_call([\n 'java',\n '-jar', os.path.join(args.path_to_jar, 'SoyToJsSrcCompiler.jar'),\n '--locales', processed_lang_list,\n '--messageFilePathFormat', args.output_dir + '{LOCALE}.xlf',\n '--outputPathFormat', args.output_dir + '{LOCALE}.js',\n '--srcs', args.template])\n if len(processed_langs) == 1:\n print('Created ' + processed_lang_list + '.js in ' + args.output_dir)\n else:\n print('Created {' + processed_lang_list + '}.js in ' + args.output_dir)\n\n for lang in processed_langs:\n os.remove(args.output_dir + lang + '.xlf')\n print('Removed .xlf files.')","function_tokens":["def","main","(",")",":","# Set up argument parser.","parser","=","argparse",".","ArgumentParser","(","description","=","'Convert JSON files to JS.'",")","parser",".","add_argument","(","'--source_lang'",",","default","=","'en'",",","help","=","'ISO 639-1 source language code'",")","parser",".","add_argument","(","'--output_dir'",",","default","=","'generated'",",","help","=","'relative directory for output files'",")","parser",".","add_argument","(","'--key_file'",",","default","=","'json'","+","os",".","path",".","sep","+","'keys.json'",",","help","=","'relative path to input keys file'",")","parser",".","add_argument","(","'--template'",",","default","=","'template.soy'",")","parser",".","add_argument","(","'--path_to_jar'",",","default","=","'..'","+","os",".","path",".","sep","+","'apps'","+","os",".","path",".","sep","+","'_soy'",",","help","=","'relative path from working directory to '","'SoyToJsSrcCompiler.jar'",")","parser",".","add_argument","(","'files'",",","nargs","=","'+'",",","help","=","'input files'",")","# Initialize global variables.","global","args","args","=","parser",".","parse_args","(",")","# Make sure output_dir ends with slash.","if","(","not","args",".","output_dir",".","endswith","(","os",".","path",".","sep",")",")",":","args",".","output_dir","+=","os",".","path",".","sep","# Read in keys.json, mapping descriptions (e.g., Maze.turnLeft) to","# Closure keys (long hash numbers).","key_file","=","open","(","args",".","key_file",")","key_dict","=","json",".","load","(","key_file",")","key_file",".","close","(",")","# Process each input file.","print","(","'Creating .xlf files...'",")","processed_langs","=","[","]","if","len","(","args",".","files",")","==","1",":","# Windows does not expand globs automatically.","args",".","files","=","glob",".","glob","(","args",".","files","[","0","]",")","for","arg_file","in","args",".","files",":","(","path_to_json",",","filename",")","=","os",".","path",".","split","(","arg_file",")","if","not","filename",".","endswith","(","'.json'",")",":","raise","InputError","(","filename",",","'filenames must end with \".json\"'",")","target_lang","=","filename","[",":","filename",".","index","(","'.'",")","]","if","not","target_lang","in","(","'qqq'",",","'keys'",")",":","processed_langs",".","append","(","target_lang",")","_process_file","(","path_to_json",",","target_lang",",","key_dict",")","# Output command line for Closure compiler.","if","processed_langs",":","print","(","'Creating .js files...'",")","processed_lang_list","=","','",".","join","(","processed_langs",")","subprocess",".","check_call","(","[","'java'",",","'-jar'",",","os",".","path",".","join","(","args",".","path_to_jar",",","'SoyToJsSrcCompiler.jar'",")",",","'--locales'",",","processed_lang_list",",","'--messageFilePathFormat'",",","args",".","output_dir","+","'{LOCALE}.xlf'",",","'--outputPathFormat'",",","args",".","output_dir","+","'{LOCALE}.js'",",","'--srcs'",",","args",".","template","]",")","if","len","(","processed_langs",")","==","1",":","print","(","'Created '","+","processed_lang_list","+","'.js in '","+","args",".","output_dir",")","else",":","print","(","'Created {'","+","processed_lang_list","+","'}.js in '","+","args",".","output_dir",")","for","lang","in","processed_langs",":","os",".","remove","(","args",".","output_dir","+","lang","+","'.xlf'",")","print","(","'Removed .xlf files.'",")"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/blockly\/i18n\/json_to_js.py#L115-L181"}
13
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"blockly\/i18n\/common.py","language":"python","identifier":"read_json_file","parameters":"(filename)","argument_list":"","return_statement":"","docstring":"Read a JSON file as UTF-8 into a dictionary, discarding @metadata.\n\n Args:\n filename: The filename, which must end \".json\".\n\n Returns:\n The dictionary.\n\n Raises:\n InputError: The filename did not end with \".json\" or an error occurred\n while opening or reading the file.","docstring_summary":"Read a JSON file as UTF-8 into a dictionary, discarding @metadata.","docstring_tokens":["Read","a","JSON","file","as","UTF","-","8","into","a","dictionary","discarding","@metadata","."],"function":"def read_json_file(filename):\n \"\"\"Read a JSON file as UTF-8 into a dictionary, discarding @metadata.\n\n Args:\n filename: The filename, which must end \".json\".\n\n Returns:\n The dictionary.\n\n Raises:\n InputError: The filename did not end with \".json\" or an error occurred\n while opening or reading the file.\n \"\"\"\n if not filename.endswith('.json'):\n raise InputError(filename, 'filenames must end with \".json\"')\n try:\n # Read in file.\n with codecs.open(filename, 'r', 'utf-8') as infile:\n defs = json.load(infile)\n if '@metadata' in defs:\n del defs['@metadata']\n return defs\n except ValueError, e:\n print('Error reading ' + filename)\n raise InputError(filename, str(e))","function_tokens":["def","read_json_file","(","filename",")",":","if","not","filename",".","endswith","(","'.json'",")",":","raise","InputError","(","filename",",","'filenames must end with \".json\"'",")","try",":","# Read in file.","with","codecs",".","open","(","filename",",","'r'",",","'utf-8'",")","as","infile",":","defs","=","json",".","load","(","infile",")","if","'@metadata'","in","defs",":","del","defs","[","'@metadata'","]","return","defs","except","ValueError",",","e",":","print","(","'Error reading '","+","filename",")","raise","InputError","(","filename",",","str","(","e",")",")"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/blockly\/i18n\/common.py#L40-L64"}
14
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"blockly\/i18n\/common.py","language":"python","identifier":"_create_qqq_file","parameters":"(output_dir)","argument_list":"","return_statement":"return qqq_file","docstring":"Creates a qqq.json file with message documentation for translatewiki.net.\n\n The file consists of key-value pairs, where the keys are message ids and\n the values are descriptions for the translators of the messages.\n What documentation exists for the format can be found at:\n http:\/\/translatewiki.net\/wiki\/Translating:Localisation_for_developers#Message_documentation\n\n The file should be closed by _close_qqq_file().\n\n Parameters:\n output_dir: The output directory.\n\n Returns:\n A pointer to a file to which a left brace and newline have been written.\n\n Raises:\n IOError: An error occurred while opening or writing the file.","docstring_summary":"Creates a qqq.json file with message documentation for translatewiki.net.","docstring_tokens":["Creates","a","qqq",".","json","file","with","message","documentation","for","translatewiki",".","net","."],"function":"def _create_qqq_file(output_dir):\n \"\"\"Creates a qqq.json file with message documentation for translatewiki.net.\n\n The file consists of key-value pairs, where the keys are message ids and\n the values are descriptions for the translators of the messages.\n What documentation exists for the format can be found at:\n http:\/\/translatewiki.net\/wiki\/Translating:Localisation_for_developers#Message_documentation\n\n The file should be closed by _close_qqq_file().\n\n Parameters:\n output_dir: The output directory.\n\n Returns:\n A pointer to a file to which a left brace and newline have been written.\n\n Raises:\n IOError: An error occurred while opening or writing the file.\n \"\"\"\n qqq_file_name = os.path.join(os.curdir, output_dir, 'qqq.json')\n qqq_file = codecs.open(qqq_file_name, 'w', 'utf-8')\n print 'Created file: ' + qqq_file_name\n qqq_file.write('{\\n')\n return qqq_file","function_tokens":["def","_create_qqq_file","(","output_dir",")",":","qqq_file_name","=","os",".","path",".","join","(","os",".","curdir",",","output_dir",",","'qqq.json'",")","qqq_file","=","codecs",".","open","(","qqq_file_name",",","'w'",",","'utf-8'",")","print","'Created file: '","+","qqq_file_name","qqq_file",".","write","(","'{\\n'",")","return","qqq_file"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/blockly\/i18n\/common.py#L67-L90"}
15
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"blockly\/i18n\/common.py","language":"python","identifier":"_close_qqq_file","parameters":"(qqq_file)","argument_list":"","return_statement":"","docstring":"Closes a qqq.json file created and opened by _create_qqq_file().\n\n This writes the final newlines and right brace.\n\n Args:\n qqq_file: A file created by _create_qqq_file().\n\n Raises:\n IOError: An error occurred while writing to or closing the file.","docstring_summary":"Closes a qqq.json file created and opened by _create_qqq_file().","docstring_tokens":["Closes","a","qqq",".","json","file","created","and","opened","by","_create_qqq_file","()","."],"function":"def _close_qqq_file(qqq_file):\n \"\"\"Closes a qqq.json file created and opened by _create_qqq_file().\n\n This writes the final newlines and right brace.\n\n Args:\n qqq_file: A file created by _create_qqq_file().\n\n Raises:\n IOError: An error occurred while writing to or closing the file.\n \"\"\"\n qqq_file.write('\\n}\\n')\n qqq_file.close()","function_tokens":["def","_close_qqq_file","(","qqq_file",")",":","qqq_file",".","write","(","'\\n}\\n'",")","qqq_file",".","close","(",")"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/blockly\/i18n\/common.py#L93-L105"}
16
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"blockly\/i18n\/common.py","language":"python","identifier":"_create_lang_file","parameters":"(author, lang, output_dir)","argument_list":"","return_statement":"return lang_file","docstring":"Creates a <lang>.json file for translatewiki.net.\n\n The file consists of metadata, followed by key-value pairs, where the keys\n are message ids and the values are the messages in the language specified\n by the corresponding command-line argument. The file should be closed by\n _close_lang_file().\n\n Args:\n author: Name and email address of contact for translators.\n lang: ISO 639-1 source language code.\n output_dir: Relative directory for output files.\n\n Returns:\n A pointer to a file to which the metadata has been written.\n\n Raises:\n IOError: An error occurred while opening or writing the file.","docstring_summary":"Creates a <lang>.json file for translatewiki.net.","docstring_tokens":["Creates","a","<lang",">",".","json","file","for","translatewiki",".","net","."],"function":"def _create_lang_file(author, lang, output_dir):\n \"\"\"Creates a <lang>.json file for translatewiki.net.\n\n The file consists of metadata, followed by key-value pairs, where the keys\n are message ids and the values are the messages in the language specified\n by the corresponding command-line argument. The file should be closed by\n _close_lang_file().\n\n Args:\n author: Name and email address of contact for translators.\n lang: ISO 639-1 source language code.\n output_dir: Relative directory for output files.\n\n Returns:\n A pointer to a file to which the metadata has been written.\n\n Raises:\n IOError: An error occurred while opening or writing the file.\n \"\"\"\n lang_file_name = os.path.join(os.curdir, output_dir, lang + '.json')\n lang_file = codecs.open(lang_file_name, 'w', 'utf-8')\n print 'Created file: ' + lang_file_name\n # string.format doesn't like printing braces, so break up our writes.\n lang_file.write('{\\n\\t\"@metadata\": {')\n lang_file.write(\"\"\"\n\\t\\t\"author\": \"{0}\",\n\\t\\t\"lastupdated\": \"{1}\",\n\\t\\t\"locale\": \"{2}\",\n\\t\\t\"messagedocumentation\" : \"qqq\"\n\"\"\".format(author, str(datetime.now()), lang))\n lang_file.write('\\t},\\n')\n return lang_file","function_tokens":["def","_create_lang_file","(","author",",","lang",",","output_dir",")",":","lang_file_name","=","os",".","path",".","join","(","os",".","curdir",",","output_dir",",","lang","+","'.json'",")","lang_file","=","codecs",".","open","(","lang_file_name",",","'w'",",","'utf-8'",")","print","'Created file: '","+","lang_file_name","# string.format doesn't like printing braces, so break up our writes.","lang_file",".","write","(","'{\\n\\t\"@metadata\": {'",")","lang_file",".","write","(","\"\"\"\n\\t\\t\"author\": \"{0}\",\n\\t\\t\"lastupdated\": \"{1}\",\n\\t\\t\"locale\": \"{2}\",\n\\t\\t\"messagedocumentation\" : \"qqq\"\n\"\"\"",".","format","(","author",",","str","(","datetime",".","now","(",")",")",",","lang",")",")","lang_file",".","write","(","'\\t},\\n'",")","return","lang_file"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/blockly\/i18n\/common.py#L108-L139"}
17
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"blockly\/i18n\/common.py","language":"python","identifier":"_close_lang_file","parameters":"(lang_file)","argument_list":"","return_statement":"","docstring":"Closes a <lang>.json file created with _create_lang_file().\n\n This also writes the terminating left brace and newline.\n\n Args:\n lang_file: A file opened with _create_lang_file().\n\n Raises:\n IOError: An error occurred while writing to or closing the file.","docstring_summary":"Closes a <lang>.json file created with _create_lang_file().","docstring_tokens":["Closes","a","<lang",">",".","json","file","created","with","_create_lang_file","()","."],"function":"def _close_lang_file(lang_file):\n \"\"\"Closes a <lang>.json file created with _create_lang_file().\n\n This also writes the terminating left brace and newline.\n\n Args:\n lang_file: A file opened with _create_lang_file().\n\n Raises:\n IOError: An error occurred while writing to or closing the file.\n \"\"\"\n lang_file.write('\\n}\\n')\n lang_file.close()","function_tokens":["def","_close_lang_file","(","lang_file",")",":","lang_file",".","write","(","'\\n}\\n'",")","lang_file",".","close","(",")"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/blockly\/i18n\/common.py#L142-L154"}
18
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"blockly\/i18n\/common.py","language":"python","identifier":"_create_key_file","parameters":"(output_dir)","argument_list":"","return_statement":"return key_file","docstring":"Creates a keys.json file mapping Closure keys to Blockly keys.\n\n Args:\n output_dir: Relative directory for output files.\n\n Raises:\n IOError: An error occurred while creating the file.","docstring_summary":"Creates a keys.json file mapping Closure keys to Blockly keys.","docstring_tokens":["Creates","a","keys",".","json","file","mapping","Closure","keys","to","Blockly","keys","."],"function":"def _create_key_file(output_dir):\n \"\"\"Creates a keys.json file mapping Closure keys to Blockly keys.\n\n Args:\n output_dir: Relative directory for output files.\n\n Raises:\n IOError: An error occurred while creating the file.\n \"\"\"\n key_file_name = os.path.join(os.curdir, output_dir, 'keys.json')\n key_file = open(key_file_name, 'w')\n key_file.write('{\\n')\n print 'Created file: ' + key_file_name\n return key_file","function_tokens":["def","_create_key_file","(","output_dir",")",":","key_file_name","=","os",".","path",".","join","(","os",".","curdir",",","output_dir",",","'keys.json'",")","key_file","=","open","(","key_file_name",",","'w'",")","key_file",".","write","(","'{\\n'",")","print","'Created file: '","+","key_file_name","return","key_file"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/blockly\/i18n\/common.py#L157-L170"}
19
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"blockly\/i18n\/common.py","language":"python","identifier":"_close_key_file","parameters":"(key_file)","argument_list":"","return_statement":"","docstring":"Closes a key file created and opened with _create_key_file().\n\n Args:\n key_file: A file created by _create_key_file().\n\n Raises:\n IOError: An error occurred while writing to or closing the file.","docstring_summary":"Closes a key file created and opened with _create_key_file().","docstring_tokens":["Closes","a","key","file","created","and","opened","with","_create_key_file","()","."],"function":"def _close_key_file(key_file):\n \"\"\"Closes a key file created and opened with _create_key_file().\n\n Args:\n key_file: A file created by _create_key_file().\n\n Raises:\n IOError: An error occurred while writing to or closing the file.\n \"\"\"\n key_file.write('\\n}\\n')\n key_file.close()","function_tokens":["def","_close_key_file","(","key_file",")",":","key_file",".","write","(","'\\n}\\n'",")","key_file",".","close","(",")"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/blockly\/i18n\/common.py#L173-L183"}
20
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"blockly\/i18n\/common.py","language":"python","identifier":"write_files","parameters":"(author, lang, output_dir, units, write_key_file)","argument_list":"","return_statement":"","docstring":"Writes the output files for the given units.\n\n There are three possible output files:\n * lang_file: JSON file mapping meanings (e.g., Maze.turnLeft) to the\n English text. The base name of the language file is specified by the\n \"lang\" command-line argument.\n * key_file: JSON file mapping meanings to Soy-generated keys (long hash\n codes). This is only output if the parameter write_key_file is True.\n * qqq_file: JSON file mapping meanings to descriptions.\n\n Args:\n author: Name and email address of contact for translators.\n lang: ISO 639-1 source language code.\n output_dir: Relative directory for output files.\n units: A list of dictionaries with entries for 'meaning', 'source',\n 'description', and 'keys' (the last only if write_key_file is true),\n in the order desired in the output files.\n write_key_file: Whether to output a keys.json file.\n\n Raises:\n IOError: An error occurs opening, writing to, or closing a file.\n KeyError: An expected key is missing from units.","docstring_summary":"Writes the output files for the given units.","docstring_tokens":["Writes","the","output","files","for","the","given","units","."],"function":"def write_files(author, lang, output_dir, units, write_key_file):\n \"\"\"Writes the output files for the given units.\n\n There are three possible output files:\n * lang_file: JSON file mapping meanings (e.g., Maze.turnLeft) to the\n English text. The base name of the language file is specified by the\n \"lang\" command-line argument.\n * key_file: JSON file mapping meanings to Soy-generated keys (long hash\n codes). This is only output if the parameter write_key_file is True.\n * qqq_file: JSON file mapping meanings to descriptions.\n\n Args:\n author: Name and email address of contact for translators.\n lang: ISO 639-1 source language code.\n output_dir: Relative directory for output files.\n units: A list of dictionaries with entries for 'meaning', 'source',\n 'description', and 'keys' (the last only if write_key_file is true),\n in the order desired in the output files.\n write_key_file: Whether to output a keys.json file.\n\n Raises:\n IOError: An error occurs opening, writing to, or closing a file.\n KeyError: An expected key is missing from units.\n \"\"\"\n lang_file = _create_lang_file(author, lang, output_dir)\n qqq_file = _create_qqq_file(output_dir)\n if write_key_file:\n key_file = _create_key_file(output_dir)\n first_entry = True\n for unit in units:\n if not first_entry:\n lang_file.write(',\\n')\n if write_key_file:\n key_file.write(',\\n')\n qqq_file.write(',\\n')\n lang_file.write(u'\\t\"{0}\": \"{1}\"'.format(\n unit['meaning'],\n unit['source'].replace('\"', \"'\")))\n if write_key_file:\n key_file.write('\"{0}\": \"{1}\"'.format(unit['meaning'], unit['key']))\n qqq_file.write(u'\\t\"{0}\": \"{1}\"'.format(\n unit['meaning'],\n unit['description'].replace('\"', \"'\").replace(\n '{lb}', '{').replace('{rb}', '}')))\n first_entry = False\n _close_lang_file(lang_file)\n if write_key_file:\n _close_key_file(key_file)\n _close_qqq_file(qqq_file)","function_tokens":["def","write_files","(","author",",","lang",",","output_dir",",","units",",","write_key_file",")",":","lang_file","=","_create_lang_file","(","author",",","lang",",","output_dir",")","qqq_file","=","_create_qqq_file","(","output_dir",")","if","write_key_file",":","key_file","=","_create_key_file","(","output_dir",")","first_entry","=","True","for","unit","in","units",":","if","not","first_entry",":","lang_file",".","write","(","',\\n'",")","if","write_key_file",":","key_file",".","write","(","',\\n'",")","qqq_file",".","write","(","',\\n'",")","lang_file",".","write","(","u'\\t\"{0}\": \"{1}\"'",".","format","(","unit","[","'meaning'","]",",","unit","[","'source'","]",".","replace","(","'\"'",",","\"'\"",")",")",")","if","write_key_file",":","key_file",".","write","(","'\"{0}\": \"{1}\"'",".","format","(","unit","[","'meaning'","]",",","unit","[","'key'","]",")",")","qqq_file",".","write","(","u'\\t\"{0}\": \"{1}\"'",".","format","(","unit","[","'meaning'","]",",","unit","[","'description'","]",".","replace","(","'\"'",",","\"'\"",")",".","replace","(","'{lb}'",",","'{'",")",".","replace","(","'{rb}'",",","'}'",")",")",")","first_entry","=","False","_close_lang_file","(","lang_file",")","if","write_key_file",":","_close_key_file","(","key_file",")","_close_qqq_file","(","qqq_file",")"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/blockly\/i18n\/common.py#L186-L234"}
21
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"blockly\/i18n\/xliff_to_json.py","language":"python","identifier":"_parse_trans_unit","parameters":"(trans_unit)","argument_list":"","return_statement":"return result","docstring":"Converts a trans-unit XML node into a more convenient dictionary format.\n\n Args:\n trans_unit: An XML representation of a .xlf translation unit.\n\n Returns:\n A dictionary with useful information about the translation unit.\n The returned dictionary is guaranteed to have an entry for 'key' and\n may have entries for 'source', 'target', 'description', and 'meaning'\n if present in the argument.\n\n Raises:\n InputError: A required field was not present.","docstring_summary":"Converts a trans-unit XML node into a more convenient dictionary format.","docstring_tokens":["Converts","a","trans","-","unit","XML","node","into","a","more","convenient","dictionary","format","."],"function":"def _parse_trans_unit(trans_unit):\n \"\"\"Converts a trans-unit XML node into a more convenient dictionary format.\n\n Args:\n trans_unit: An XML representation of a .xlf translation unit.\n\n Returns:\n A dictionary with useful information about the translation unit.\n The returned dictionary is guaranteed to have an entry for 'key' and\n may have entries for 'source', 'target', 'description', and 'meaning'\n if present in the argument.\n\n Raises:\n InputError: A required field was not present.\n \"\"\"\n\n def get_value(tag_name):\n elts = trans_unit.getElementsByTagName(tag_name)\n if not elts:\n return None\n elif len(elts) == 1:\n return ''.join([child.toxml() for child in elts[0].childNodes])\n else:\n raise InputError('', 'Unable to extract ' + tag_name)\n\n result = {}\n key = trans_unit.getAttribute('id')\n if not key:\n raise InputError('', 'id attribute not found')\n result['key'] = key\n\n # Get source and target, if present.\n try:\n result['source'] = get_value('source')\n result['target'] = get_value('target')\n except InputError, e:\n raise InputError(key, e.msg)\n\n # Get notes, using the from value as key and the data as value.\n notes = trans_unit.getElementsByTagName('note')\n for note in notes:\n from_value = note.getAttribute('from')\n if from_value and len(note.childNodes) == 1:\n result[from_value] = note.childNodes[0].data\n else:\n raise InputError(key, 'Unable to extract ' + from_value)\n\n return result","function_tokens":["def","_parse_trans_unit","(","trans_unit",")",":","def","get_value","(","tag_name",")",":","elts","=","trans_unit",".","getElementsByTagName","(","tag_name",")","if","not","elts",":","return","None","elif","len","(","elts",")","==","1",":","return","''",".","join","(","[","child",".","toxml","(",")","for","child","in","elts","[","0","]",".","childNodes","]",")","else",":","raise","InputError","(","''",",","'Unable to extract '","+","tag_name",")","result","=","{","}","key","=","trans_unit",".","getAttribute","(","'id'",")","if","not","key",":","raise","InputError","(","''",",","'id attribute not found'",")","result","[","'key'","]","=","key","# Get source and target, if present.","try",":","result","[","'source'","]","=","get_value","(","'source'",")","result","[","'target'","]","=","get_value","(","'target'",")","except","InputError",",","e",":","raise","InputError","(","key",",","e",".","msg",")","# Get notes, using the from value as key and the data as value.","notes","=","trans_unit",".","getElementsByTagName","(","'note'",")","for","note","in","notes",":","from_value","=","note",".","getAttribute","(","'from'",")","if","from_value","and","len","(","note",".","childNodes",")","==","1",":","result","[","from_value","]","=","note",".","childNodes","[","0","]",".","data","else",":","raise","InputError","(","key",",","'Unable to extract '","+","from_value",")","return","result"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/blockly\/i18n\/xliff_to_json.py#L33-L80"}
22
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"blockly\/i18n\/xliff_to_json.py","language":"python","identifier":"_process_file","parameters":"(filename)","argument_list":"","return_statement":"","docstring":"Builds list of translation units from input file.\n\n Each translation unit in the input file includes:\n - an id (opaquely generated by Soy)\n - the Blockly name for the message\n - the text in the source language (generally English)\n - a description for the translator\n\n The Soy and Blockly ids are joined with a hyphen and serve as the\n keys in both output files. The value is the corresponding text (in the\n <lang>.json file) or the description (in the qqq.json file).\n\n Args:\n filename: The name of an .xlf file produced by Closure.\n\n Raises:\n IOError: An I\/O error occurred with an input or output file.\n InputError: The input file could not be parsed or lacked required\n fields.\n\n Returns:\n A list of dictionaries produced by parse_trans_unit().","docstring_summary":"Builds list of translation units from input file.","docstring_tokens":["Builds","list","of","translation","units","from","input","file","."],"function":"def _process_file(filename):\n \"\"\"Builds list of translation units from input file.\n\n Each translation unit in the input file includes:\n - an id (opaquely generated by Soy)\n - the Blockly name for the message\n - the text in the source language (generally English)\n - a description for the translator\n\n The Soy and Blockly ids are joined with a hyphen and serve as the\n keys in both output files. The value is the corresponding text (in the\n <lang>.json file) or the description (in the qqq.json file).\n\n Args:\n filename: The name of an .xlf file produced by Closure.\n\n Raises:\n IOError: An I\/O error occurred with an input or output file.\n InputError: The input file could not be parsed or lacked required\n fields.\n\n Returns:\n A list of dictionaries produced by parse_trans_unit().\n \"\"\"\n try:\n results = [] # list of dictionaries (return value)\n names = [] # list of names of encountered keys (local variable)\n try:\n parsed_xml = minidom.parse(filename)\n except IOError:\n # Don't get caught by below handler\n raise\n except Exception, e:\n print\n raise InputError(filename, str(e))\n\n # Make sure needed fields are present and non-empty.\n for trans_unit in parsed_xml.getElementsByTagName('trans-unit'):\n unit = _parse_trans_unit(trans_unit)\n for key in ['description', 'meaning', 'source']:\n if not key in unit or not unit[key]:\n raise InputError(filename + ':' + unit['key'],\n key + ' not found')\n if unit['description'].lower() == 'ibid':\n if unit['meaning'] not in names:\n # If the term has not already been described, the use of 'ibid'\n # is an error.\n raise InputError(\n filename,\n 'First encountered definition of: ' + unit['meaning']\n + ' has definition: ' + unit['description']\n + '. This error can occur if the definition was not'\n + ' provided on the first appearance of the message'\n + ' or if the source (English-language) messages differ.')\n else:\n # If term has already been described, 'ibid' was used correctly,\n # and we output nothing.\n pass\n else:\n if unit['meaning'] in names:\n raise InputError(filename,\n 'Second definition of: ' + unit['meaning'])\n names.append(unit['meaning'])\n results.append(unit)\n\n return results\n except IOError, e:\n print 'Error with file {0}: {1}'.format(filename, e.strerror)\n sys.exit(1)","function_tokens":["def","_process_file","(","filename",")",":","try",":","results","=","[","]","# list of dictionaries (return value)","names","=","[","]","# list of names of encountered keys (local variable)","try",":","parsed_xml","=","minidom",".","parse","(","filename",")","except","IOError",":","# Don't get caught by below handler","raise","except","Exception",",","e",":","print","raise","InputError","(","filename",",","str","(","e",")",")","# Make sure needed fields are present and non-empty.","for","trans_unit","in","parsed_xml",".","getElementsByTagName","(","'trans-unit'",")",":","unit","=","_parse_trans_unit","(","trans_unit",")","for","key","in","[","'description'",",","'meaning'",",","'source'","]",":","if","not","key","in","unit","or","not","unit","[","key","]",":","raise","InputError","(","filename","+","':'","+","unit","[","'key'","]",",","key","+","' not found'",")","if","unit","[","'description'","]",".","lower","(",")","==","'ibid'",":","if","unit","[","'meaning'","]","not","in","names",":","# If the term has not already been described, the use of 'ibid'","# is an error.","raise","InputError","(","filename",",","'First encountered definition of: '","+","unit","[","'meaning'","]","+","' has definition: '","+","unit","[","'description'","]","+","'. This error can occur if the definition was not'","+","' provided on the first appearance of the message'","+","' or if the source (English-language) messages differ.'",")","else",":","# If term has already been described, 'ibid' was used correctly,","# and we output nothing.","pass","else",":","if","unit","[","'meaning'","]","in","names",":","raise","InputError","(","filename",",","'Second definition of: '","+","unit","[","'meaning'","]",")","names",".","append","(","unit","[","'meaning'","]",")","results",".","append","(","unit",")","return","results","except","IOError",",","e",":","print","'Error with file {0}: {1}'",".","format","(","filename",",","e",".","strerror",")","sys",".","exit","(","1",")"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/blockly\/i18n\/xliff_to_json.py#L83-L151"}
23
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"blockly\/i18n\/xliff_to_json.py","language":"python","identifier":"sort_units","parameters":"(units, templates)","argument_list":"","return_statement":"return sorted(units, key=key_function)","docstring":"Sorts the translation units by their definition order in the template.\n\n Args:\n units: A list of dictionaries produced by parse_trans_unit()\n that have a non-empty value for the key 'meaning'.\n templates: A string containing the Soy templates in which each of\n the units' meanings is defined.\n\n Returns:\n A new list of translation units, sorted by the order in which\n their meaning is defined in the templates.\n\n Raises:\n InputError: If a meaning definition cannot be found in the\n templates.","docstring_summary":"Sorts the translation units by their definition order in the template.","docstring_tokens":["Sorts","the","translation","units","by","their","definition","order","in","the","template","."],"function":"def sort_units(units, templates):\n \"\"\"Sorts the translation units by their definition order in the template.\n\n Args:\n units: A list of dictionaries produced by parse_trans_unit()\n that have a non-empty value for the key 'meaning'.\n templates: A string containing the Soy templates in which each of\n the units' meanings is defined.\n\n Returns:\n A new list of translation units, sorted by the order in which\n their meaning is defined in the templates.\n\n Raises:\n InputError: If a meaning definition cannot be found in the\n templates.\n \"\"\"\n def key_function(unit):\n match = re.search(\n '\\\\smeaning\\\\s*=\\\\s*\"{0}\"\\\\s'.format(unit['meaning']),\n templates)\n if match:\n return match.start()\n else:\n raise InputError(args.templates,\n 'msg definition for meaning not found: ' +\n unit['meaning'])\n return sorted(units, key=key_function)","function_tokens":["def","sort_units","(","units",",","templates",")",":","def","key_function","(","unit",")",":","match","=","re",".","search","(","'\\\\smeaning\\\\s*=\\\\s*\"{0}\"\\\\s'",".","format","(","unit","[","'meaning'","]",")",",","templates",")","if","match",":","return","match",".","start","(",")","else",":","raise","InputError","(","args",".","templates",",","'msg definition for meaning not found: '","+","unit","[","'meaning'","]",")","return","sorted","(","units",",","key","=","key_function",")"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/blockly\/i18n\/xliff_to_json.py#L154-L181"}
24
+ {"nwo":"BlocklyDuino\/BlocklyDuino","sha":"265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d","path":"blockly\/i18n\/xliff_to_json.py","language":"python","identifier":"main","parameters":"()","argument_list":"","return_statement":"","docstring":"Parses arguments and processes the specified file.\n\n Raises:\n IOError: An I\/O error occurred with an input or output file.\n InputError: Input files lacked required fields.","docstring_summary":"Parses arguments and processes the specified file.","docstring_tokens":["Parses","arguments","and","processes","the","specified","file","."],"function":"def main():\n \"\"\"Parses arguments and processes the specified file.\n\n Raises:\n IOError: An I\/O error occurred with an input or output file.\n InputError: Input files lacked required fields.\n \"\"\"\n # Set up argument parser.\n parser = argparse.ArgumentParser(description='Create translation files.')\n parser.add_argument(\n '--author',\n default='Ellen Spertus <ellen.spertus@gmail.com>',\n help='name and email address of contact for translators')\n parser.add_argument('--lang', default='en',\n help='ISO 639-1 source language code')\n parser.add_argument('--output_dir', default='json',\n help='relative directory for output files')\n parser.add_argument('--xlf', help='file containing xlf definitions')\n parser.add_argument('--templates', default=['template.soy'], nargs='+',\n help='relative path to Soy templates, comma or space '\n 'separated (used for ordering messages)')\n global args\n args = parser.parse_args()\n\n # Make sure output_dir ends with slash.\n if (not args.output_dir.endswith(os.path.sep)):\n args.output_dir += os.path.sep\n\n # Process the input file, and sort the entries.\n units = _process_file(args.xlf)\n files = []\n for arg in args.templates:\n for filename in arg.split(','):\n filename = filename.strip();\n if filename:\n with open(filename) as myfile:\n files.append(' '.join(line.strip() for line in myfile))\n sorted_units = sort_units(units, ' '.join(files))\n\n # Write the output files.\n write_files(args.author, args.lang, args.output_dir, sorted_units, True)\n\n # Delete the input .xlf file.\n os.remove(args.xlf)\n print('Removed ' + args.xlf)","function_tokens":["def","main","(",")",":","# Set up argument parser.","parser","=","argparse",".","ArgumentParser","(","description","=","'Create translation files.'",")","parser",".","add_argument","(","'--author'",",","default","=","'Ellen Spertus <ellen.spertus@gmail.com>'",",","help","=","'name and email address of contact for translators'",")","parser",".","add_argument","(","'--lang'",",","default","=","'en'",",","help","=","'ISO 639-1 source language code'",")","parser",".","add_argument","(","'--output_dir'",",","default","=","'json'",",","help","=","'relative directory for output files'",")","parser",".","add_argument","(","'--xlf'",",","help","=","'file containing xlf definitions'",")","parser",".","add_argument","(","'--templates'",",","default","=","[","'template.soy'","]",",","nargs","=","'+'",",","help","=","'relative path to Soy templates, comma or space '","'separated (used for ordering messages)'",")","global","args","args","=","parser",".","parse_args","(",")","# Make sure output_dir ends with slash.","if","(","not","args",".","output_dir",".","endswith","(","os",".","path",".","sep",")",")",":","args",".","output_dir","+=","os",".","path",".","sep","# Process the input file, and sort the entries.","units","=","_process_file","(","args",".","xlf",")","files","=","[","]","for","arg","in","args",".","templates",":","for","filename","in","arg",".","split","(","','",")",":","filename","=","filename",".","strip","(",")","if","filename",":","with","open","(","filename",")","as","myfile",":","files",".","append","(","' '",".","join","(","line",".","strip","(",")","for","line","in","myfile",")",")","sorted_units","=","sort_units","(","units",",","' '",".","join","(","files",")",")","# Write the output files.","write_files","(","args",".","author",",","args",".","lang",",","args",".","output_dir",",","sorted_units",",","True",")","# Delete the input .xlf file.","os",".","remove","(","args",".","xlf",")","print","(","'Removed '","+","args",".","xlf",")"],"url":"https:\/\/github.com\/BlocklyDuino\/BlocklyDuino\/blob\/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d\/blockly\/i18n\/xliff_to_json.py#L184-L228"}
BosNaufal__react-simple-pwa.jsonl ADDED
@@ -0,0 +1,4 @@
 
 
 
 
1
+ {"nwo":"BosNaufal\/react-simple-pwa","sha":"5260ec6b87ec0dd6864d2697104f555672c0d567","path":"src\/vendor\/ionicons\/builder\/scripts\/eotlitetool.py","language":"python","identifier":"get_table_directory","parameters":"(data)","argument_list":"","return_statement":"return font","docstring":"read the SFNT header and table directory","docstring_summary":"read the SFNT header and table directory","docstring_tokens":["read","the","SFNT","header","and","table","directory"],"function":"def get_table_directory(data):\n \"\"\"read the SFNT header and table directory\"\"\"\n datalen = len(data)\n sfntsize = struct.calcsize(OpenType.SFNT_UNPACK)\n if sfntsize > datalen:\n raise FontError, 'truncated font data'\n sfntvers, numTables = struct.unpack(OpenType.SFNT_UNPACK, data[:sfntsize])[:2]\n if sfntvers != OpenType.SFNT_CFF and sfntvers != OpenType.SFNT_TRUE:\n raise FontError, 'invalid font type';\n \n font = {}\n font['version'] = sfntvers\n font['numTables'] = numTables\n \n # create set of offsets, lengths for tables\n table_dir_size = struct.calcsize(OpenType.TABLE_DIR_UNPACK)\n if sfntsize + table_dir_size * numTables > datalen:\n raise FontError, 'truncated font data, table directory extends past end of data'\n table_dir = {}\n for i in range(0, numTables):\n start = sfntsize + i * table_dir_size\n end = start + table_dir_size\n tag, check, bongo, dirlen = struct.unpack(OpenType.TABLE_DIR_UNPACK, data[start:end])\n table_dir[tag] = {'offset': bongo, 'length': dirlen, 'checksum': check}\n \n font['tableDir'] = table_dir\n \n return font","function_tokens":["def","get_table_directory","(","data",")",":","datalen","=","len","(","data",")","sfntsize","=","struct",".","calcsize","(","OpenType",".","SFNT_UNPACK",")","if","sfntsize",">","datalen",":","raise","FontError",",","'truncated font data'","sfntvers",",","numTables","=","struct",".","unpack","(","OpenType",".","SFNT_UNPACK",",","data","[",":","sfntsize","]",")","[",":","2","]","if","sfntvers","!=","OpenType",".","SFNT_CFF","and","sfntvers","!=","OpenType",".","SFNT_TRUE",":","raise","FontError",",","'invalid font type'","font","=","{","}","font","[","'version'","]","=","sfntvers","font","[","'numTables'","]","=","numTables","# create set of offsets, lengths for tables","table_dir_size","=","struct",".","calcsize","(","OpenType",".","TABLE_DIR_UNPACK",")","if","sfntsize","+","table_dir_size","*","numTables",">","datalen",":","raise","FontError",",","'truncated font data, table directory extends past end of data'","table_dir","=","{","}","for","i","in","range","(","0",",","numTables",")",":","start","=","sfntsize","+","i","*","table_dir_size","end","=","start","+","table_dir_size","tag",",","check",",","bongo",",","dirlen","=","struct",".","unpack","(","OpenType",".","TABLE_DIR_UNPACK",",","data","[","start",":","end","]",")","table_dir","[","tag","]","=","{","'offset'",":","bongo",",","'length'",":","dirlen",",","'checksum'",":","check","}","font","[","'tableDir'","]","=","table_dir","return","font"],"url":"https:\/\/github.com\/BosNaufal\/react-simple-pwa\/blob\/5260ec6b87ec0dd6864d2697104f555672c0d567\/src\/vendor\/ionicons\/builder\/scripts\/eotlitetool.py#L287-L314"}
2
+ {"nwo":"BosNaufal\/react-simple-pwa","sha":"5260ec6b87ec0dd6864d2697104f555672c0d567","path":"src\/vendor\/ionicons\/builder\/scripts\/eotlitetool.py","language":"python","identifier":"get_name_records","parameters":"(nametable)","argument_list":"","return_statement":"return name","docstring":"reads through the name records within name table","docstring_summary":"reads through the name records within name table","docstring_tokens":["reads","through","the","name","records","within","name","table"],"function":"def get_name_records(nametable):\n \"\"\"reads through the name records within name table\"\"\"\n name = {}\n # read the header\n headersize = 6\n count, strOffset = struct.unpack('>2H', nametable[2:6])\n namerecsize = struct.calcsize(OpenType.NAME_RECORD_UNPACK)\n if count * namerecsize + headersize > len(nametable):\n raise FontError, 'names exceed size of name table'\n name['count'] = count\n name['strOffset'] = strOffset\n \n # read through the name records\n namerecs = {}\n for i in range(0, count):\n start = headersize + i * namerecsize\n end = start + namerecsize\n platformID, encodingID, languageID, nameID, namelen, offset = struct.unpack(OpenType.NAME_RECORD_UNPACK, nametable[start:end])\n if platformID != OpenType.PLATFORM_ID_MICROSOFT or \\\n encodingID != OpenType.ENCODING_ID_MICROSOFT_UNICODEBMP or \\\n languageID != OpenType.LANG_ID_MICROSOFT_EN_US:\n continue\n namerecs[nameID] = {'offset': offset, 'length': namelen}\n \n name['namerecords'] = namerecs\n return name","function_tokens":["def","get_name_records","(","nametable",")",":","name","=","{","}","# read the header","headersize","=","6","count",",","strOffset","=","struct",".","unpack","(","'>2H'",",","nametable","[","2",":","6","]",")","namerecsize","=","struct",".","calcsize","(","OpenType",".","NAME_RECORD_UNPACK",")","if","count","*","namerecsize","+","headersize",">","len","(","nametable",")",":","raise","FontError",",","'names exceed size of name table'","name","[","'count'","]","=","count","name","[","'strOffset'","]","=","strOffset","# read through the name records","namerecs","=","{","}","for","i","in","range","(","0",",","count",")",":","start","=","headersize","+","i","*","namerecsize","end","=","start","+","namerecsize","platformID",",","encodingID",",","languageID",",","nameID",",","namelen",",","offset","=","struct",".","unpack","(","OpenType",".","NAME_RECORD_UNPACK",",","nametable","[","start",":","end","]",")","if","platformID","!=","OpenType",".","PLATFORM_ID_MICROSOFT","or","encodingID","!=","OpenType",".","ENCODING_ID_MICROSOFT_UNICODEBMP","or","languageID","!=","OpenType",".","LANG_ID_MICROSOFT_EN_US",":","continue","namerecs","[","nameID","]","=","{","'offset'",":","offset",",","'length'",":","namelen","}","name","[","'namerecords'","]","=","namerecs","return","name"],"url":"https:\/\/github.com\/BosNaufal\/react-simple-pwa\/blob\/5260ec6b87ec0dd6864d2697104f555672c0d567\/src\/vendor\/ionicons\/builder\/scripts\/eotlitetool.py#L316-L341"}
3
+ {"nwo":"BosNaufal\/react-simple-pwa","sha":"5260ec6b87ec0dd6864d2697104f555672c0d567","path":"src\/vendor\/ionicons\/builder\/scripts\/eotlitetool.py","language":"python","identifier":"make_eot_name_headers","parameters":"(fontdata, nameTableDir)","argument_list":"","return_statement":"return ''.join(nameheaders)","docstring":"extracts names from the name table and generates the names header portion of the EOT header","docstring_summary":"extracts names from the name table and generates the names header portion of the EOT header","docstring_tokens":["extracts","names","from","the","name","table","and","generates","the","names","header","portion","of","the","EOT","header"],"function":"def make_eot_name_headers(fontdata, nameTableDir):\n \"\"\"extracts names from the name table and generates the names header portion of the EOT header\"\"\"\n nameoffset = nameTableDir['offset']\n namelen = nameTableDir['length']\n name = get_name_records(fontdata[nameoffset : nameoffset + namelen])\n namestroffset = name['strOffset']\n namerecs = name['namerecords']\n \n eotnames = (OpenType.NAME_ID_FAMILY, OpenType.NAME_ID_STYLE, OpenType.NAME_ID_VERSION, OpenType.NAME_ID_FULL)\n nameheaders = []\n for nameid in eotnames:\n if nameid in namerecs:\n namerecord = namerecs[nameid]\n noffset = namerecord['offset']\n nlen = namerecord['length']\n nformat = '%dH' % (nlen \/ 2)\t\t# length is in number of bytes\n start = nameoffset + namestroffset + noffset\n end = start + nlen\n nstr = struct.unpack('>' + nformat, fontdata[start:end])\n nameheaders.append(struct.pack('<H' + nformat + '2x', nlen, *nstr))\n else:\n nameheaders.append(struct.pack('4x')) # len = 0, padding = 0\n \n return ''.join(nameheaders)","function_tokens":["def","make_eot_name_headers","(","fontdata",",","nameTableDir",")",":","nameoffset","=","nameTableDir","[","'offset'","]","namelen","=","nameTableDir","[","'length'","]","name","=","get_name_records","(","fontdata","[","nameoffset",":","nameoffset","+","namelen","]",")","namestroffset","=","name","[","'strOffset'","]","namerecs","=","name","[","'namerecords'","]","eotnames","=","(","OpenType",".","NAME_ID_FAMILY",",","OpenType",".","NAME_ID_STYLE",",","OpenType",".","NAME_ID_VERSION",",","OpenType",".","NAME_ID_FULL",")","nameheaders","=","[","]","for","nameid","in","eotnames",":","if","nameid","in","namerecs",":","namerecord","=","namerecs","[","nameid","]","noffset","=","namerecord","[","'offset'","]","nlen","=","namerecord","[","'length'","]","nformat","=","'%dH'","%","(","nlen","\/","2",")","# length is in number of bytes","start","=","nameoffset","+","namestroffset","+","noffset","end","=","start","+","nlen","nstr","=","struct",".","unpack","(","'>'","+","nformat",",","fontdata","[","start",":","end","]",")","nameheaders",".","append","(","struct",".","pack","(","'<H'","+","nformat","+","'2x'",",","nlen",",","*","nstr",")",")","else",":","nameheaders",".","append","(","struct",".","pack","(","'4x'",")",")","# len = 0, padding = 0","return","''",".","join","(","nameheaders",")"],"url":"https:\/\/github.com\/BosNaufal\/react-simple-pwa\/blob\/5260ec6b87ec0dd6864d2697104f555672c0d567\/src\/vendor\/ionicons\/builder\/scripts\/eotlitetool.py#L343-L366"}
4
+ {"nwo":"BosNaufal\/react-simple-pwa","sha":"5260ec6b87ec0dd6864d2697104f555672c0d567","path":"src\/vendor\/ionicons\/builder\/scripts\/eotlitetool.py","language":"python","identifier":"make_eot_header","parameters":"(fontdata)","argument_list":"","return_statement":"return ''.join((fixed, nameheaders, rootstring))","docstring":"given ttf font data produce an EOT header","docstring_summary":"given ttf font data produce an EOT header","docstring_tokens":["given","ttf","font","data","produce","an","EOT","header"],"function":"def make_eot_header(fontdata):\n \"\"\"given ttf font data produce an EOT header\"\"\"\n fontDataSize = len(fontdata)\n font = get_table_directory(fontdata)\n \n # toss out .otf fonts, t2embed library doesn't support these\n tableDir = font['tableDir']\n \n # check for required tables\n required = (OpenType.TABLE_HEAD, OpenType.TABLE_NAME, OpenType.TABLE_OS2)\n for table in required:\n if not (table in tableDir):\n raise FontError, 'missing required table ' + multicharval(table)\n \n # read name strings\n \n # pull out data from individual tables to construct fixed header portion\n # need to calculate eotSize before packing\n version = EOT.EOT_VERSION\n flags = 0\n charset = EOT.EOT_DEFAULT_CHARSET\n magicNumber = EOT.EOT_MAGIC_NUMBER\n \n # read values from OS\/2 table\n os2Dir = tableDir[OpenType.TABLE_OS2]\n os2offset = os2Dir['offset']\n os2size = struct.calcsize(OpenType.OS2_UNPACK)\n \n if os2size > os2Dir['length']:\n raise FontError, 'OS\/2 table invalid length'\n \n os2fields = struct.unpack(OpenType.OS2_UNPACK, fontdata[os2offset : os2offset + os2size])\n \n panose = []\n urange = []\n codepage = []\n \n weight, fsType = os2fields[:2]\n panose[:10] = os2fields[2:12]\n urange[:4] = os2fields[12:16]\n fsSelection = os2fields[16]\n codepage[:2] = os2fields[17:19]\n \n italic = fsSelection & OpenType.OS2_FSSELECTION_ITALIC\n \n # read in values from head table\n headDir = tableDir[OpenType.TABLE_HEAD]\n headoffset = headDir['offset']\n headsize = struct.calcsize(OpenType.HEAD_UNPACK)\n \n if headsize > headDir['length']:\n raise FontError, 'head table invalid length'\n \n headfields = struct.unpack(OpenType.HEAD_UNPACK, fontdata[headoffset : headoffset + headsize])\n checkSumAdjustment = headfields[0]\n \n # make name headers\n nameheaders = make_eot_name_headers(fontdata, tableDir[OpenType.TABLE_NAME])\n rootstring = make_root_string()\n \n # calculate the total eot size\n eotSize = struct.calcsize(EOT.EOT_HEADER_PACK) + len(nameheaders) + len(rootstring) + fontDataSize\n fixed = struct.pack(EOT.EOT_HEADER_PACK,\n *([eotSize, fontDataSize, version, flags] + panose + [charset, italic] +\n [weight, fsType, magicNumber] + urange + codepage + [checkSumAdjustment]))\n \n return ''.join((fixed, nameheaders, rootstring))","function_tokens":["def","make_eot_header","(","fontdata",")",":","fontDataSize","=","len","(","fontdata",")","font","=","get_table_directory","(","fontdata",")","# toss out .otf fonts, t2embed library doesn't support these","tableDir","=","font","[","'tableDir'","]","# check for required tables","required","=","(","OpenType",".","TABLE_HEAD",",","OpenType",".","TABLE_NAME",",","OpenType",".","TABLE_OS2",")","for","table","in","required",":","if","not","(","table","in","tableDir",")",":","raise","FontError",",","'missing required table '","+","multicharval","(","table",")","# read name strings","# pull out data from individual tables to construct fixed header portion","# need to calculate eotSize before packing","version","=","EOT",".","EOT_VERSION","flags","=","0","charset","=","EOT",".","EOT_DEFAULT_CHARSET","magicNumber","=","EOT",".","EOT_MAGIC_NUMBER","# read values from OS\/2 table","os2Dir","=","tableDir","[","OpenType",".","TABLE_OS2","]","os2offset","=","os2Dir","[","'offset'","]","os2size","=","struct",".","calcsize","(","OpenType",".","OS2_UNPACK",")","if","os2size",">","os2Dir","[","'length'","]",":","raise","FontError",",","'OS\/2 table invalid length'","os2fields","=","struct",".","unpack","(","OpenType",".","OS2_UNPACK",",","fontdata","[","os2offset",":","os2offset","+","os2size","]",")","panose","=","[","]","urange","=","[","]","codepage","=","[","]","weight",",","fsType","=","os2fields","[",":","2","]","panose","[",":","10","]","=","os2fields","[","2",":","12","]","urange","[",":","4","]","=","os2fields","[","12",":","16","]","fsSelection","=","os2fields","[","16","]","codepage","[",":","2","]","=","os2fields","[","17",":","19","]","italic","=","fsSelection","&","OpenType",".","OS2_FSSELECTION_ITALIC","# read in values from head table","headDir","=","tableDir","[","OpenType",".","TABLE_HEAD","]","headoffset","=","headDir","[","'offset'","]","headsize","=","struct",".","calcsize","(","OpenType",".","HEAD_UNPACK",")","if","headsize",">","headDir","[","'length'","]",":","raise","FontError",",","'head table invalid length'","headfields","=","struct",".","unpack","(","OpenType",".","HEAD_UNPACK",",","fontdata","[","headoffset",":","headoffset","+","headsize","]",")","checkSumAdjustment","=","headfields","[","0","]","# make name headers","nameheaders","=","make_eot_name_headers","(","fontdata",",","tableDir","[","OpenType",".","TABLE_NAME","]",")","rootstring","=","make_root_string","(",")","# calculate the total eot size","eotSize","=","struct",".","calcsize","(","EOT",".","EOT_HEADER_PACK",")","+","len","(","nameheaders",")","+","len","(","rootstring",")","+","fontDataSize","fixed","=","struct",".","pack","(","EOT",".","EOT_HEADER_PACK",",","*","(","[","eotSize",",","fontDataSize",",","version",",","flags","]","+","panose","+","[","charset",",","italic","]","+","[","weight",",","fsType",",","magicNumber","]","+","urange","+","codepage","+","[","checkSumAdjustment","]",")",")","return","''",".","join","(","(","fixed",",","nameheaders",",","rootstring",")",")"],"url":"https:\/\/github.com\/BosNaufal\/react-simple-pwa\/blob\/5260ec6b87ec0dd6864d2697104f555672c0d567\/src\/vendor\/ionicons\/builder\/scripts\/eotlitetool.py#L372-L438"}
ByronHsu__Never-Blink.jsonl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
1
+ {"nwo":"ByronHsu\/Never-Blink","sha":"fa5753fb27633ef403e3cc0641b9f78da8117733","path":"server.py","language":"python","identifier":"find_by_id","parameters":"(_id)","argument_list":"","return_statement":"return index","docstring":"Find element by id in the player_list.\n Args:\n _id: ID of this player.\n Return:\n index: The index of this player in the player list.","docstring_summary":"Find element by id in the player_list.\n Args:\n _id: ID of this player.\n Return:\n index: The index of this player in the player list.","docstring_tokens":["Find","element","by","id","in","the","player_list",".","Args",":","_id",":","ID","of","this","player",".","Return",":","index",":","The","index","of","this","player","in","the","player","list","."],"function":"def find_by_id(_id):\n \"\"\"\n Find element by id in the player_list.\n Args:\n _id: ID of this player.\n Return:\n index: The index of this player in the player list.\n \"\"\"\n filt = [i for (i, item) in enumerate(player_list) if item['id'] == _id]\n index = None if len(filt) == 0 else filt[0]\n return index","function_tokens":["def","find_by_id","(","_id",")",":","filt","=","[","i","for","(","i",",","item",")","in","enumerate","(","player_list",")","if","item","[","'id'","]","==","_id","]","index","=","None","if","len","(","filt",")","==","0","else","filt","[","0","]","return","index"],"url":"https:\/\/github.com\/ByronHsu\/Never-Blink\/blob\/fa5753fb27633ef403e3cc0641b9f78da8117733\/server.py#L39-L49"}
2
+ {"nwo":"ByronHsu\/Never-Blink","sha":"fa5753fb27633ef403e3cc0641b9f78da8117733","path":"server.py","language":"python","identifier":"find_random_waiting","parameters":"(_id)","argument_list":"","return_statement":"return index","docstring":"Randomly choose a 'waiting' player from the list.\n But it can not choose itself(_id).\n Args:\n _id: ID of this player.\n Return:\n index: The index of the chosen player in the player list.","docstring_summary":"Randomly choose a 'waiting' player from the list.\n But it can not choose itself(_id).\n Args:\n _id: ID of this player.\n Return:\n index: The index of the chosen player in the player list.","docstring_tokens":["Randomly","choose","a","waiting","player","from","the","list",".","But","it","can","not","choose","itself","(","_id",")",".","Args",":","_id",":","ID","of","this","player",".","Return",":","index",":","The","index","of","the","chosen","player","in","the","player","list","."],"function":"def find_random_waiting(_id):\n \"\"\"\n Randomly choose a 'waiting' player from the list.\n But it can not choose itself(_id).\n Args:\n _id: ID of this player.\n Return:\n index: The index of the chosen player in the player list.\n \"\"\"\n filt = [i for (i, item) in enumerate(player_list) if (\n item['status'] == 'waiting' and item['id'] != _id)]\n if len(filt):\n index = random.choice(filt)\n else:\n index = None\n return index","function_tokens":["def","find_random_waiting","(","_id",")",":","filt","=","[","i","for","(","i",",","item",")","in","enumerate","(","player_list",")","if","(","item","[","'status'","]","==","'waiting'","and","item","[","'id'","]","!=","_id",")","]","if","len","(","filt",")",":","index","=","random",".","choice","(","filt",")","else",":","index","=","None","return","index"],"url":"https:\/\/github.com\/ByronHsu\/Never-Blink\/blob\/fa5753fb27633ef403e3cc0641b9f78da8117733\/server.py#L52-L67"}
3
+ {"nwo":"ByronHsu\/Never-Blink","sha":"fa5753fb27633ef403e3cc0641b9f78da8117733","path":"server.py","language":"python","identifier":"on_connect","parameters":"()","argument_list":"","return_statement":"","docstring":"Called when the client just connected.\n Create a player and push it to the list.\n Player:\n id: Indentifier of the player.\n status: 'idle', 'waiting', 'playing'.\n ear: Eye aspect ratio.\n rival: The rival's id.\n startTime: The start time of the game.\n end: Whether the game has ended. '1' means end, '0' means playing.","docstring_summary":"Called when the client just connected.\n Create a player and push it to the list.\n Player:\n id: Indentifier of the player.\n status: 'idle', 'waiting', 'playing'.\n ear: Eye aspect ratio.\n rival: The rival's id.\n startTime: The start time of the game.\n end: Whether the game has ended. '1' means end, '0' means playing.","docstring_tokens":["Called","when","the","client","just","connected",".","Create","a","player","and","push","it","to","the","list",".","Player",":","id",":","Indentifier","of","the","player",".","status",":","idle","waiting","playing",".","ear",":","Eye","aspect","ratio",".","rival",":","The","rival","s","id",".","startTime",":","The","start","time","of","the","game",".","end",":","Whether","the","game","has","ended",".","1","means","end","0","means","playing","."],"function":"def on_connect():\n \"\"\"\n Called when the client just connected.\n Create a player and push it to the list.\n Player:\n id: Indentifier of the player.\n status: 'idle', 'waiting', 'playing'.\n ear: Eye aspect ratio.\n rival: The rival's id.\n startTime: The start time of the game.\n end: Whether the game has ended. '1' means end, '0' means playing.\n \"\"\"\n client_id = request.args['id']\n index = find_by_id(client_id)\n if not index:\n player_list.append({'id': client_id, 'status': 'idle',\n 'ear': 0, 'rival': None, 'startTime': 0, 'end': 0})\n print(client_id, 'connected !')","function_tokens":["def","on_connect","(",")",":","client_id","=","request",".","args","[","'id'","]","index","=","find_by_id","(","client_id",")","if","not","index",":","player_list",".","append","(","{","'id'",":","client_id",",","'status'",":","'idle'",",","'ear'",":","0",",","'rival'",":","None",",","'startTime'",":","0",",","'end'",":","0","}",")","print","(","client_id",",","'connected !'",")"],"url":"https:\/\/github.com\/ByronHsu\/Never-Blink\/blob\/fa5753fb27633ef403e3cc0641b9f78da8117733\/server.py#L75-L92"}
4
+ {"nwo":"ByronHsu\/Never-Blink","sha":"fa5753fb27633ef403e3cc0641b9f78da8117733","path":"server.py","language":"python","identifier":"on_disconnect","parameters":"(message)","argument_list":"","return_statement":"","docstring":"Called when the client just disconnected.\n Delete the player from the list.","docstring_summary":"Called when the client just disconnected.\n Delete the player from the list.","docstring_tokens":["Called","when","the","client","just","disconnected",".","Delete","the","player","from","the","list","."],"function":"def on_disconnect(message):\n \"\"\"\n Called when the client just disconnected.\n Delete the player from the list.\n \"\"\"\n client_id = message['id']\n index = find_by_id(client_id)\n del player_list[index]\n print(client_id, 'disconnected !')","function_tokens":["def","on_disconnect","(","message",")",":","client_id","=","message","[","'id'","]","index","=","find_by_id","(","client_id",")","del","player_list","[","index","]","print","(","client_id",",","'disconnected !'",")"],"url":"https:\/\/github.com\/ByronHsu\/Never-Blink\/blob\/fa5753fb27633ef403e3cc0641b9f78da8117733\/server.py#L96-L104"}
5
+ {"nwo":"ByronHsu\/Never-Blink","sha":"fa5753fb27633ef403e3cc0641b9f78da8117733","path":"server.py","language":"python","identifier":"set_player_wait","parameters":"(message)","argument_list":"","return_statement":"","docstring":"Set the player's status to 'waiting'.\n And then Randomly match a player whose status is also 'waiting'.\n Args:\n id: ID of the player.\n Emit:\n get_rival: Tell the player its rival's id.","docstring_summary":"Set the player's status to 'waiting'.\n And then Randomly match a player whose status is also 'waiting'.\n Args:\n id: ID of the player.\n Emit:\n get_rival: Tell the player its rival's id.","docstring_tokens":["Set","the","player","s","status","to","waiting",".","And","then","Randomly","match","a","player","whose","status","is","also","waiting",".","Args",":","id",":","ID","of","the","player",".","Emit",":","get_rival",":","Tell","the","player","its","rival","s","id","."],"function":"def set_player_wait(message):\n \"\"\"\n Set the player's status to 'waiting'.\n And then Randomly match a player whose status is also 'waiting'.\n Args:\n id: ID of the player.\n Emit:\n get_rival: Tell the player its rival's id.\n \"\"\"\n client_id = message['id']\n curr_index = find_by_id(client_id)\n player_list[curr_index]['status'] = 'waiting'\n print(client_id, 'set to waiting...')\n # look for rival\n rival_index = find_random_waiting(client_id)\n if rival_index != None:\n rival_id = player_list[rival_index]['id']\n player_list[curr_index]['rival'] = rival_id\n player_list[curr_index]['status'] = 'playing'\n\n player_list[rival_index]['rival'] = client_id\n player_list[rival_index]['status'] = 'playing'\n\n emit('get_rival', {'id': rival_id})\n print(client_id, 'find rival', rival_id)","function_tokens":["def","set_player_wait","(","message",")",":","client_id","=","message","[","'id'","]","curr_index","=","find_by_id","(","client_id",")","player_list","[","curr_index","]","[","'status'","]","=","'waiting'","print","(","client_id",",","'set to waiting...'",")","# look for rival","rival_index","=","find_random_waiting","(","client_id",")","if","rival_index","!=","None",":","rival_id","=","player_list","[","rival_index","]","[","'id'","]","player_list","[","curr_index","]","[","'rival'","]","=","rival_id","player_list","[","curr_index","]","[","'status'","]","=","'playing'","player_list","[","rival_index","]","[","'rival'","]","=","client_id","player_list","[","rival_index","]","[","'status'","]","=","'playing'","emit","(","'get_rival'",",","{","'id'",":","rival_id","}",")","print","(","client_id",",","'find rival'",",","rival_id",")"],"url":"https:\/\/github.com\/ByronHsu\/Never-Blink\/blob\/fa5753fb27633ef403e3cc0641b9f78da8117733\/server.py#L108-L132"}
6
+ {"nwo":"ByronHsu\/Never-Blink","sha":"fa5753fb27633ef403e3cc0641b9f78da8117733","path":"server.py","language":"python","identifier":"set_player_startTime","parameters":"(message)","argument_list":"","return_statement":"","docstring":"Set the player's startTime.\n Args:\n id: ID of the player.","docstring_summary":"Set the player's startTime.\n Args:\n id: ID of the player.","docstring_tokens":["Set","the","player","s","startTime",".","Args",":","id",":","ID","of","the","player","."],"function":"def set_player_startTime(message):\n \"\"\"\n Set the player's startTime.\n Args:\n id: ID of the player.\n \"\"\"\n client_id = message['id']\n curr_index = find_by_id(client_id)\n player_list[curr_index]['startTime'] = time.time()\n print('startTime', player_list[curr_index])","function_tokens":["def","set_player_startTime","(","message",")",":","client_id","=","message","[","'id'","]","curr_index","=","find_by_id","(","client_id",")","player_list","[","curr_index","]","[","'startTime'","]","=","time",".","time","(",")","print","(","'startTime'",",","player_list","[","curr_index","]",")"],"url":"https:\/\/github.com\/ByronHsu\/Never-Blink\/blob\/fa5753fb27633ef403e3cc0641b9f78da8117733\/server.py#L136-L145"}
7
+ {"nwo":"ByronHsu\/Never-Blink","sha":"fa5753fb27633ef403e3cc0641b9f78da8117733","path":"server.py","language":"python","identifier":"send_image","parameters":"(message)","argument_list":"","return_statement":"","docstring":"1. Convert base64 string from client to np image.\n 2. Run 'Detector engine' to calculate its value.\n 3. Emit new player data to the player.\n Args:\n uri: Base64 string from client.\n id: ID of the player.\n Emit:\n get_arena_data: send arena status to the client including \n EAR1: Eye aspect ratio of this player.\n EAR2: Eye aspect ratio of its rival.\n elapsed: Elapsed time since start.\n end: Whether the game has ended.","docstring_summary":"1. Convert base64 string from client to np image.\n 2. Run 'Detector engine' to calculate its value.\n 3. Emit new player data to the player.\n Args:\n uri: Base64 string from client.\n id: ID of the player.\n Emit:\n get_arena_data: send arena status to the client including \n EAR1: Eye aspect ratio of this player.\n EAR2: Eye aspect ratio of its rival.\n elapsed: Elapsed time since start.\n end: Whether the game has ended.","docstring_tokens":["1",".","Convert","base64","string","from","client","to","np","image",".","2",".","Run","Detector","engine","to","calculate","its","value",".","3",".","Emit","new","player","data","to","the","player",".","Args",":","uri",":","Base64","string","from","client",".","id",":","ID","of","the","player",".","Emit",":","get_arena_data",":","send","arena","status","to","the","client","including","EAR1",":","Eye","aspect","ratio","of","this","player",".","EAR2",":","Eye","aspect","ratio","of","its","rival",".","elapsed",":","Elapsed","time","since","start",".","end",":","Whether","the","game","has","ended","."],"function":"def send_image(message):\n \"\"\"\n 1. Convert base64 string from client to np image.\n 2. Run 'Detector engine' to calculate its value.\n 3. Emit new player data to the player.\n Args:\n uri: Base64 string from client.\n id: ID of the player.\n Emit:\n get_arena_data: send arena status to the client including \n EAR1: Eye aspect ratio of this player.\n EAR2: Eye aspect ratio of its rival.\n elapsed: Elapsed time since start.\n end: Whether the game has ended.\n \"\"\"\n # ===============\n # Process Base64\n # ===============\n\n uri, _id = message['uri'], message['id']\n # split header and body\n img_data = uri.split(',')[1]\n img_data = base64.b64decode(img_data)\n image = Image.open(io.BytesIO(img_data))\n # bgr\n array = np.array(image)\n REJECT = 0\n\n # ===============\n # Set EAR\n # ===============\n\n index = find_by_id(_id)\n EAR1 = player_list[index]['ear']\n\n # If the game has ended, we should not update the player.\n if player_list[index]['end'] == 0:\n EAR1 = detector.calculate_ear(array)\n player_list[index]['ear'] = EAR1\n player_list[index]['uri'] = uri\n\n # Find rival's EAR.\n rival_id = player_list[index]['rival']\n rival_index = find_by_id(rival_id)\n EAR2 = player_list[rival_index]['ear']\n\n # Calculat elapsed time\n elapsed = time.time() - player_list[index]['startTime']\n\n # EAR < threshold is determined as 'blink'.\n threshold = 0.20\n # The first 3 second is not counted.\n prepare_time = 3\n if ((EAR1 < threshold and EAR1 > 0) or (EAR2 < threshold and EAR2 > 0)) and elapsed > prepare_time:\n # The game end. Set player's status back to 'idle'.\n player_list[index]['end'] = 1\n player_list[index]['status'] = 'idle'\n player_list[rival_index]['end'] = 1\n player_list[rival_index]['status'] = 'idle'\n emit('get_arena_data', {'EAR1': EAR1, 'EAR2': EAR2, 'elapsed': elapsed, 'end': 1,\n 'uri1': player_list[index]['uri'], 'uri2': player_list[rival_index]['uri']})\n else:\n emit('get_arena_data', {'EAR1': EAR1,\n 'EAR2': EAR2, 'elapsed': elapsed, 'end': 0})","function_tokens":["def","send_image","(","message",")",":","# ===============","# Process Base64","# ===============","uri",",","_id","=","message","[","'uri'","]",",","message","[","'id'","]","# split header and body","img_data","=","uri",".","split","(","','",")","[","1","]","img_data","=","base64",".","b64decode","(","img_data",")","image","=","Image",".","open","(","io",".","BytesIO","(","img_data",")",")","# bgr","array","=","np",".","array","(","image",")","REJECT","=","0","# ===============","# Set EAR","# ===============","index","=","find_by_id","(","_id",")","EAR1","=","player_list","[","index","]","[","'ear'","]","# If the game has ended, we should not update the player.","if","player_list","[","index","]","[","'end'","]","==","0",":","EAR1","=","detector",".","calculate_ear","(","array",")","player_list","[","index","]","[","'ear'","]","=","EAR1","player_list","[","index","]","[","'uri'","]","=","uri","# Find rival's EAR.","rival_id","=","player_list","[","index","]","[","'rival'","]","rival_index","=","find_by_id","(","rival_id",")","EAR2","=","player_list","[","rival_index","]","[","'ear'","]","# Calculat elapsed time","elapsed","=","time",".","time","(",")","-","player_list","[","index","]","[","'startTime'","]","# EAR < threshold is determined as 'blink'.","threshold","=","0.20","# The first 3 second is not counted.","prepare_time","=","3","if","(","(","EAR1","<","threshold","and","EAR1",">","0",")","or","(","EAR2","<","threshold","and","EAR2",">","0",")",")","and","elapsed",">","prepare_time",":","# The game end. Set player's status back to 'idle'.","player_list","[","index","]","[","'end'","]","=","1","player_list","[","index","]","[","'status'","]","=","'idle'","player_list","[","rival_index","]","[","'end'","]","=","1","player_list","[","rival_index","]","[","'status'","]","=","'idle'","emit","(","'get_arena_data'",",","{","'EAR1'",":","EAR1",",","'EAR2'",":","EAR2",",","'elapsed'",":","elapsed",",","'end'",":","1",",","'uri1'",":","player_list","[","index","]","[","'uri'","]",",","'uri2'",":","player_list","[","rival_index","]","[","'uri'","]","}",")","else",":","emit","(","'get_arena_data'",",","{","'EAR1'",":","EAR1",",","'EAR2'",":","EAR2",",","'elapsed'",":","elapsed",",","'end'",":","0","}",")"],"url":"https:\/\/github.com\/ByronHsu\/Never-Blink\/blob\/fa5753fb27633ef403e3cc0641b9f78da8117733\/server.py#L149-L212"}
CERT-Polska__drakvuf-sandbox.jsonl ADDED
The diff for this file is too large to render. See raw diff
COVID-19-electronic-health-system__Corona-tracker.jsonl ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"COVID-19-electronic-health-system\/Corona-tracker","sha":"80cab55a7a03c43fa4a3412daa6e4ff1f0a45d8c","path":"src\/python\/pull_gsheets_translations_mvp.py","language":"python","identifier":"depunctuate","parameters":"(text)","argument_list":"","return_statement":"return text","docstring":"Removes punctuation from text.\n\n\tArguments:\n\t\ttext {[string]} -- [any string]\n\n\tReturns:\n\t\t[string] -- [string with punctuation removed]","docstring_summary":"Removes punctuation from text.","docstring_tokens":["Removes","punctuation","from","text","."],"function":"def depunctuate(text):\n\t\"\"\" Removes punctuation from text.\n\n\tArguments:\n\t\ttext {[string]} -- [any string]\n\n\tReturns:\n\t\t[string] -- [string with punctuation removed]\n\t\"\"\"\n\tchars = punctuation\n\tfor c in chars:\n\t\ttext = text.replace(c, \"\")\n\treturn text","function_tokens":["def","depunctuate","(","text",")",":","chars","=","punctuation","for","c","in","chars",":","text","=","text",".","replace","(","c",",","\"\"",")","return","text"],"url":"https:\/\/github.com\/COVID-19-electronic-health-system\/Corona-tracker\/blob\/80cab55a7a03c43fa4a3412daa6e4ff1f0a45d8c\/src\/python\/pull_gsheets_translations_mvp.py#L50-L62"}
2
+ {"nwo":"COVID-19-electronic-health-system\/Corona-tracker","sha":"80cab55a7a03c43fa4a3412daa6e4ff1f0a45d8c","path":"src\/python\/pull_gsheets_translations_mvp.py","language":"python","identifier":"convert_to_camelCase","parameters":"(value)","argument_list":"","return_statement":"","docstring":"Converts a string to camelCase and removes punctuation.\n\n\tArguments:\n\t\tvalue {[string]} -- [string from the 'value' column in language_df]\n\n\tReturns:\n\t\t[string] -- [returns a string with no punctuation, in camelCase format.]","docstring_summary":"Converts a string to camelCase and removes punctuation.","docstring_tokens":["Converts","a","string","to","camelCase","and","removes","punctuation","."],"function":"def convert_to_camelCase(value):\n\t\"\"\" Converts a string to camelCase and removes punctuation.\n\n\tArguments:\n\t\tvalue {[string]} -- [string from the 'value' column in language_df]\n\n\tReturns:\n\t\t[string] -- [returns a string with no punctuation, in camelCase format.]\n\t\"\"\"\n\t# if value is a string with more than one word\n\tif len(value.split()) > 1:\n\t\t#converts value to camelCase\n\t\tcamelCase = value.split()[0].lower() + \" \".join(value.split()[1:]).title().replace(\" \",\"\")\n\t\t#removes punctuation\n\t\treturn camelCase.translate(str.maketrans('', '', punctuation))\n\telse:\n\t\treturn value.lower().translate(str.maketrans('', '', punctuation))","function_tokens":["def","convert_to_camelCase","(","value",")",":","# if value is a string with more than one word","if","len","(","value",".","split","(",")",")",">","1",":","#converts value to camelCase","camelCase","=","value",".","split","(",")","[","0","]",".","lower","(",")","+","\" \"",".","join","(","value",".","split","(",")","[","1",":","]",")",".","title","(",")",".","replace","(","\" \"",",","\"\"",")","#removes punctuation","return","camelCase",".","translate","(","str",".","maketrans","(","''",",","''",",","punctuation",")",")","else",":","return","value",".","lower","(",")",".","translate","(","str",".","maketrans","(","''",",","''",",","punctuation",")",")"],"url":"https:\/\/github.com\/COVID-19-electronic-health-system\/Corona-tracker\/blob\/80cab55a7a03c43fa4a3412daa6e4ff1f0a45d8c\/src\/python\/pull_gsheets_translations_mvp.py#L64-L80"}
3
+ {"nwo":"COVID-19-electronic-health-system\/Corona-tracker","sha":"80cab55a7a03c43fa4a3412daa6e4ff1f0a45d8c","path":"src\/python\/pull_gsheets_translations_mvp.py","language":"python","identifier":"education_value_cleaner","parameters":"(language_df)","argument_list":"","return_statement":"return Series(lst_new,index=language_df.index)","docstring":"Converts the long text in the Education 'value' column to shorter text to be used as JSON keys.\n\n\tArguments:\n\t\tlanguage_df {[Series]} -- [A pandas series containing the 'value' column from the 'Education' sheet ]\n\n\tReturns:\n\t\t[Series] -- [A pandas Series with shortened text and no punctuation.]","docstring_summary":"Converts the long text in the Education 'value' column to shorter text to be used as JSON keys.","docstring_tokens":["Converts","the","long","text","in","the","Education","value","column","to","shorter","text","to","be","used","as","JSON","keys","."],"function":"def education_value_cleaner(language_df):\n\t\"\"\" Converts the long text in the Education 'value' column to shorter text to be used as JSON keys.\n\n\tArguments:\n\t\tlanguage_df {[Series]} -- [A pandas series containing the 'value' column from the 'Education' sheet ]\n\n\tReturns:\n\t\t[Series] -- [A pandas Series with shortened text and no punctuation.]\n\t\"\"\"\n\tlst = [word_tokenize(x) for x in language_df.value.tolist()]\n\t#http:\/\/www.nltk.org\/book_1ed\/ch05.html\n\tpos_tagged = [pos_tag(x) for x in lst]\n\tlst_new=[]\n\tfor pt in pos_tagged:\n\t\t#choose nouns in sentence\n\t\tnouns = [depunctuate(x[0]) for x in pt if \"NN\" in x[1]]\n\t\t#choose verbs in setence\n\t\tverbs = [depunctuate(x[0]) for x in pt if 'VB' in x[1]]\n\t\t#make fieldKey and add to new list of fieldKeys\n\t\tif len(verbs)==0 and len(nouns)==2:\n\t\t\tlst_new.append(nouns[0].lower() + nouns[1].title())\n\t\telif len(verbs)==1 and len(nouns)==1:\n\t\t\tlst_new.append(nouns[0].lower() + verbs[0].title())\n\t\telse:\n\t\t\tlst_new.append(nouns[0].lower() + nouns[1].title() + verbs[0].title())\n\treturn Series(lst_new,index=language_df.index)","function_tokens":["def","education_value_cleaner","(","language_df",")",":","lst","=","[","word_tokenize","(","x",")","for","x","in","language_df",".","value",".","tolist","(",")","]","#http:\/\/www.nltk.org\/book_1ed\/ch05.html","pos_tagged","=","[","pos_tag","(","x",")","for","x","in","lst","]","lst_new","=","[","]","for","pt","in","pos_tagged",":","#choose nouns in sentence","nouns","=","[","depunctuate","(","x","[","0","]",")","for","x","in","pt","if","\"NN\"","in","x","[","1","]","]","#choose verbs in setence","verbs","=","[","depunctuate","(","x","[","0","]",")","for","x","in","pt","if","'VB'","in","x","[","1","]","]","#make fieldKey and add to new list of fieldKeys","if","len","(","verbs",")","==","0","and","len","(","nouns",")","==","2",":","lst_new",".","append","(","nouns","[","0","]",".","lower","(",")","+","nouns","[","1","]",".","title","(",")",")","elif","len","(","verbs",")","==","1","and","len","(","nouns",")","==","1",":","lst_new",".","append","(","nouns","[","0","]",".","lower","(",")","+","verbs","[","0","]",".","title","(",")",")","else",":","lst_new",".","append","(","nouns","[","0","]",".","lower","(",")","+","nouns","[","1","]",".","title","(",")","+","verbs","[","0","]",".","title","(",")",")","return","Series","(","lst_new",",","index","=","language_df",".","index",")"],"url":"https:\/\/github.com\/COVID-19-electronic-health-system\/Corona-tracker\/blob\/80cab55a7a03c43fa4a3412daa6e4ff1f0a45d8c\/src\/python\/pull_gsheets_translations_mvp.py#L82-L107"}
4
+ {"nwo":"COVID-19-electronic-health-system\/Corona-tracker","sha":"80cab55a7a03c43fa4a3412daa6e4ff1f0a45d8c","path":"src\/python\/pull_gsheets_translations_mvp.py","language":"python","identifier":"survey_value_cleaner","parameters":"(language_df)","argument_list":"","return_statement":"return DataFrame(rows_added,columns=language_df.columns)","docstring":"Converts the long text found within the 'Survey' sheets to shorter text to be used as JSON keys.\n\n\tArguments:\n\t\tlanguage_df {[DataFrame]} -- [A pandas DataFrame containing the information from the 'Survey' sheet.]\n\n\tReturns:\n\t\t[DataFrame] -- [Returns a new DataFrame with shortended text and no punctuation.]","docstring_summary":"Converts the long text found within the 'Survey' sheets to shorter text to be used as JSON keys.","docstring_tokens":["Converts","the","long","text","found","within","the","Survey","sheets","to","shorter","text","to","be","used","as","JSON","keys","."],"function":"def survey_value_cleaner(language_df):\n\t\"\"\" Converts the long text found within the 'Survey' sheets to shorter text to be used as JSON keys.\n\n\tArguments:\n\t\tlanguage_df {[DataFrame]} -- [A pandas DataFrame containing the information from the 'Survey' sheet.]\n\n\tReturns:\n\t\t[DataFrame] -- [Returns a new DataFrame with shortended text and no punctuation.]\n\t\"\"\"\n\tvPA_col = [i for i,x in enumerate(language_df.columns) if x=='valuePossibleAnswers'][0]\n\ttVPA_col = [i for i,x in enumerate(language_df.columns) if x=='translatedValuePossibleAnswers'][0]\n\tv_col = [i for i,x in enumerate(language_df.columns) if x=='value'][0]\n\ttV_col = [i for i,x in enumerate(language_df.columns) if x=='translatedValue'][0]\n\trows = language_df.values.tolist()\n\trows_added = []\n\tfor i,row in enumerate(rows):\n\t\torig_row = row.copy()\n\t\torig_row[v_col] = convert_to_camelCase(orig_row[v_col])\n\t\trows_added.append(orig_row)\n\t\tarr = row[vPA_col].split(';')\n\t\ttarr = row[tVPA_col].split(';')\n\t\tif len(arr)==len(tarr) and len(arr)>3:\n\t\t\tfor j,_ in enumerate(arr):\n\t\t\t\trow_new = row.copy()\n\t\t\t\trow_new[v_col] = arr[j].replace('\\n','')\n\t\t\t\trow_new[v_col] = convert_to_camelCase(row_new[v_col]).replace(\" \",\"\")\n\t\t\t\t#.replace(' ','').translate(str.maketrans('', '', punctuation))\n\t\t\t\trow_new[tV_col] = tarr[j].replace('\\n','')\n\t\t\t\t#.replace(' ','').translate(str.maketrans('', '', punctuation))\n\t\t\t\trows_added.append(row_new)\n\treturn DataFrame(rows_added,columns=language_df.columns)","function_tokens":["def","survey_value_cleaner","(","language_df",")",":","vPA_col","=","[","i","for","i",",","x","in","enumerate","(","language_df",".","columns",")","if","x","==","'valuePossibleAnswers'","]","[","0","]","tVPA_col","=","[","i","for","i",",","x","in","enumerate","(","language_df",".","columns",")","if","x","==","'translatedValuePossibleAnswers'","]","[","0","]","v_col","=","[","i","for","i",",","x","in","enumerate","(","language_df",".","columns",")","if","x","==","'value'","]","[","0","]","tV_col","=","[","i","for","i",",","x","in","enumerate","(","language_df",".","columns",")","if","x","==","'translatedValue'","]","[","0","]","rows","=","language_df",".","values",".","tolist","(",")","rows_added","=","[","]","for","i",",","row","in","enumerate","(","rows",")",":","orig_row","=","row",".","copy","(",")","orig_row","[","v_col","]","=","convert_to_camelCase","(","orig_row","[","v_col","]",")","rows_added",".","append","(","orig_row",")","arr","=","row","[","vPA_col","]",".","split","(","';'",")","tarr","=","row","[","tVPA_col","]",".","split","(","';'",")","if","len","(","arr",")","==","len","(","tarr",")","and","len","(","arr",")",">","3",":","for","j",",","_","in","enumerate","(","arr",")",":","row_new","=","row",".","copy","(",")","row_new","[","v_col","]","=","arr","[","j","]",".","replace","(","'\\n'",",","''",")","row_new","[","v_col","]","=","convert_to_camelCase","(","row_new","[","v_col","]",")",".","replace","(","\" \"",",","\"\"",")","#.replace(' ','').translate(str.maketrans('', '', punctuation))","row_new","[","tV_col","]","=","tarr","[","j","]",".","replace","(","'\\n'",",","''",")","#.replace(' ','').translate(str.maketrans('', '', punctuation))","rows_added",".","append","(","row_new",")","return","DataFrame","(","rows_added",",","columns","=","language_df",".","columns",")"],"url":"https:\/\/github.com\/COVID-19-electronic-health-system\/Corona-tracker\/blob\/80cab55a7a03c43fa4a3412daa6e4ff1f0a45d8c\/src\/python\/pull_gsheets_translations_mvp.py#L109-L139"}
5
+ {"nwo":"COVID-19-electronic-health-system\/Corona-tracker","sha":"80cab55a7a03c43fa4a3412daa6e4ff1f0a45d8c","path":"src\/python\/pull_gsheets_translations_mvp.py","language":"python","identifier":"convert_worksheet_to_df","parameters":"(wk)","argument_list":"","return_statement":"return language_df","docstring":"Converts current worksheet into a pandas dataframe.\n\n\tArguments:\n\t\twk {[worksheet object]} -- [Current language worksheet being iterated over.]\n\n\tReturns:\n\t\t[DataFrame] -- [A pandas dataframe containing the information from the current worksheet with a cleaned 'parentKey' column.]","docstring_summary":"Converts current worksheet into a pandas dataframe.","docstring_tokens":["Converts","current","worksheet","into","a","pandas","dataframe","."],"function":"def convert_worksheet_to_df(wk):\n\t\"\"\"Converts current worksheet into a pandas dataframe.\n\n\tArguments:\n\t\twk {[worksheet object]} -- [Current language worksheet being iterated over.]\n\n\tReturns:\n\t\t[DataFrame] -- [A pandas dataframe containing the information from the current worksheet with a cleaned 'parentKey' column.]\n\t\"\"\"\n\tlanguage_lists = wk.get_all_values()\n\tlanguage_df = DataFrame(language_lists[1:],columns=language_lists[0])\n\tlanguage_df = language_df[language_df['parentKey']!='']\n\treturn language_df","function_tokens":["def","convert_worksheet_to_df","(","wk",")",":","language_lists","=","wk",".","get_all_values","(",")","language_df","=","DataFrame","(","language_lists","[","1",":","]",",","columns","=","language_lists","[","0","]",")","language_df","=","language_df","[","language_df","[","'parentKey'","]","!=","''","]","return","language_df"],"url":"https:\/\/github.com\/COVID-19-electronic-health-system\/Corona-tracker\/blob\/80cab55a7a03c43fa4a3412daa6e4ff1f0a45d8c\/src\/python\/pull_gsheets_translations_mvp.py#L141-L153"}
6
+ {"nwo":"COVID-19-electronic-health-system\/Corona-tracker","sha":"80cab55a7a03c43fa4a3412daa6e4ff1f0a45d8c","path":"src\/python\/pull_gsheets_translations_mvp.py","language":"python","identifier":"clean_dataframe_column_values_to_short_JSON_keys","parameters":"(wk,df)","argument_list":"","return_statement":"return df[['parentKey','fieldKey','childKey','value','translatedValue']]","docstring":"Cleans the current language dataframe columns into short JSON keys, depending on the type of worksheet.\n\n\tArguments:\n\t\twk {[worksheet object]} -- [Current worksheet being iterated over.]\n\t\tdf {[DataFrame]} -- [The current language dataframe.]\n\n\tReturns:\n\t\t[DataFrame] -- [A cleaned dataframe with the necessary columns for the JSON key:value pairs.]","docstring_summary":"Cleans the current language dataframe columns into short JSON keys, depending on the type of worksheet.","docstring_tokens":["Cleans","the","current","language","dataframe","columns","into","short","JSON","keys","depending","on","the","type","of","worksheet","."],"function":"def clean_dataframe_column_values_to_short_JSON_keys(wk,df):\n\t\"\"\" Cleans the current language dataframe columns into short JSON keys, depending on the type of worksheet.\n\n\tArguments:\n\t\twk {[worksheet object]} -- [Current worksheet being iterated over.]\n\t\tdf {[DataFrame]} -- [The current language dataframe.]\n\n\tReturns:\n\t\t[DataFrame] -- [A cleaned dataframe with the necessary columns for the JSON key:value pairs.]\n\t\"\"\"\n\tif 'Education' in wk.title:\n\t\tdf.value = education_value_cleaner(df)\n\telif 'Survey' in wk.title:\n\t\tosLanguage_df = df\n\t\tdf = survey_value_cleaner(df)\n\telse:\n\t\tdf['value'] = df['value'].apply(convert_to_camelCase)\n\t\n\treturn df[['parentKey','fieldKey','childKey','value','translatedValue']]","function_tokens":["def","clean_dataframe_column_values_to_short_JSON_keys","(","wk",",","df",")",":","if","'Education'","in","wk",".","title",":","df",".","value","=","education_value_cleaner","(","df",")","elif","'Survey'","in","wk",".","title",":","osLanguage_df","=","df","df","=","survey_value_cleaner","(","df",")","else",":","df","[","'value'","]","=","df","[","'value'","]",".","apply","(","convert_to_camelCase",")","return","df","[","[","'parentKey'",",","'fieldKey'",",","'childKey'",",","'value'",",","'translatedValue'","]","]"],"url":"https:\/\/github.com\/COVID-19-electronic-health-system\/Corona-tracker\/blob\/80cab55a7a03c43fa4a3412daa6e4ff1f0a45d8c\/src\/python\/pull_gsheets_translations_mvp.py#L155-L173"}
7
+ {"nwo":"COVID-19-electronic-health-system\/Corona-tracker","sha":"80cab55a7a03c43fa4a3412daa6e4ff1f0a45d8c","path":"src\/python\/pull_gsheets_translations_mvp.py","language":"python","identifier":"save_to_JSON","parameters":"(out_dir,locale,working_dict)","argument_list":"","return_statement":"","docstring":"Converts working_dict into JSON and saves it into \/out_dir\/locale\/.\n\n\tArguments:\n\t\tout_dir {[string]} -- [Path to save all translations]\n\t\tlocale {[string]} -- [Two letter abbreviation of the language.]\n\t\tworking_dict {[dict]} -- [The language dataframe converted to the following format:\n\t\t\t\t{\n\t\t\t\t\t\"parentKey\":{\n\t\t\t\t\t\t\"childKey\":{\n\t\t\t\t\t\t\t'fieldKey':{'value':'translatedValue','array':['translatedValue']},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t]","docstring_summary":"Converts working_dict into JSON and saves it into \/out_dir\/locale\/.","docstring_tokens":["Converts","working_dict","into","JSON","and","saves","it","into","\/","out_dir","\/","locale","\/","."],"function":"def save_to_JSON(out_dir,locale,working_dict):\n\t\"\"\" Converts working_dict into JSON and saves it into \/out_dir\/locale\/.\n\n\tArguments:\n\t\tout_dir {[string]} -- [Path to save all translations]\n\t\tlocale {[string]} -- [Two letter abbreviation of the language.]\n\t\tworking_dict {[dict]} -- [The language dataframe converted to the following format:\n\t\t\t\t{\n\t\t\t\t\t\"parentKey\":{\n\t\t\t\t\t\t\"childKey\":{\n\t\t\t\t\t\t\t'fieldKey':{'value':'translatedValue','array':['translatedValue']},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t]\n\t\"\"\"\n\tif not path.exists(out_dir+locale):\n\t\tmkdir(out_dir+locale)\n\twith open(out_dir+locale+'\/translation.json', 'w') as f:\n\t\tdump(working_dict, f)","function_tokens":["def","save_to_JSON","(","out_dir",",","locale",",","working_dict",")",":","if","not","path",".","exists","(","out_dir","+","locale",")",":","mkdir","(","out_dir","+","locale",")","with","open","(","out_dir","+","locale","+","'\/translation.json'",",","'w'",")","as","f",":","dump","(","working_dict",",","f",")"],"url":"https:\/\/github.com\/COVID-19-electronic-health-system\/Corona-tracker\/blob\/80cab55a7a03c43fa4a3412daa6e4ff1f0a45d8c\/src\/python\/pull_gsheets_translations_mvp.py#L175-L194"}
8
+ {"nwo":"COVID-19-electronic-health-system\/Corona-tracker","sha":"80cab55a7a03c43fa4a3412daa6e4ff1f0a45d8c","path":"src\/python\/pull_gsheets_translations_mvp.py","language":"python","identifier":"connect_to_gsheets_API","parameters":"(credentials_path,scope)","argument_list":"","return_statement":"return authorize(credentials)","docstring":"Connects to google sheets API using a credentials JSON.\n\n\tArguments:\n\t\tcredentials_path {[string]} -- [Path to your credentials.json file for the google sheets API]\n\t\tscope {[list]} -- [List of strings to determine the data you access from google sheets API]\n\n\tReturns:\n\t\t[class] -- [client_class instance that allows an authorized user to access google sheets]","docstring_summary":"Connects to google sheets API using a credentials JSON.","docstring_tokens":["Connects","to","google","sheets","API","using","a","credentials","JSON","."],"function":"def connect_to_gsheets_API(credentials_path,scope):\n\t\"\"\" Connects to google sheets API using a credentials JSON.\n\n\tArguments:\n\t\tcredentials_path {[string]} -- [Path to your credentials.json file for the google sheets API]\n\t\tscope {[list]} -- [List of strings to determine the data you access from google sheets API]\n\n\tReturns:\n\t\t[class] -- [client_class instance that allows an authorized user to access google sheets]\n\t\"\"\"\n\tcredentials = Credentials.from_service_account_file(credentials_path, scopes=scope)\n\treturn authorize(credentials)","function_tokens":["def","connect_to_gsheets_API","(","credentials_path",",","scope",")",":","credentials","=","Credentials",".","from_service_account_file","(","credentials_path",",","scopes","=","scope",")","return","authorize","(","credentials",")"],"url":"https:\/\/github.com\/COVID-19-electronic-health-system\/Corona-tracker\/blob\/80cab55a7a03c43fa4a3412daa6e4ff1f0a45d8c\/src\/python\/pull_gsheets_translations_mvp.py#L196-L207"}
9
+ {"nwo":"COVID-19-electronic-health-system\/Corona-tracker","sha":"80cab55a7a03c43fa4a3412daa6e4ff1f0a45d8c","path":"src\/python\/pull_gsheets_translations_mvp.py","language":"python","identifier":"list_all_spreadsheets_name","parameters":"(gc)","argument_list":"","return_statement":"return [x['name'] for x in list_all_spreadsheets]","docstring":"Creates a list of all the spreadsheet found in the authorized google account.\n\n\tArguments:\n\t\tgc {[class]} -- [Authorized client_class instance]\n\n\tReturns:\n\t\t[list] -- [Names of all spreadsheets found in the Translations folder in google drive.]","docstring_summary":"Creates a list of all the spreadsheet found in the authorized google account.","docstring_tokens":["Creates","a","list","of","all","the","spreadsheet","found","in","the","authorized","google","account","."],"function":"def list_all_spreadsheets_name(gc):\n\t\"\"\" Creates a list of all the spreadsheet found in the authorized google account.\n\n\tArguments:\n\t\tgc {[class]} -- [Authorized client_class instance]\n\n\tReturns:\n\t\t[list] -- [Names of all spreadsheets found in the Translations folder in google drive.]\n\t\"\"\"\n\tlist_all_spreadsheets = gc.list_spreadsheet_files()\n\treturn [x['name'] for x in list_all_spreadsheets]","function_tokens":["def","list_all_spreadsheets_name","(","gc",")",":","list_all_spreadsheets","=","gc",".","list_spreadsheet_files","(",")","return","[","x","[","'name'","]","for","x","in","list_all_spreadsheets","]"],"url":"https:\/\/github.com\/COVID-19-electronic-health-system\/Corona-tracker\/blob\/80cab55a7a03c43fa4a3412daa6e4ff1f0a45d8c\/src\/python\/pull_gsheets_translations_mvp.py#L209-L219"}
10
+ {"nwo":"COVID-19-electronic-health-system\/Corona-tracker","sha":"80cab55a7a03c43fa4a3412daa6e4ff1f0a45d8c","path":"src\/python\/pull_gsheets_translations_mvp.py","language":"python","identifier":"filter_old_translation_sheets","parameters":"(spreadsheet_names,current_translation_regex,old_translation_regex,languages_to_translate)","argument_list":"","return_statement":"return [x for x in translation_sheet_names for y in languages_to_translate if y in x]","docstring":"Removes the old translation sheets from the data model.\n\n\tArguments:\n\t\tspreadsheet_names {[list]} -- [List of the spreadsheet names found in the Translation folder.]\n\t\tcurrent_translation_regex {[string]} -- [String to filter out the sheets to be converted to JSON.]\n\t\told_translation_regex {[string]} -- [String to filter out the translation sheets not used in data model.]\n\t\tlanguages_to_translate {[list]} -- [List of lanaguages to translate.]\n\n\tReturns:\n\t\t[list] -- [list of spreadsheets to use for the data model.]","docstring_summary":"Removes the old translation sheets from the data model.","docstring_tokens":["Removes","the","old","translation","sheets","from","the","data","model","."],"function":"def filter_old_translation_sheets(spreadsheet_names,current_translation_regex,old_translation_regex,languages_to_translate):\n\t\"\"\" Removes the old translation sheets from the data model.\n\n\tArguments:\n\t\tspreadsheet_names {[list]} -- [List of the spreadsheet names found in the Translation folder.]\n\t\tcurrent_translation_regex {[string]} -- [String to filter out the sheets to be converted to JSON.]\n\t\told_translation_regex {[string]} -- [String to filter out the translation sheets not used in data model.]\n\t\tlanguages_to_translate {[list]} -- [List of lanaguages to translate.]\n\n\tReturns:\n\t\t[list] -- [list of spreadsheets to use for the data model.]\n\t\"\"\"\n\ttranslation_sheet_names = [ x for x in spreadsheet_names if (current_translation_regex in x) & (old_translation_regex not in x)]\n\treturn [x for x in translation_sheet_names for y in languages_to_translate if y in x]","function_tokens":["def","filter_old_translation_sheets","(","spreadsheet_names",",","current_translation_regex",",","old_translation_regex",",","languages_to_translate",")",":","translation_sheet_names","=","[","x","for","x","in","spreadsheet_names","if","(","current_translation_regex","in","x",")","&","(","old_translation_regex","not","in","x",")","]","return","[","x","for","x","in","translation_sheet_names","for","y","in","languages_to_translate","if","y","in","x","]"],"url":"https:\/\/github.com\/COVID-19-electronic-health-system\/Corona-tracker\/blob\/80cab55a7a03c43fa4a3412daa6e4ff1f0a45d8c\/src\/python\/pull_gsheets_translations_mvp.py#L221-L234"}
CaliOpen__Caliopen.jsonl ADDED
The diff for this file is too large to render. See raw diff
CanonicalLtd__react-native.jsonl ADDED
@@ -0,0 +1,2 @@
 
 
1
+ {"nwo":"CanonicalLtd\/react-native","sha":"98e0ce38cdcb8c489a064c436a353be754e95f89","path":"JSCLegacyProfiler\/smap.py","language":"python","identifier":"_parse_vlq","parameters":"(segment)","argument_list":"","return_statement":"return values","docstring":"Parse a string of VLQ-encoded data.\n\n Returns:\n a list of integers.","docstring_summary":"Parse a string of VLQ-encoded data.","docstring_tokens":["Parse","a","string","of","VLQ","-","encoded","data","."],"function":"def _parse_vlq(segment):\n \"\"\"Parse a string of VLQ-encoded data.\n\n Returns:\n a list of integers.\n \"\"\"\n\n values = []\n\n cur, shift = 0, 0\n for c in segment:\n val = B64[c]\n # Each character is 6 bits:\n # 5 of value and the high bit is the continuation.\n val, cont = val & 0b11111, val >> 5\n cur += val << shift\n shift += 5\n\n if not cont:\n # The low bit of the unpacked value is the sign.\n cur, sign = cur >> 1, cur & 1\n if sign:\n cur = -cur\n values.append(cur)\n cur, shift = 0, 0\n\n if cur or shift:\n raise Exception('leftover cur\/shift in vlq decode')\n\n return values","function_tokens":["def","_parse_vlq","(","segment",")",":","values","=","[","]","cur",",","shift","=","0",",","0","for","c","in","segment",":","val","=","B64","[","c","]","# Each character is 6 bits:","# 5 of value and the high bit is the continuation.","val",",","cont","=","val","&","0b11111",",","val",">>","5","cur","+=","val","<<","shift","shift","+=","5","if","not","cont",":","# The low bit of the unpacked value is the sign.","cur",",","sign","=","cur",">>","1",",","cur","&","1","if","sign",":","cur","=","-","cur","values",".","append","(","cur",")","cur",",","shift","=","0",",","0","if","cur","or","shift",":","raise","Exception","(","'leftover cur\/shift in vlq decode'",")","return","values"],"url":"https:\/\/github.com\/CanonicalLtd\/react-native\/blob\/98e0ce38cdcb8c489a064c436a353be754e95f89\/JSCLegacyProfiler\/smap.py#L259-L288"}
2
+ {"nwo":"CanonicalLtd\/react-native","sha":"98e0ce38cdcb8c489a064c436a353be754e95f89","path":"JSCLegacyProfiler\/smap.py","language":"python","identifier":"_parse_smap","parameters":"(file)","argument_list":"","return_statement":"","docstring":"Given a file-like object, yield SmapState()s as they are read from it.","docstring_summary":"Given a file-like object, yield SmapState()s as they are read from it.","docstring_tokens":["Given","a","file","-","like","object","yield","SmapState","()","s","as","they","are","read","from","it","."],"function":"def _parse_smap(file):\n \"\"\"Given a file-like object, yield SmapState()s as they are read from it.\"\"\"\n\n smap = json.load(file)\n sources = smap['sources']\n names = smap['names']\n mappings = smap['mappings']\n lines = mappings.split(';')\n\n dst_col, src_id, src_line, src_col, name_id = 0, 0, 0, 0, 0\n for dst_line, line in enumerate(lines):\n segments = line.split(',')\n dst_col = 0\n for segment in segments:\n if not segment:\n continue\n parsed = _parse_vlq(segment)\n dst_col += parsed[0]\n\n src = None\n name = None\n if len(parsed) > 1:\n src_id += parsed[1]\n src = sources[src_id]\n src_line += parsed[2]\n src_col += parsed[3]\n\n if len(parsed) > 4:\n name_id += parsed[4]\n name = names[name_id]\n\n assert dst_line >= 0\n assert dst_col >= 0\n assert src_line >= 0\n assert src_col >= 0\n\n yield SmapState(dst_line, dst_col, src, src_line, src_col, name)","function_tokens":["def","_parse_smap","(","file",")",":","smap","=","json",".","load","(","file",")","sources","=","smap","[","'sources'","]","names","=","smap","[","'names'","]","mappings","=","smap","[","'mappings'","]","lines","=","mappings",".","split","(","';'",")","dst_col",",","src_id",",","src_line",",","src_col",",","name_id","=","0",",","0",",","0",",","0",",","0","for","dst_line",",","line","in","enumerate","(","lines",")",":","segments","=","line",".","split","(","','",")","dst_col","=","0","for","segment","in","segments",":","if","not","segment",":","continue","parsed","=","_parse_vlq","(","segment",")","dst_col","+=","parsed","[","0","]","src","=","None","name","=","None","if","len","(","parsed",")",">","1",":","src_id","+=","parsed","[","1","]","src","=","sources","[","src_id","]","src_line","+=","parsed","[","2","]","src_col","+=","parsed","[","3","]","if","len","(","parsed",")",">","4",":","name_id","+=","parsed","[","4","]","name","=","names","[","name_id","]","assert","dst_line",">=","0","assert","dst_col",">=","0","assert","src_line",">=","0","assert","src_col",">=","0","yield","SmapState","(","dst_line",",","dst_col",",","src",",","src_line",",","src_col",",","name",")"],"url":"https:\/\/github.com\/CanonicalLtd\/react-native\/blob\/98e0ce38cdcb8c489a064c436a353be754e95f89\/JSCLegacyProfiler\/smap.py#L291-L327"}
CartoDB__cartodb.jsonl ADDED
@@ -0,0 +1,2 @@
 
 
1
+ {"nwo":"CartoDB\/cartodb","sha":"46b91228a01123976363f55a5e1d712a600785a6","path":"lib\/importer\/misc\/dbfUtils.py","language":"python","identifier":"dbfreader","parameters":"(f)","argument_list":"","return_statement":"","docstring":"Returns an iterator over records in a Xbase DBF file.\n\n The first row returned contains the field names.\n The second row contains field specs: (type, size, decimal places).\n Subsequent rows contain the data records.\n If a record is marked as deleted, it is skipped.\n\n File should be opened for binary reads.","docstring_summary":"Returns an iterator over records in a Xbase DBF file.","docstring_tokens":["Returns","an","iterator","over","records","in","a","Xbase","DBF","file","."],"function":"def dbfreader(f):\n \"\"\"Returns an iterator over records in a Xbase DBF file.\n\n The first row returned contains the field names.\n The second row contains field specs: (type, size, decimal places).\n Subsequent rows contain the data records.\n If a record is marked as deleted, it is skipped.\n\n File should be opened for binary reads.\n\n \"\"\"\n # See DBF format spec at:\n # http:\/\/www.pgts.com.au\/download\/public\/xbase.htm#DBF_STRUCT\n\n numrec, lenheader = struct.unpack('<xxxxLH22x', f.read(32)) \n numfields = (lenheader - 33) \/\/ 32\n\n fields = []\n for fieldno in range(numfields):\n name, typ, size, deci = struct.unpack('<11sc4xBB14x', f.read(32))\n name = name.replace('\\0', '') # eliminate NULs from string \n fields.append((name, typ, size, deci))\n yield [field[0] for field in fields]\n yield [tuple(field[1:]) for field in fields]\n\n terminator = f.read(1)\n assert terminator == '\\r'\n\n fields.insert(0, ('DeletionFlag', 'C', 1, 0))\n fmt = ''.join(['%ds' % fieldinfo[2] for fieldinfo in fields])\n fmtsiz = struct.calcsize(fmt)\n for i in range(numrec):\n record = struct.unpack(fmt, f.read(fmtsiz))\n if record[0] != ' ':\n continue # deleted record\n result = []\n for (name, typ, size, deci), value in zip(fields, record):\n if name == 'DeletionFlag':\n continue\n if typ == \"N\":\n value = value.replace('\\0', '').lstrip()\n if value == '':\n value = 0\n elif deci:\n try:\n value = decimal.Decimal(value)\n except decimal.InvalidOperation:\n # Could be '************************' (for NULL)\n value = 0\n else:\n value = value\n elif typ == 'D':\n y, m, d = int(value[:4]), int(value[4:6]), int(value[6:8])\n try:\n value = datetime.date(y, m, d)\n except ValueError:\n # Could be '00000000' (for NULL)\n value = 0\n elif typ == 'L':\n value = (value in 'YyTt' and 'T') or (value in 'NnFf' and 'F') or '?'\n result.append(value)\n yield result","function_tokens":["def","dbfreader","(","f",")",":","# See DBF format spec at:","# http:\/\/www.pgts.com.au\/download\/public\/xbase.htm#DBF_STRUCT","numrec",",","lenheader","=","struct",".","unpack","(","'<xxxxLH22x'",",","f",".","read","(","32",")",")","numfields","=","(","lenheader","-","33",")","\/\/","32","fields","=","[","]","for","fieldno","in","range","(","numfields",")",":","name",",","typ",",","size",",","deci","=","struct",".","unpack","(","'<11sc4xBB14x'",",","f",".","read","(","32",")",")","name","=","name",".","replace","(","'\\0'",",","''",")","# eliminate NULs from string ","fields",".","append","(","(","name",",","typ",",","size",",","deci",")",")","yield","[","field","[","0","]","for","field","in","fields","]","yield","[","tuple","(","field","[","1",":","]",")","for","field","in","fields","]","terminator","=","f",".","read","(","1",")","assert","terminator","==","'\\r'","fields",".","insert","(","0",",","(","'DeletionFlag'",",","'C'",",","1",",","0",")",")","fmt","=","''",".","join","(","[","'%ds'","%","fieldinfo","[","2","]","for","fieldinfo","in","fields","]",")","fmtsiz","=","struct",".","calcsize","(","fmt",")","for","i","in","range","(","numrec",")",":","record","=","struct",".","unpack","(","fmt",",","f",".","read","(","fmtsiz",")",")","if","record","[","0","]","!=","' '",":","continue","# deleted record","result","=","[","]","for","(","name",",","typ",",","size",",","deci",")",",","value","in","zip","(","fields",",","record",")",":","if","name","==","'DeletionFlag'",":","continue","if","typ","==","\"N\"",":","value","=","value",".","replace","(","'\\0'",",","''",")",".","lstrip","(",")","if","value","==","''",":","value","=","0","elif","deci",":","try",":","value","=","decimal",".","Decimal","(","value",")","except","decimal",".","InvalidOperation",":","# Could be '************************' (for NULL)","value","=","0","else",":","value","=","value","elif","typ","==","'D'",":","y",",","m",",","d","=","int","(","value","[",":","4","]",")",",","int","(","value","[","4",":","6","]",")",",","int","(","value","[","6",":","8","]",")","try",":","value","=","datetime",".","date","(","y",",","m",",","d",")","except","ValueError",":","# Could be '00000000' (for NULL)","value","=","0","elif","typ","==","'L'",":","value","=","(","value","in","'YyTt'","and","'T'",")","or","(","value","in","'NnFf'","and","'F'",")","or","'?'","result",".","append","(","value",")","yield","result"],"url":"https:\/\/github.com\/CartoDB\/cartodb\/blob\/46b91228a01123976363f55a5e1d712a600785a6\/lib\/importer\/misc\/dbfUtils.py#L3-L64"}
2
+ {"nwo":"CartoDB\/cartodb","sha":"46b91228a01123976363f55a5e1d712a600785a6","path":"lib\/importer\/misc\/dbfUtils.py","language":"python","identifier":"dbfwriter","parameters":"(f, fieldnames, fieldspecs, records)","argument_list":"","return_statement":"","docstring":"Return a string suitable for writing directly to a binary dbf file.\n\n File f should be open for writing in a binary mode.\n\n Fieldnames should be no longer than ten characters and not include \\x00.\n Fieldspecs are in the form (type, size, deci) where\n type is one of:\n C for ascii character data\n M for ascii character memo data (real memo fields not supported)\n D for datetime objects\n N for ints or decimal objects\n L for logical values 'T', 'F', or '?'\n size is the field width\n deci is the number of decimal places in the provided decimal object\n Records can be an iterable over the records (sequences of field values).","docstring_summary":"Return a string suitable for writing directly to a binary dbf file.","docstring_tokens":["Return","a","string","suitable","for","writing","directly","to","a","binary","dbf","file","."],"function":"def dbfwriter(f, fieldnames, fieldspecs, records):\n \"\"\" Return a string suitable for writing directly to a binary dbf file.\n\n File f should be open for writing in a binary mode.\n\n Fieldnames should be no longer than ten characters and not include \\x00.\n Fieldspecs are in the form (type, size, deci) where\n type is one of:\n C for ascii character data\n M for ascii character memo data (real memo fields not supported)\n D for datetime objects\n N for ints or decimal objects\n L for logical values 'T', 'F', or '?'\n size is the field width\n deci is the number of decimal places in the provided decimal object\n Records can be an iterable over the records (sequences of field values).\n \n \"\"\"\n # header info\n ver = 3\n now = datetime.datetime.now()\n yr, mon, day = now.year-1900, now.month, now.day\n numrec = len(records)\n numfields = len(fieldspecs)\n lenheader = numfields * 32 + 33\n lenrecord = sum(field[1] for field in fieldspecs) + 1\n hdr = struct.pack('<BBBBLHH20x', ver, yr, mon, day, numrec, lenheader, lenrecord)\n f.write(hdr)\n \n # field specs\n for name, (typ, size, deci) in zip(fieldnames, fieldspecs):\n name = name.ljust(11, '\\x00')\n fld = struct.pack('<11sc4xBB14x', name, typ, size, deci)\n f.write(fld)\n\n # terminator\n f.write('\\r')\n\n # records\n for record in records:\n f.write(' ') # deletion flag\n for (typ, size, deci), value in zip(fieldspecs, record):\n if typ == \"N\":\n value = str(value).rjust(size, ' ')\n elif typ == 'D':\n value = value.strftime('%Y%m%d')\n elif typ == 'L':\n value = str(value)[0].upper()\n else:\n value = str(value)[:size].ljust(size, ' ')\n assert len(value) == size\n f.write(value)\n\n # End of file\n f.write('\\x1A')","function_tokens":["def","dbfwriter","(","f",",","fieldnames",",","fieldspecs",",","records",")",":","# header info","ver","=","3","now","=","datetime",".","datetime",".","now","(",")","yr",",","mon",",","day","=","now",".","year","-","1900",",","now",".","month",",","now",".","day","numrec","=","len","(","records",")","numfields","=","len","(","fieldspecs",")","lenheader","=","numfields","*","32","+","33","lenrecord","=","sum","(","field","[","1","]","for","field","in","fieldspecs",")","+","1","hdr","=","struct",".","pack","(","'<BBBBLHH20x'",",","ver",",","yr",",","mon",",","day",",","numrec",",","lenheader",",","lenrecord",")","f",".","write","(","hdr",")","# field specs","for","name",",","(","typ",",","size",",","deci",")","in","zip","(","fieldnames",",","fieldspecs",")",":","name","=","name",".","ljust","(","11",",","'\\x00'",")","fld","=","struct",".","pack","(","'<11sc4xBB14x'",",","name",",","typ",",","size",",","deci",")","f",".","write","(","fld",")","# terminator","f",".","write","(","'\\r'",")","# records","for","record","in","records",":","f",".","write","(","' '",")","# deletion flag","for","(","typ",",","size",",","deci",")",",","value","in","zip","(","fieldspecs",",","record",")",":","if","typ","==","\"N\"",":","value","=","str","(","value",")",".","rjust","(","size",",","' '",")","elif","typ","==","'D'",":","value","=","value",".","strftime","(","'%Y%m%d'",")","elif","typ","==","'L'",":","value","=","str","(","value",")","[","0","]",".","upper","(",")","else",":","value","=","str","(","value",")","[",":","size","]",".","ljust","(","size",",","' '",")","assert","len","(","value",")","==","size","f",".","write","(","value",")","# End of file","f",".","write","(","'\\x1A'",")"],"url":"https:\/\/github.com\/CartoDB\/cartodb\/blob\/46b91228a01123976363f55a5e1d712a600785a6\/lib\/importer\/misc\/dbfUtils.py#L67-L121"}
CermakM__jupyter-datatables.jsonl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
1
+ {"nwo":"CermakM\/jupyter-datatables","sha":"59b4880f926caaecb862477f3f1c2e7bbebb4939","path":"jupyter_datatables\/__init__.py","language":"python","identifier":"enable_datatables_mode","parameters":"()","argument_list":"","return_statement":"","docstring":"Enable Jupyter DataTables.","docstring_summary":"Enable Jupyter DataTables.","docstring_tokens":["Enable","Jupyter","DataTables","."],"function":"def enable_datatables_mode():\n \"\"\"Enable Jupyter DataTables.\"\"\"\n global _IS_ENABLED\n\n if not _IS_INITIALIZED:\n init_datatables_mode()\n else:\n pd.DataFrame._repr_javascript_ = __REPR__\n\n _IS_ENABLED = True","function_tokens":["def","enable_datatables_mode","(",")",":","global","_IS_ENABLED","if","not","_IS_INITIALIZED",":","init_datatables_mode","(",")","else",":","pd",".","DataFrame",".","_repr_javascript_","=","__REPR__","_IS_ENABLED","=","True"],"url":"https:\/\/github.com\/CermakM\/jupyter-datatables\/blob\/59b4880f926caaecb862477f3f1c2e7bbebb4939\/jupyter_datatables\/__init__.py#L62-L71"}
2
+ {"nwo":"CermakM\/jupyter-datatables","sha":"59b4880f926caaecb862477f3f1c2e7bbebb4939","path":"jupyter_datatables\/__init__.py","language":"python","identifier":"disable_datatables_mode","parameters":"()","argument_list":"","return_statement":"","docstring":"Disable Jupyter DataTables.","docstring_summary":"Disable Jupyter DataTables.","docstring_tokens":["Disable","Jupyter","DataTables","."],"function":"def disable_datatables_mode():\n \"\"\"Disable Jupyter DataTables.\"\"\"\n global _IS_ENABLED\n\n if _IS_INITIALIZED:\n del pd.DataFrame._repr_javascript_\n\n _IS_ENABLED = False","function_tokens":["def","disable_datatables_mode","(",")",":","global","_IS_ENABLED","if","_IS_INITIALIZED",":","del","pd",".","DataFrame",".","_repr_javascript_","_IS_ENABLED","=","False"],"url":"https:\/\/github.com\/CermakM\/jupyter-datatables\/blob\/59b4880f926caaecb862477f3f1c2e7bbebb4939\/jupyter_datatables\/__init__.py#L74-L81"}
3
+ {"nwo":"CermakM\/jupyter-datatables","sha":"59b4880f926caaecb862477f3f1c2e7bbebb4939","path":"jupyter_datatables\/__init__.py","language":"python","identifier":"init_datatables_mode","parameters":"(options: dict = None, classes: list = None)","argument_list":"","return_statement":"","docstring":"Initialize DataTable mode for pandas DataFrame representation.","docstring_summary":"Initialize DataTable mode for pandas DataFrame representation.","docstring_tokens":["Initialize","DataTable","mode","for","pandas","DataFrame","representation","."],"function":"def init_datatables_mode(options: dict = None, classes: list = None):\n \"\"\"Initialize DataTable mode for pandas DataFrame representation.\"\"\"\n global _IS_INITIALIZED\n global __REPR__\n\n if not _IS_ENABLED:\n raise Exception(\n \"Jupyter DataTables are disabled. Use `enable_datatables_mode()` instead.\")\n\n # extensions to be loaded\n extensions = config.defaults.extensions\n\n require(\"d3\", \"https:\/\/d3js.org\/d3.v5.min\")\n require(\"d3-array\", \"https:\/\/d3js.org\/d3-array.v2.min\")\n\n require.config(**{\n \"paths\": {\n \"moment\": \"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/moment.js\/2.8.0\/moment\",\n \"chartjs\": \"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/Chart.js\/2.8.0\/Chart\"\n },\n \"shim\": {\n \"chartjs\": {\n # enforce moment to be loaded before chartjs\n \"deps\": [\"moment\"]\n }\n },\n })\n\n # configure path to the datatables library using requireJS\n libs = OrderedDict(\n {\n # FIXME: minified version on prod\n \"datatables.net\": \"https:\/\/cdn.datatables.net\/1.10.18\/js\/jquery.dataTables\"\n }\n )\n shim = OrderedDict({\"datatables.net\": {\"exports\": \"$.fn.dataTable\"}})\n\n bundles = OrderedDict()\n\n if extensions.buttons:\n lib = \"datatables.net-buttons\"\n\n libs[lib] = \"https:\/\/cdn.datatables.net\/buttons\/1.5.6\/js\/dataTables.buttons.min\"\n shim[lib] = {\"deps\": [\"datatables.net\"]}\n\n # required to export Excel file, must be loaded first\n libs[\"jszip\"] = \"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/jszip\/2.5.0\/jszip.min\"\n\n bundles[lib] = {\n \"buttons.colvis\": \"https:\/\/cdn.datatables.net\/buttons\/1.5.6\/js\/buttons.colVis.min\",\n \"buttons.flash\": \"https:\/\/cdn.datatables.net\/buttons\/1.5.6\/js\/buttons.flash.min\",\n \"buttons.html5\": \"https:\/\/cdn.datatables.net\/buttons\/1.5.6\/js\/buttons.html5.min\",\n \"buttons.print\": \"https:\/\/cdn.datatables.net\/buttons\/1.5.6\/js\/buttons.print.min\",\n }\n for bundle, path in bundles[lib].items():\n libs[bundle] = path\n shim[bundle] = {\"deps\": [\"jszip\", lib]}\n\n # requirements for correct Buttons functionality\n libs[\n \"pdfmake\"\n ] = \"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/pdfmake\/0.1.36\/pdfmake.min\"\n shim[\"pdfmake\"] = {\"deps\": [\"datatables.net\"]}\n libs[\n \"vfsfonts\"\n ] = \"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/pdfmake\/0.1.36\/vfs_fonts\"\n shim[\"vfsfonts\"] = {\"deps\": [\"datatables.net\"]}\n\n if extensions.responsive:\n libs[\"datatables.responsive\"] = (\n \"https:\/\/cdn.datatables.net\/\" \"responsive\/2.2.2\/js\/dataTables.responsive.min\"\n ) # Responsive\n\n if extensions.scroller:\n libs[\"datatables.scroller\"] = (\n \"https:\/\/cdn.datatables.net\/\" \"scroller\/2.0.0\/js\/dataTables.scroller.min\"\n ) # Scroll\n\n if extensions.select:\n libs[\"datatables.select\"] = (\n \"https:\/\/cdn.datatables.net\/\" \"select\/1.3.0\/js\/dataTables.select.min\"\n ) # Select\n\n require.config(paths=libs, shim=shim)\n\n # link stylesheets\n link_css(\n \"https:\/\/cdn.datatables.net\/v\/dt\/\"\n \"dt-1.10.18\/\" # DataTables\n \"af-2.3.3\/\" # AutoFill\n \"b-1.5.6\/\" # Buttons\n \"b-colvis-1.5.6\/\" # Buttons - Column Visibility\n \"b-flash-1.5.6\/\" # Buttons - Flash\n \"b-html5-1.5.6\/\" # Buttons - HTML5\n \"b-print-1.5.6\/\" # Buttons - Print View\n \"cr-1.5.0\/\" # ColReorder\n \"fc-3.2.5\/\" # FixedColumns\n \"fh-3.1.4\/\" # FixedHeader\n \"kt-2.5.0\/\" # KeyTable\n \"r-2.2.2\/\" # Responsive\n \"rg-1.1.0\/\" # RowGroup\n \"rr-1.2.4\/\" # RowReorder\n \"sc-2.0.0\/\" # Scroll\n \"sl-1.3.0\/\" # Select\n \"datatables.min.css\",\n {\"id\": \"datatables.min.css\"},\n )\n\n # load custom style\n load_css(\n Path(_HERE, \"css\/jupyter-datatables.css\").read_text(encoding=\"utf-8\"),\n {\"id\": \"jupyter-datatables-css\"},\n )\n\n load_js(\n Path(_HERE, \"js\/config.js\").read_text(encoding=\"utf-8\"),\n {\"id\": \"dt-config-js\"})\n\n load_js(\n Path(_HERE, \"js\/components.js\").read_text(encoding=\"utf-8\"),\n {\"id\": \"dt-components-js\"})\n\n load_js(\n Path(_HERE, \"js\/graph-objects.js\").read_text(encoding=\"utf-8\"),\n {\"id\": \"dt-graph-objects-js\"})\n\n load_js(\n Path(_HERE, \"js\/toolbar.js\").read_text(encoding=\"utf-8\"),\n {\"id\": \"dt-toolbar-js\"})\n\n load_js(\n Path(_HERE, \"js\/tooltips.js\").read_text(encoding=\"utf-8\"),\n {\"id\": \"dt-tooltips-js\"})\n\n load_js(\n Path(_HERE, \"js\/jupyter-datatables.js\").read_text(encoding=\"utf-8\"),\n {\"id\": \"jupyter-datatables-js\"})\n\n __REPR__ = partialmethod(\n _repr_datatable_, options=options, classes=classes\n )\n\n _IS_INITIALIZED = True\n\n pd.DataFrame._repr_javascript_ = __REPR__","function_tokens":["def","init_datatables_mode","(","options",":","dict","=","None",",","classes",":","list","=","None",")",":","global","_IS_INITIALIZED","global","__REPR__","if","not","_IS_ENABLED",":","raise","Exception","(","\"Jupyter DataTables are disabled. Use `enable_datatables_mode()` instead.\"",")","# extensions to be loaded","extensions","=","config",".","defaults",".","extensions","require","(","\"d3\"",",","\"https:\/\/d3js.org\/d3.v5.min\"",")","require","(","\"d3-array\"",",","\"https:\/\/d3js.org\/d3-array.v2.min\"",")","require",".","config","(","*","*","{","\"paths\"",":","{","\"moment\"",":","\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/moment.js\/2.8.0\/moment\"",",","\"chartjs\"",":","\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/Chart.js\/2.8.0\/Chart\"","}",",","\"shim\"",":","{","\"chartjs\"",":","{","# enforce moment to be loaded before chartjs","\"deps\"",":","[","\"moment\"","]","}","}",",","}",")","# configure path to the datatables library using requireJS","libs","=","OrderedDict","(","{","# FIXME: minified version on prod","\"datatables.net\"",":","\"https:\/\/cdn.datatables.net\/1.10.18\/js\/jquery.dataTables\"","}",")","shim","=","OrderedDict","(","{","\"datatables.net\"",":","{","\"exports\"",":","\"$.fn.dataTable\"","}","}",")","bundles","=","OrderedDict","(",")","if","extensions",".","buttons",":","lib","=","\"datatables.net-buttons\"","libs","[","lib","]","=","\"https:\/\/cdn.datatables.net\/buttons\/1.5.6\/js\/dataTables.buttons.min\"","shim","[","lib","]","=","{","\"deps\"",":","[","\"datatables.net\"","]","}","# required to export Excel file, must be loaded first","libs","[","\"jszip\"","]","=","\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/jszip\/2.5.0\/jszip.min\"","bundles","[","lib","]","=","{","\"buttons.colvis\"",":","\"https:\/\/cdn.datatables.net\/buttons\/1.5.6\/js\/buttons.colVis.min\"",",","\"buttons.flash\"",":","\"https:\/\/cdn.datatables.net\/buttons\/1.5.6\/js\/buttons.flash.min\"",",","\"buttons.html5\"",":","\"https:\/\/cdn.datatables.net\/buttons\/1.5.6\/js\/buttons.html5.min\"",",","\"buttons.print\"",":","\"https:\/\/cdn.datatables.net\/buttons\/1.5.6\/js\/buttons.print.min\"",",","}","for","bundle",",","path","in","bundles","[","lib","]",".","items","(",")",":","libs","[","bundle","]","=","path","shim","[","bundle","]","=","{","\"deps\"",":","[","\"jszip\"",",","lib","]","}","# requirements for correct Buttons functionality","libs","[","\"pdfmake\"","]","=","\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/pdfmake\/0.1.36\/pdfmake.min\"","shim","[","\"pdfmake\"","]","=","{","\"deps\"",":","[","\"datatables.net\"","]","}","libs","[","\"vfsfonts\"","]","=","\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/pdfmake\/0.1.36\/vfs_fonts\"","shim","[","\"vfsfonts\"","]","=","{","\"deps\"",":","[","\"datatables.net\"","]","}","if","extensions",".","responsive",":","libs","[","\"datatables.responsive\"","]","=","(","\"https:\/\/cdn.datatables.net\/\"","\"responsive\/2.2.2\/js\/dataTables.responsive.min\"",")","# Responsive","if","extensions",".","scroller",":","libs","[","\"datatables.scroller\"","]","=","(","\"https:\/\/cdn.datatables.net\/\"","\"scroller\/2.0.0\/js\/dataTables.scroller.min\"",")","# Scroll","if","extensions",".","select",":","libs","[","\"datatables.select\"","]","=","(","\"https:\/\/cdn.datatables.net\/\"","\"select\/1.3.0\/js\/dataTables.select.min\"",")","# Select","require",".","config","(","paths","=","libs",",","shim","=","shim",")","# link stylesheets","link_css","(","\"https:\/\/cdn.datatables.net\/v\/dt\/\"","\"dt-1.10.18\/\"","# DataTables","\"af-2.3.3\/\"","# AutoFill","\"b-1.5.6\/\"","# Buttons","\"b-colvis-1.5.6\/\"","# Buttons - Column Visibility","\"b-flash-1.5.6\/\"","# Buttons - Flash","\"b-html5-1.5.6\/\"","# Buttons - HTML5","\"b-print-1.5.6\/\"","# Buttons - Print View","\"cr-1.5.0\/\"","# ColReorder","\"fc-3.2.5\/\"","# FixedColumns","\"fh-3.1.4\/\"","# FixedHeader","\"kt-2.5.0\/\"","# KeyTable","\"r-2.2.2\/\"","# Responsive","\"rg-1.1.0\/\"","# RowGroup","\"rr-1.2.4\/\"","# RowReorder","\"sc-2.0.0\/\"","# Scroll","\"sl-1.3.0\/\"","# Select","\"datatables.min.css\"",",","{","\"id\"",":","\"datatables.min.css\"","}",",",")","# load custom style","load_css","(","Path","(","_HERE",",","\"css\/jupyter-datatables.css\"",")",".","read_text","(","encoding","=","\"utf-8\"",")",",","{","\"id\"",":","\"jupyter-datatables-css\"","}",",",")","load_js","(","Path","(","_HERE",",","\"js\/config.js\"",")",".","read_text","(","encoding","=","\"utf-8\"",")",",","{","\"id\"",":","\"dt-config-js\"","}",")","load_js","(","Path","(","_HERE",",","\"js\/components.js\"",")",".","read_text","(","encoding","=","\"utf-8\"",")",",","{","\"id\"",":","\"dt-components-js\"","}",")","load_js","(","Path","(","_HERE",",","\"js\/graph-objects.js\"",")",".","read_text","(","encoding","=","\"utf-8\"",")",",","{","\"id\"",":","\"dt-graph-objects-js\"","}",")","load_js","(","Path","(","_HERE",",","\"js\/toolbar.js\"",")",".","read_text","(","encoding","=","\"utf-8\"",")",",","{","\"id\"",":","\"dt-toolbar-js\"","}",")","load_js","(","Path","(","_HERE",",","\"js\/tooltips.js\"",")",".","read_text","(","encoding","=","\"utf-8\"",")",",","{","\"id\"",":","\"dt-tooltips-js\"","}",")","load_js","(","Path","(","_HERE",",","\"js\/jupyter-datatables.js\"",")",".","read_text","(","encoding","=","\"utf-8\"",")",",","{","\"id\"",":","\"jupyter-datatables-js\"","}",")","__REPR__","=","partialmethod","(","_repr_datatable_",",","options","=","options",",","classes","=","classes",")","_IS_INITIALIZED","=","True","pd",".","DataFrame",".","_repr_javascript_","=","__REPR__"],"url":"https:\/\/github.com\/CermakM\/jupyter-datatables\/blob\/59b4880f926caaecb862477f3f1c2e7bbebb4939\/jupyter_datatables\/__init__.py#L84-L228"}
4
+ {"nwo":"CermakM\/jupyter-datatables","sha":"59b4880f926caaecb862477f3f1c2e7bbebb4939","path":"jupyter_datatables\/__init__.py","language":"python","identifier":"_repr_datatable_","parameters":"(self, options: dict = None, classes: list = None)","argument_list":"","return_statement":"return f\"\"\"\n (function() {{\n const sample_size = Number({sample_size}).toLocaleString();\n const adjusted = Boolean('{adjusted}' == 'True')\n\n const total = Number({len(self)}).toLocaleString();\n\n element.append($('<p>').text(\n `Sample size: ${{sample_size}} out of ${{total}} ${{ adjusted ? \"(adjusted)\" : \"\" }}`));\n }}());\n \"\"\"","docstring":"Return DataTable representation of pandas DataFrame.","docstring_summary":"Return DataTable representation of pandas DataFrame.","docstring_tokens":["Return","DataTable","representation","of","pandas","DataFrame","."],"function":"def _repr_datatable_(self, options: dict = None, classes: list = None):\n \"\"\"Return DataTable representation of pandas DataFrame.\"\"\"\n if options is None:\n options = {}\n options.update({\n k: v for k, v in config.defaults.options.__dict__.items()\n if not k.startswith(\"_\")\n })\n\n # column types\n options.update({'columnDefs': _get_columns_defs(self, options)})\n\n # pop buttons, we need to use them separately\n buttons = options.pop(\"buttons\", [])\n classes = classes if classes is not None else \" \".join(\n config.defaults.classes)\n\n script = \"\"\"\n const settings = await appendDataTable(`$$html`, $$options, $$buttons, element);\n\n console.debug(\"DataTable successfully created.\");\n \"\"\"\n\n df = self\n sample_size = config.defaults.sample_size or len(self)\n\n if sample_size > len(df):\n raise ValueError(\n f\"Sample size cannot be larger than length of the table: {sample_size} > {len(df)}\"\n )\n\n adjusted = False\n\n if config.defaults.limit is not None:\n n = len(self)\n\n # compute the sample size, it will be used for the data preview\n # to speed up computation\n if len(self) > config.defaults.limit:\n sample_size = getattr(config.defaults, 'sample_size', None) or min([\n n, _calculate_sample_size(n)\n ])\n\n idx = []\n # get 5% of extremes from each column to account for outliers in the sample\n # (if applicable)\n fraction = math.ceil(sample_size * 0.05)\n for col in self.columns:\n if self[col].dtype != \"O\":\n # for comfortable preview, take the first 10 samples (if applicable)\n idx.extend(self.index[:min(len(self), 10, sample_size)])\n idx.extend(self.nlargest(fraction, col).index)\n idx.extend(self.nsmallest(fraction, col).index)\n\n idx = set(idx)\n random_index = self.index.difference(idx)\n random_sample = sample_size - \\\n min(len(idx), sample_size) if len(random_index) else 0\n\n sample_index = pd.Index({\n *idx,\n *np.random.choice(random_index, size=random_sample, replace=False)\n })\n adjusted = len(sample_index) != sample_size\n\n df = self.loc[sample_index].sort_index()\n\n sample_size = len(df)\n\n sort = config.defaults.sort\n if sort == True or sort == 'index':\n df.sort_index(inplace=True)\n elif sort:\n df.sort_values(inplace=True)\n\n sha = hashlib.sha256(\n df.to_json().encode()\n )\n digest = sha.hexdigest()\n\n html = df.to_html(classes=classes, table_id=digest)\n\n execute_with_requirements(\n script,\n required=[\n \"base\/js\/events\",\n \"datatables.net\",\n \"d3\",\n \"chartjs\",\n \"dt-config\",\n \"dt-components\",\n \"dt-graph-objects\",\n \"dt-toolbar\",\n \"dt-tooltips\",\n \"jupyter-datatables\"\n ],\n html=html,\n options=json.dumps(options),\n buttons=buttons,\n )\n\n # return script which links the scrollbars event after save\n safe_script = \"\"\"\n setTimeout(() => {\n const table_id = '$$table_id';\n const table = $(`#${table_id}_wrapper`);\n \n let scrollHead = table.find('div.dataTables_scrollHead');\n let scrollBody = table.find('div.dataTables_scrollBody');\n \n $(scrollBody).on(\n 'scroll',\n (e) => {\n scrollHead.scrollLeft(scrollBody.scrollLeft());\n },\n );\n }, 200);\n \"\"\"\n\n safe_execute(safe_script, table_id=digest)\n\n return f\"\"\"\n (function() {{\n const sample_size = Number({sample_size}).toLocaleString();\n const adjusted = Boolean('{adjusted}' == 'True')\n\n const total = Number({len(self)}).toLocaleString();\n\n element.append($('<p>').text(\n `Sample size: ${{sample_size}} out of ${{total}} ${{ adjusted ? \"(adjusted)\" : \"\" }}`));\n }}());\n \"\"\"","function_tokens":["def","_repr_datatable_","(","self",",","options",":","dict","=","None",",","classes",":","list","=","None",")",":","if","options","is","None",":","options","=","{","}","options",".","update","(","{","k",":","v","for","k",",","v","in","config",".","defaults",".","options",".","__dict__",".","items","(",")","if","not","k",".","startswith","(","\"_\"",")","}",")","# column types","options",".","update","(","{","'columnDefs'",":","_get_columns_defs","(","self",",","options",")","}",")","# pop buttons, we need to use them separately","buttons","=","options",".","pop","(","\"buttons\"",",","[","]",")","classes","=","classes","if","classes","is","not","None","else","\" \"",".","join","(","config",".","defaults",".","classes",")","script","=","\"\"\"\n const settings = await appendDataTable(`$$html`, $$options, $$buttons, element);\n\n console.debug(\"DataTable successfully created.\");\n \"\"\"","df","=","self","sample_size","=","config",".","defaults",".","sample_size","or","len","(","self",")","if","sample_size",">","len","(","df",")",":","raise","ValueError","(","f\"Sample size cannot be larger than length of the table: {sample_size} > {len(df)}\"",")","adjusted","=","False","if","config",".","defaults",".","limit","is","not","None",":","n","=","len","(","self",")","# compute the sample size, it will be used for the data preview","# to speed up computation","if","len","(","self",")",">","config",".","defaults",".","limit",":","sample_size","=","getattr","(","config",".","defaults",",","'sample_size'",",","None",")","or","min","(","[","n",",","_calculate_sample_size","(","n",")","]",")","idx","=","[","]","# get 5% of extremes from each column to account for outliers in the sample","# (if applicable)","fraction","=","math",".","ceil","(","sample_size","*","0.05",")","for","col","in","self",".","columns",":","if","self","[","col","]",".","dtype","!=","\"O\"",":","# for comfortable preview, take the first 10 samples (if applicable)","idx",".","extend","(","self",".","index","[",":","min","(","len","(","self",")",",","10",",","sample_size",")","]",")","idx",".","extend","(","self",".","nlargest","(","fraction",",","col",")",".","index",")","idx",".","extend","(","self",".","nsmallest","(","fraction",",","col",")",".","index",")","idx","=","set","(","idx",")","random_index","=","self",".","index",".","difference","(","idx",")","random_sample","=","sample_size","-","min","(","len","(","idx",")",",","sample_size",")","if","len","(","random_index",")","else","0","sample_index","=","pd",".","Index","(","{","*","idx",",","*","np",".","random",".","choice","(","random_index",",","size","=","random_sample",",","replace","=","False",")","}",")","adjusted","=","len","(","sample_index",")","!=","sample_size","df","=","self",".","loc","[","sample_index","]",".","sort_index","(",")","sample_size","=","len","(","df",")","sort","=","config",".","defaults",".","sort","if","sort","==","True","or","sort","==","'index'",":","df",".","sort_index","(","inplace","=","True",")","elif","sort",":","df",".","sort_values","(","inplace","=","True",")","sha","=","hashlib",".","sha256","(","df",".","to_json","(",")",".","encode","(",")",")","digest","=","sha",".","hexdigest","(",")","html","=","df",".","to_html","(","classes","=","classes",",","table_id","=","digest",")","execute_with_requirements","(","script",",","required","=","[","\"base\/js\/events\"",",","\"datatables.net\"",",","\"d3\"",",","\"chartjs\"",",","\"dt-config\"",",","\"dt-components\"",",","\"dt-graph-objects\"",",","\"dt-toolbar\"",",","\"dt-tooltips\"",",","\"jupyter-datatables\"","]",",","html","=","html",",","options","=","json",".","dumps","(","options",")",",","buttons","=","buttons",",",")","# return script which links the scrollbars event after save","safe_script","=","\"\"\"\n setTimeout(() => {\n const table_id = '$$table_id';\n const table = $(`#${table_id}_wrapper`);\n \n let scrollHead = table.find('div.dataTables_scrollHead');\n let scrollBody = table.find('div.dataTables_scrollBody');\n \n $(scrollBody).on(\n 'scroll',\n (e) => {\n scrollHead.scrollLeft(scrollBody.scrollLeft());\n },\n );\n }, 200);\n \"\"\"","safe_execute","(","safe_script",",","table_id","=","digest",")","return","f\"\"\"\n (function() {{\n const sample_size = Number({sample_size}).toLocaleString();\n const adjusted = Boolean('{adjusted}' == 'True')\n\n const total = Number({len(self)}).toLocaleString();\n\n element.append($('<p>').text(\n `Sample size: ${{sample_size}} out of ${{total}} ${{ adjusted ? \"(adjusted)\" : \"\" }}`));\n }}());\n \"\"\""],"url":"https:\/\/github.com\/CermakM\/jupyter-datatables\/blob\/59b4880f926caaecb862477f3f1c2e7bbebb4939\/jupyter_datatables\/__init__.py#L231-L362"}
5
+ {"nwo":"CermakM\/jupyter-datatables","sha":"59b4880f926caaecb862477f3f1c2e7bbebb4939","path":"jupyter_datatables\/__init__.py","language":"python","identifier":"_get_columns_defs","parameters":"(df: pd.DataFrame, options: dict = None)","argument_list":"","return_statement":"return col_defs","docstring":"Create column defs to be used by DataTable constructor.","docstring_summary":"Create column defs to be used by DataTable constructor.","docstring_tokens":["Create","column","defs","to","be","used","by","DataTable","constructor","."],"function":"def _get_columns_defs(df: pd.DataFrame, options: dict = None):\n \"\"\"Create column defs to be used by DataTable constructor.\"\"\"\n options = options or {}\n\n idx_cols = df.index.names\n col_defs = list(options.get('columnDefs', []))\n\n for i, dtype in enumerate(map(str, df.dtypes)):\n col_idx = i + len(idx_cols)\n col_def = {}\n\n append = True\n for d in col_defs:\n if d.get('targets', None) == col_idx:\n append = False\n col_def = d\n break\n\n col_def.update(type=dtype, targets=col_idx)\n if append:\n col_defs.append(col_def)\n\n return col_defs","function_tokens":["def","_get_columns_defs","(","df",":","pd",".","DataFrame",",","options",":","dict","=","None",")",":","options","=","options","or","{","}","idx_cols","=","df",".","index",".","names","col_defs","=","list","(","options",".","get","(","'columnDefs'",",","[","]",")",")","for","i",",","dtype","in","enumerate","(","map","(","str",",","df",".","dtypes",")",")",":","col_idx","=","i","+","len","(","idx_cols",")","col_def","=","{","}","append","=","True","for","d","in","col_defs",":","if","d",".","get","(","'targets'",",","None",")","==","col_idx",":","append","=","False","col_def","=","d","break","col_def",".","update","(","type","=","dtype",",","targets","=","col_idx",")","if","append",":","col_defs",".","append","(","col_def",")","return","col_defs"],"url":"https:\/\/github.com\/CermakM\/jupyter-datatables\/blob\/59b4880f926caaecb862477f3f1c2e7bbebb4939\/jupyter_datatables\/__init__.py#L365-L387"}
6
+ {"nwo":"CermakM\/jupyter-datatables","sha":"59b4880f926caaecb862477f3f1c2e7bbebb4939","path":"jupyter_datatables\/__init__.py","language":"python","identifier":"_calculate_sample_size","parameters":"(n, ci: float = 0.975, e: float = 0.02, p: float = 0.5)","argument_list":"","return_statement":"return _smart_ceil(u \/ (1 + u * math.pow(n, -1)))","docstring":"Calculate representative sample size.\n\n :param ci: float, confidence interval, default = 0.975\n :param e: float, margin of error, default = 0.02\n :param p: float, population proportion, default = 0.5","docstring_summary":"Calculate representative sample size.","docstring_tokens":["Calculate","representative","sample","size","."],"function":"def _calculate_sample_size(n, ci: float = 0.975, e: float = 0.02, p: float = 0.5) -> int:\n \"\"\"Calculate representative sample size.\n\n :param ci: float, confidence interval, default = 0.975\n :param e: float, margin of error, default = 0.02\n :param p: float, population proportion, default = 0.5\n \"\"\"\n try:\n from scipy import stats as st\n except ImportError:\n return math.sqrt(n)\n\n z = st.norm.ppf(1 - (1 - ci) \/ 2)\n u = z**2 * p * (1 - p) \/ e**2\n\n return _smart_ceil(u \/ (1 + u * math.pow(n, -1)))","function_tokens":["def","_calculate_sample_size","(","n",",","ci",":","float","=","0.975",",","e",":","float","=","0.02",",","p",":","float","=","0.5",")","->","int",":","try",":","from","scipy","import","stats","as","st","except","ImportError",":","return","math",".","sqrt","(","n",")","z","=","st",".","norm",".","ppf","(","1","-","(","1","-","ci",")","\/","2",")","u","=","z","**","2","*","p","*","(","1","-","p",")","\/","e","**","2","return","_smart_ceil","(","u","\/","(","1","+","u","*","math",".","pow","(","n",",","-","1",")",")",")"],"url":"https:\/\/github.com\/CermakM\/jupyter-datatables\/blob\/59b4880f926caaecb862477f3f1c2e7bbebb4939\/jupyter_datatables\/__init__.py#L390-L405"}
7
+ {"nwo":"CermakM\/jupyter-datatables","sha":"59b4880f926caaecb862477f3f1c2e7bbebb4939","path":"jupyter_datatables\/__init__.py","language":"python","identifier":"_smart_ceil","parameters":"(x: typing.Union[int, float], order: int = None)","argument_list":"","return_statement":"return int(x if x % mod == 0 else x + mod - x % mod)","docstring":"Smart ceil to the nearest round integer.\n\n The 'nearest' is chosen based on the order of the given number","docstring_summary":"Smart ceil to the nearest round integer.","docstring_tokens":["Smart","ceil","to","the","nearest","round","integer","."],"function":"def _smart_ceil(x: typing.Union[int, float], order: int = None) -> int:\n \"\"\"Smart ceil to the nearest round integer.\n\n The 'nearest' is chosen based on the order of the given number\n \"\"\"\n order = int(order) if order else len(str(math.ceil(x)))\n if order <= 0:\n raise ValueError(\"`order` must be integer >= 0\")\n mod = math.pow(10, min([order, 3]))\n\n return int(x if x % mod == 0 else x + mod - x % mod)","function_tokens":["def","_smart_ceil","(","x",":","typing",".","Union","[","int",",","float","]",",","order",":","int","=","None",")","->","int",":","order","=","int","(","order",")","if","order","else","len","(","str","(","math",".","ceil","(","x",")",")",")","if","order","<=","0",":","raise","ValueError","(","\"`order` must be integer >= 0\"",")","mod","=","math",".","pow","(","10",",","min","(","[","order",",","3","]",")",")","return","int","(","x","if","x","%","mod","==","0","else","x","+","mod","-","x","%","mod",")"],"url":"https:\/\/github.com\/CermakM\/jupyter-datatables\/blob\/59b4880f926caaecb862477f3f1c2e7bbebb4939\/jupyter_datatables\/__init__.py#L408-L418"}
ChromeDevTools__devtools-frontend.jsonl ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
1
+ {"nwo":"ChromeDevTools\/devtools-frontend","sha":"36834dd5de91aba0b15de21fc93958eee9e49108","path":"PRESUBMIT.py","language":"python","identifier":"_CheckForTooLargeFiles","parameters":"(input_api, output_api)","argument_list":"","return_statement":"","docstring":"Avoid large files, especially binary files, in the repository since\n git doesn't scale well for those. They will be in everyone's repo\n clones forever, forever making Chromium slower to clone and work\n with.","docstring_summary":"Avoid large files, especially binary files, in the repository since\n git doesn't scale well for those. They will be in everyone's repo\n clones forever, forever making Chromium slower to clone and work\n with.","docstring_tokens":["Avoid","large","files","especially","binary","files","in","the","repository","since","git","doesn","t","scale","well","for","those",".","They","will","be","in","everyone","s","repo","clones","forever","forever","making","Chromium","slower","to","clone","and","work","with","."],"function":"def _CheckForTooLargeFiles(input_api, output_api):\n \"\"\"Avoid large files, especially binary files, in the repository since\n git doesn't scale well for those. They will be in everyone's repo\n clones forever, forever making Chromium slower to clone and work\n with.\"\"\"\n # Uploading files to cloud storage is not trivial so we don't want\n # to set the limit too low, but the upper limit for \"normal\" large\n # files seems to be 1-2 MB, with a handful around 5-8 MB, so\n # anything over 20 MB is exceptional.\n TOO_LARGE_FILE_SIZE_LIMIT = 20 * 1024 * 1024 # 10 MB\n too_large_files = []\n for f in input_api.AffectedFiles():\n # Check both added and modified files (but not deleted files).\n if f.Action() in ('A', 'M'):\n size = input_api.os_path.getsize(f.AbsoluteLocalPath())\n if size > TOO_LARGE_FILE_SIZE_LIMIT:\n too_large_files.append(\"%s: %d bytes\" % (f.LocalPath(), size))\n if too_large_files:\n message = (\n 'Do not commit large files to git since git scales badly for those.\\n' +\n 'Instead put the large files in cloud storage and use DEPS to\\n' +\n 'fetch them.\\n' + '\\n'.join(too_large_files)\n )\n return [output_api.PresubmitError(\n 'Too large files found in commit', long_text=message + '\\n')]\n else:\n return []","function_tokens":["def","_CheckForTooLargeFiles","(","input_api",",","output_api",")",":","# Uploading files to cloud storage is not trivial so we don't want","# to set the limit too low, but the upper limit for \"normal\" large","# files seems to be 1-2 MB, with a handful around 5-8 MB, so","# anything over 20 MB is exceptional.","TOO_LARGE_FILE_SIZE_LIMIT","=","20","*","1024","*","1024","# 10 MB","too_large_files","=","[","]","for","f","in","input_api",".","AffectedFiles","(",")",":","# Check both added and modified files (but not deleted files).","if","f",".","Action","(",")","in","(","'A'",",","'M'",")",":","size","=","input_api",".","os_path",".","getsize","(","f",".","AbsoluteLocalPath","(",")",")","if","size",">","TOO_LARGE_FILE_SIZE_LIMIT",":","too_large_files",".","append","(","\"%s: %d bytes\"","%","(","f",".","LocalPath","(",")",",","size",")",")","if","too_large_files",":","message","=","(","'Do not commit large files to git since git scales badly for those.\\n'","+","'Instead put the large files in cloud storage and use DEPS to\\n'","+","'fetch them.\\n'","+","'\\n'",".","join","(","too_large_files",")",")","return","[","output_api",".","PresubmitError","(","'Too large files found in commit'",",","long_text","=","message","+","'\\n'",")","]","else",":","return","[","]"],"url":"https:\/\/github.com\/ChromeDevTools\/devtools-frontend\/blob\/36834dd5de91aba0b15de21fc93958eee9e49108\/PRESUBMIT.py#L472-L498"}
2
+ {"nwo":"ChromeDevTools\/devtools-frontend","sha":"36834dd5de91aba0b15de21fc93958eee9e49108","path":"PRESUBMIT.py","language":"python","identifier":"_CommonChecks","parameters":"(input_api, output_api)","argument_list":"","return_statement":"return results","docstring":"Checks common to both upload and commit.","docstring_summary":"Checks common to both upload and commit.","docstring_tokens":["Checks","common","to","both","upload","and","commit","."],"function":"def _CommonChecks(input_api, output_api):\n \"\"\"Checks common to both upload and commit.\"\"\"\n results = []\n results.extend(\n input_api.canned_checks.CheckAuthorizedAuthor(\n input_api, output_api, bot_allowlist=[AUTOROLL_ACCOUNT]))\n results.extend(_CheckExperimentTelemetry(input_api, output_api))\n results.extend(_CheckGeneratedFiles(input_api, output_api))\n results.extend(_CheckDevToolsStyleJS(input_api, output_api))\n results.extend(_CheckDevToolsStyleCSS(input_api, output_api))\n results.extend(_CheckDevToolsRunESLintTests(input_api, output_api))\n results.extend(_CheckDevToolsNonJSFileLicenseHeaders(\n input_api, output_api))\n\n results.extend(_CheckFormat(input_api, output_api))\n results.extend(_CheckChangesAreExclusiveToDirectory(input_api, output_api))\n # Run the canned checks from `depot_tools` after the custom DevTools checks.\n # The canned checks for example check that lines have line endings. The\n # DevTools presubmit checks automatically fix these issues. If we would run\n # the canned checks before the DevTools checks, they would erroneously conclude\n # that there are issues in the code. Since the canned checks are allowed to be\n # ignored, a confusing message is shown that asks if the failed presubmit can\n # be continued regardless. By fixing the issues before we reach the canned checks,\n # we don't show the message to suppress these errors, which would otherwise be\n # causing CQ to fail.\n results.extend(_RunCannedChecks(input_api, output_api))\n return results","function_tokens":["def","_CommonChecks","(","input_api",",","output_api",")",":","results","=","[","]","results",".","extend","(","input_api",".","canned_checks",".","CheckAuthorizedAuthor","(","input_api",",","output_api",",","bot_allowlist","=","[","AUTOROLL_ACCOUNT","]",")",")","results",".","extend","(","_CheckExperimentTelemetry","(","input_api",",","output_api",")",")","results",".","extend","(","_CheckGeneratedFiles","(","input_api",",","output_api",")",")","results",".","extend","(","_CheckDevToolsStyleJS","(","input_api",",","output_api",")",")","results",".","extend","(","_CheckDevToolsStyleCSS","(","input_api",",","output_api",")",")","results",".","extend","(","_CheckDevToolsRunESLintTests","(","input_api",",","output_api",")",")","results",".","extend","(","_CheckDevToolsNonJSFileLicenseHeaders","(","input_api",",","output_api",")",")","results",".","extend","(","_CheckFormat","(","input_api",",","output_api",")",")","results",".","extend","(","_CheckChangesAreExclusiveToDirectory","(","input_api",",","output_api",")",")","# Run the canned checks from `depot_tools` after the custom DevTools checks.","# The canned checks for example check that lines have line endings. The","# DevTools presubmit checks automatically fix these issues. If we would run","# the canned checks before the DevTools checks, they would erroneously conclude","# that there are issues in the code. Since the canned checks are allowed to be","# ignored, a confusing message is shown that asks if the failed presubmit can","# be continued regardless. By fixing the issues before we reach the canned checks,","# we don't show the message to suppress these errors, which would otherwise be","# causing CQ to fail.","results",".","extend","(","_RunCannedChecks","(","input_api",",","output_api",")",")","return","results"],"url":"https:\/\/github.com\/ChromeDevTools\/devtools-frontend\/blob\/36834dd5de91aba0b15de21fc93958eee9e49108\/PRESUBMIT.py#L520-L546"}
3
+ {"nwo":"ChromeDevTools\/devtools-frontend","sha":"36834dd5de91aba0b15de21fc93958eee9e49108","path":"PRESUBMIT.py","language":"python","identifier":"_SideEffectChecks","parameters":"(input_api, output_api)","argument_list":"","return_statement":"return results","docstring":"Check side effects caused by other checks","docstring_summary":"Check side effects caused by other checks","docstring_tokens":["Check","side","effects","caused","by","other","checks"],"function":"def _SideEffectChecks(input_api, output_api):\n \"\"\"Check side effects caused by other checks\"\"\"\n results = []\n results.extend(_CheckNoUncheckedFiles(input_api, output_api))\n results.extend(_CheckForTooLargeFiles(input_api, output_api))\n return results","function_tokens":["def","_SideEffectChecks","(","input_api",",","output_api",")",":","results","=","[","]","results",".","extend","(","_CheckNoUncheckedFiles","(","input_api",",","output_api",")",")","results",".","extend","(","_CheckForTooLargeFiles","(","input_api",",","output_api",")",")","return","results"],"url":"https:\/\/github.com\/ChromeDevTools\/devtools-frontend\/blob\/36834dd5de91aba0b15de21fc93958eee9e49108\/PRESUBMIT.py#L549-L554"}
4
+ {"nwo":"ChromeDevTools\/devtools-frontend","sha":"36834dd5de91aba0b15de21fc93958eee9e49108","path":"PRESUBMIT.py","language":"python","identifier":"_getAffectedFiles","parameters":"(input_api, parent_directories, excluded_actions, accepted_endings)","argument_list":"","return_statement":"return affected_files","docstring":"Return absolute file paths of affected files (not due to an excluded action)\n under a parent directory with an accepted file ending.","docstring_summary":"Return absolute file paths of affected files (not due to an excluded action)\n under a parent directory with an accepted file ending.","docstring_tokens":["Return","absolute","file","paths","of","affected","files","(","not","due","to","an","excluded","action",")","under","a","parent","directory","with","an","accepted","file","ending","."],"function":"def _getAffectedFiles(input_api, parent_directories, excluded_actions, accepted_endings): # pylint: disable=invalid-name\n \"\"\"Return absolute file paths of affected files (not due to an excluded action)\n under a parent directory with an accepted file ending.\n \"\"\"\n local_paths = [\n f.AbsoluteLocalPath() for f in input_api.AffectedFiles() if all(f.Action() != action for action in excluded_actions)\n ]\n affected_files = [\n file_name for file_name in local_paths\n if any(parent_directory in file_name\n for parent_directory in parent_directories) and (\n len(accepted_endings) == 0 or any(\n file_name.endswith(accepted_ending)\n for accepted_ending in accepted_endings))\n ]\n return affected_files","function_tokens":["def","_getAffectedFiles","(","input_api",",","parent_directories",",","excluded_actions",",","accepted_endings",")",":","# pylint: disable=invalid-name","local_paths","=","[","f",".","AbsoluteLocalPath","(",")","for","f","in","input_api",".","AffectedFiles","(",")","if","all","(","f",".","Action","(",")","!=","action","for","action","in","excluded_actions",")","]","affected_files","=","[","file_name","for","file_name","in","local_paths","if","any","(","parent_directory","in","file_name","for","parent_directory","in","parent_directories",")","and","(","len","(","accepted_endings",")","==","0","or","any","(","file_name",".","endswith","(","accepted_ending",")","for","accepted_ending","in","accepted_endings",")",")","]","return","affected_files"],"url":"https:\/\/github.com\/ChromeDevTools\/devtools-frontend\/blob\/36834dd5de91aba0b15de21fc93958eee9e49108\/PRESUBMIT.py#L578-L593"}
5
+ {"nwo":"ChromeDevTools\/devtools-frontend","sha":"36834dd5de91aba0b15de21fc93958eee9e49108","path":"third_party\/pyjson5\/src\/json5\/lib.py","language":"python","identifier":"load","parameters":"(fp, encoding=None, cls=None, object_hook=None, parse_float=None,\n parse_int=None, parse_constant=None, object_pairs_hook=None)","argument_list":"","return_statement":"return loads(s, encoding=encoding, cls=cls, object_hook=object_hook,\n parse_float=parse_float, parse_int=parse_int,\n parse_constant=parse_constant,\n object_pairs_hook=object_pairs_hook)","docstring":"Deserialize ``fp`` (a ``.read()``-supporting file-like object\n containing a JSON document) to a Python object.","docstring_summary":"Deserialize ``fp`` (a ``.read()``-supporting file-like object\n containing a JSON document) to a Python object.","docstring_tokens":["Deserialize","fp","(","a",".","read","()","-","supporting","file","-","like","object","containing","a","JSON","document",")","to","a","Python","object","."],"function":"def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None,\n parse_int=None, parse_constant=None, object_pairs_hook=None):\n \"\"\"Deserialize ``fp`` (a ``.read()``-supporting file-like object\n containing a JSON document) to a Python object.\"\"\"\n\n s = fp.read()\n return loads(s, encoding=encoding, cls=cls, object_hook=object_hook,\n parse_float=parse_float, parse_int=parse_int,\n parse_constant=parse_constant,\n object_pairs_hook=object_pairs_hook)","function_tokens":["def","load","(","fp",",","encoding","=","None",",","cls","=","None",",","object_hook","=","None",",","parse_float","=","None",",","parse_int","=","None",",","parse_constant","=","None",",","object_pairs_hook","=","None",")",":","s","=","fp",".","read","(",")","return","loads","(","s",",","encoding","=","encoding",",","cls","=","cls",",","object_hook","=","object_hook",",","parse_float","=","parse_float",",","parse_int","=","parse_int",",","parse_constant","=","parse_constant",",","object_pairs_hook","=","object_pairs_hook",")"],"url":"https:\/\/github.com\/ChromeDevTools\/devtools-frontend\/blob\/36834dd5de91aba0b15de21fc93958eee9e49108\/third_party\/pyjson5\/src\/json5\/lib.py#L27-L36"}
6
+ {"nwo":"ChromeDevTools\/devtools-frontend","sha":"36834dd5de91aba0b15de21fc93958eee9e49108","path":"third_party\/pyjson5\/src\/json5\/lib.py","language":"python","identifier":"loads","parameters":"(s, encoding=None, cls=None, object_hook=None, parse_float=None,\n parse_int=None, parse_constant=None, object_pairs_hook=None)","argument_list":"","return_statement":"return _walk_ast(ast, dictify, parse_float, parse_int, parse_constant)","docstring":"Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a\n JSON5 document) to a Python object.","docstring_summary":"Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a\n JSON5 document) to a Python object.","docstring_tokens":["Deserialize","s","(","a","str","or","unicode","instance","containing","a","JSON5","document",")","to","a","Python","object","."],"function":"def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,\n parse_int=None, parse_constant=None, object_pairs_hook=None):\n \"\"\"Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a\n JSON5 document) to a Python object.\"\"\"\n\n assert cls is None, 'Custom decoders are not supported'\n\n if sys.version_info[0] < 3:\n decodable_type = type('')\n else:\n decodable_type = type(b'')\n if isinstance(s, decodable_type):\n encoding = encoding or 'utf-8'\n s = s.decode(encoding)\n\n if not s:\n raise ValueError('Empty strings are not legal JSON5')\n parser = Parser(s, '<string>')\n ast, err, newpos = parser.parse()\n if err:\n raise ValueError(err)\n\n def _fp_constant_parser(s):\n return float(s.replace('Infinity', 'inf').replace('NaN', 'nan'))\n\n if object_pairs_hook:\n dictify = object_pairs_hook\n elif object_hook:\n dictify = lambda pairs: object_hook(dict(pairs))\n else:\n dictify = dict\n\n parse_float = parse_float or float\n parse_int = parse_int or int\n parse_constant = parse_constant or _fp_constant_parser\n\n return _walk_ast(ast, dictify, parse_float, parse_int, parse_constant)","function_tokens":["def","loads","(","s",",","encoding","=","None",",","cls","=","None",",","object_hook","=","None",",","parse_float","=","None",",","parse_int","=","None",",","parse_constant","=","None",",","object_pairs_hook","=","None",")",":","assert","cls","is","None",",","'Custom decoders are not supported'","if","sys",".","version_info","[","0","]","<","3",":","decodable_type","=","type","(","''",")","else",":","decodable_type","=","type","(","b''",")","if","isinstance","(","s",",","decodable_type",")",":","encoding","=","encoding","or","'utf-8'","s","=","s",".","decode","(","encoding",")","if","not","s",":","raise","ValueError","(","'Empty strings are not legal JSON5'",")","parser","=","Parser","(","s",",","'<string>'",")","ast",",","err",",","newpos","=","parser",".","parse","(",")","if","err",":","raise","ValueError","(","err",")","def","_fp_constant_parser","(","s",")",":","return","float","(","s",".","replace","(","'Infinity'",",","'inf'",")",".","replace","(","'NaN'",",","'nan'",")",")","if","object_pairs_hook",":","dictify","=","object_pairs_hook","elif","object_hook",":","dictify","=","lambda","pairs",":","object_hook","(","dict","(","pairs",")",")","else",":","dictify","=","dict","parse_float","=","parse_float","or","float","parse_int","=","parse_int","or","int","parse_constant","=","parse_constant","or","_fp_constant_parser","return","_walk_ast","(","ast",",","dictify",",","parse_float",",","parse_int",",","parse_constant",")"],"url":"https:\/\/github.com\/ChromeDevTools\/devtools-frontend\/blob\/36834dd5de91aba0b15de21fc93958eee9e49108\/third_party\/pyjson5\/src\/json5\/lib.py#L39-L75"}
7
+ {"nwo":"ChromeDevTools\/devtools-frontend","sha":"36834dd5de91aba0b15de21fc93958eee9e49108","path":"third_party\/pyjson5\/src\/json5\/lib.py","language":"python","identifier":"dumps","parameters":"(obj, compact=False, as_json=False, **kwargs)","argument_list":"","return_statement":"","docstring":"Serialize ``obj`` to a JSON5-formatted ``str``.","docstring_summary":"Serialize ``obj`` to a JSON5-formatted ``str``.","docstring_tokens":["Serialize","obj","to","a","JSON5","-","formatted","str","."],"function":"def dumps(obj, compact=False, as_json=False, **kwargs):\n \"\"\"Serialize ``obj`` to a JSON5-formatted ``str``.\"\"\"\n\n if as_json or not compact:\n return json.dumps(obj, **kwargs)\n\n t = type(obj)\n if obj == True:\n return u'true'\n elif obj == False:\n return u'false'\n elif obj == None:\n return u'null'\n elif t == type('') or t == type(u''):\n single = \"'\" in obj\n double = '\"' in obj\n if single and double:\n return json.dumps(obj)\n elif single:\n return '\"' + obj + '\"'\n else:\n return \"'\" + obj + \"'\"\n elif t is float or t is int:\n return str(obj)\n elif t is dict:\n return u'{' + u','.join([\n _dumpkey(k) + u':' + dumps(v) for k, v in obj.items()\n ]) + '}'\n elif t is list:\n return u'[' + ','.join([dumps(el) for el in obj]) + u']'\n else: # pragma: no cover\n return u''","function_tokens":["def","dumps","(","obj",",","compact","=","False",",","as_json","=","False",",","*","*","kwargs",")",":","if","as_json","or","not","compact",":","return","json",".","dumps","(","obj",",","*","*","kwargs",")","t","=","type","(","obj",")","if","obj","==","True",":","return","u'true'","elif","obj","==","False",":","return","u'false'","elif","obj","==","None",":","return","u'null'","elif","t","==","type","(","''",")","or","t","==","type","(","u''",")",":","single","=","\"'\"","in","obj","double","=","'\"'","in","obj","if","single","and","double",":","return","json",".","dumps","(","obj",")","elif","single",":","return","'\"'","+","obj","+","'\"'","else",":","return","\"'\"","+","obj","+","\"'\"","elif","t","is","float","or","t","is","int",":","return","str","(","obj",")","elif","t","is","dict",":","return","u'{'","+","u','",".","join","(","[","_dumpkey","(","k",")","+","u':'","+","dumps","(","v",")","for","k",",","v","in","obj",".","items","(",")","]",")","+","'}'","elif","t","is","list",":","return","u'['","+","','",".","join","(","[","dumps","(","el",")","for","el","in","obj","]",")","+","u']'","else",":","# pragma: no cover","return","u''"],"url":"https:\/\/github.com\/ChromeDevTools\/devtools-frontend\/blob\/36834dd5de91aba0b15de21fc93958eee9e49108\/third_party\/pyjson5\/src\/json5\/lib.py#L120-L151"}
8
+ {"nwo":"ChromeDevTools\/devtools-frontend","sha":"36834dd5de91aba0b15de21fc93958eee9e49108","path":"third_party\/pyjson5\/src\/json5\/lib.py","language":"python","identifier":"dump","parameters":"(obj, fp, **kwargs)","argument_list":"","return_statement":"","docstring":"Serialize ``obj`` to a JSON5-formatted stream to ``fp`` (a ``.write()``-\n supporting file-like object).","docstring_summary":"Serialize ``obj`` to a JSON5-formatted stream to ``fp`` (a ``.write()``-\n supporting file-like object).","docstring_tokens":["Serialize","obj","to","a","JSON5","-","formatted","stream","to","fp","(","a",".","write","()","-","supporting","file","-","like","object",")","."],"function":"def dump(obj, fp, **kwargs):\n \"\"\"Serialize ``obj`` to a JSON5-formatted stream to ``fp`` (a ``.write()``-\n supporting file-like object).\"\"\"\n\n s = dumps(obj, **kwargs)\n fp.write(str(s))","function_tokens":["def","dump","(","obj",",","fp",",","*","*","kwargs",")",":","s","=","dumps","(","obj",",","*","*","kwargs",")","fp",".","write","(","str","(","s",")",")"],"url":"https:\/\/github.com\/ChromeDevTools\/devtools-frontend\/blob\/36834dd5de91aba0b15de21fc93958eee9e49108\/third_party\/pyjson5\/src\/json5\/lib.py#L154-L159"}
CivilHub__CivilHub.jsonl ADDED
The diff for this file is too large to render. See raw diff
Cloud-CV__Origami.jsonl ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"Cloud-CV\/Origami","sha":"8046898c1afdcc0d32ac3c4a0909f63e2133c3a0","path":"api\/views.py","language":"python","identifier":"redirect_login","parameters":"(req)","argument_list":"","return_statement":"return HttpResponseRedirect(\n '\/login?status=passed&token=' + token.token + '&username=' + user.username + '&user_id=' + str(user.id))","docstring":"Retrieves the token, username and user_id of the user and\n redirects the user to the next page.","docstring_summary":"Retrieves the token, username and user_id of the user and\n redirects the user to the next page.","docstring_tokens":["Retrieves","the","token","username","and","user_id","of","the","user","and","redirects","the","user","to","the","next","page","."],"function":"def redirect_login(req):\n \"\"\"\n Retrieves the token, username and user_id of the user and\n redirects the user to the next page.\n \"\"\"\n user = User.objects.get(username=req.user.username)\n acc = SocialAccount.objects.get(user=user)\n token = SocialToken.objects.get(account=acc)\n if not str(user.id) == acc.uid:\n tmp = user\n user = user.delete()\n tmp.id = acc.uid\n tmp.save()\n acc.user = tmp\n acc.save()\n return HttpResponseRedirect(\n '\/login?status=passed&token=' + token.token + '&username=' + tmp.username + '&user_id=' + str(tmp.id))\n return HttpResponseRedirect(\n '\/login?status=passed&token=' + token.token + '&username=' + user.username + '&user_id=' + str(user.id))","function_tokens":["def","redirect_login","(","req",")",":","user","=","User",".","objects",".","get","(","username","=","req",".","user",".","username",")","acc","=","SocialAccount",".","objects",".","get","(","user","=","user",")","token","=","SocialToken",".","objects",".","get","(","account","=","acc",")","if","not","str","(","user",".","id",")","==","acc",".","uid",":","tmp","=","user","user","=","user",".","delete","(",")","tmp",".","id","=","acc",".","uid","tmp",".","save","(",")","acc",".","user","=","tmp","acc",".","save","(",")","return","HttpResponseRedirect","(","'\/login?status=passed&token='","+","token",".","token","+","'&username='","+","tmp",".","username","+","'&user_id='","+","str","(","tmp",".","id",")",")","return","HttpResponseRedirect","(","'\/login?status=passed&token='","+","token",".","token","+","'&username='","+","user",".","username","+","'&user_id='","+","str","(","user",".","id",")",")"],"url":"https:\/\/github.com\/Cloud-CV\/Origami\/blob\/8046898c1afdcc0d32ac3c4a0909f63e2133c3a0\/api\/views.py#L121-L139"}
2
+ {"nwo":"Cloud-CV\/Origami","sha":"8046898c1afdcc0d32ac3c4a0909f63e2133c3a0","path":"api\/views.py","language":"python","identifier":"is_cloudcv","parameters":"(request)","argument_list":"","return_statement":"return Response(serialize.data, status=response_status.HTTP_200_OK)","docstring":"Returns all fields in the current RootSettings object.","docstring_summary":"Returns all fields in the current RootSettings object.","docstring_tokens":["Returns","all","fields","in","the","current","RootSettings","object","."],"function":"def is_cloudcv(request):\n \"\"\"\n Returns all fields in the current RootSettings object.\n \"\"\"\n settings = RootSettings.objects.all().first()\n serialize = RootSettingsSerializer(settings)\n return Response(serialize.data, status=response_status.HTTP_200_OK)","function_tokens":["def","is_cloudcv","(","request",")",":","settings","=","RootSettings",".","objects",".","all","(",")",".","first","(",")","serialize","=","RootSettingsSerializer","(","settings",")","return","Response","(","serialize",".","data",",","status","=","response_status",".","HTTP_200_OK",")"],"url":"https:\/\/github.com\/Cloud-CV\/Origami\/blob\/8046898c1afdcc0d32ac3c4a0909f63e2133c3a0\/api\/views.py#L143-L149"}
3
+ {"nwo":"Cloud-CV\/Origami","sha":"8046898c1afdcc0d32ac3c4a0909f63e2133c3a0","path":"api\/views.py","language":"python","identifier":"get_all_user_demos","parameters":"(request, id)","argument_list":"","return_statement":"return Response(serialize.data, status=response_status.HTTP_200_OK)","docstring":"Returns properties of all demos for the\n user identified by the given id.","docstring_summary":"Returns properties of all demos for the\n user identified by the given id.","docstring_tokens":["Returns","properties","of","all","demos","for","the","user","identified","by","the","given","id","."],"function":"def get_all_user_demos(request, id):\n \"\"\"\n Returns properties of all demos for the\n user identified by the given id.\n \"\"\"\n demos = Demo.objects.filter(user_id=id)\n serialize = DemoSerializer(demos, many=True)\n return Response(serialize.data, status=response_status.HTTP_200_OK)","function_tokens":["def","get_all_user_demos","(","request",",","id",")",":","demos","=","Demo",".","objects",".","filter","(","user_id","=","id",")","serialize","=","DemoSerializer","(","demos",",","many","=","True",")","return","Response","(","serialize",".","data",",","status","=","response_status",".","HTTP_200_OK",")"],"url":"https:\/\/github.com\/Cloud-CV\/Origami\/blob\/8046898c1afdcc0d32ac3c4a0909f63e2133c3a0\/api\/views.py#L153-L160"}
4
+ {"nwo":"Cloud-CV\/Origami","sha":"8046898c1afdcc0d32ac3c4a0909f63e2133c3a0","path":"api\/views.py","language":"python","identifier":"get_all_demos","parameters":"(request)","argument_list":"","return_statement":"return Response(data, status=response_status.HTTP_200_OK)","docstring":"If the request parameter search_by is demo,\n returns all demos which contains the search_term as a substring,\n otherwise returns all demos belonging to the user having the\n username matching the given search_term.","docstring_summary":"If the request parameter search_by is demo,\n returns all demos which contains the search_term as a substring,\n otherwise returns all demos belonging to the user having the\n username matching the given search_term.","docstring_tokens":["If","the","request","parameter","search_by","is","demo","returns","all","demos","which","contains","the","search_term","as","a","substring","otherwise","returns","all","demos","belonging","to","the","user","having","the","username","matching","the","given","search_term","."],"function":"def get_all_demos(request):\n \"\"\"\n If the request parameter search_by is demo,\n returns all demos which contains the search_term as a substring,\n otherwise returns all demos belonging to the user having the\n username matching the given search_term.\n \"\"\"\n search_by = request.query_params.get('search_by', None)\n search_term = request.query_params.get('search_term', None)\n demos = []\n if search_by == \"demo\":\n demos = Demo.objects.filter(name__icontains=search_term)\n else:\n try:\n user = User.objects.get(username__iexact=search_term)\n demos = Demo.objects.filter(user_id=user.id)\n except User.DoesNotExist:\n demos = []\n serialize = DemoSerializer(demos, many=True)\n data = serialize.data\n for x in range(len(demos)):\n data[x][\"username\"] = User.objects.get(id=data[x][\"user_id\"]).username\n return Response(data, status=response_status.HTTP_200_OK)","function_tokens":["def","get_all_demos","(","request",")",":","search_by","=","request",".","query_params",".","get","(","'search_by'",",","None",")","search_term","=","request",".","query_params",".","get","(","'search_term'",",","None",")","demos","=","[","]","if","search_by","==","\"demo\"",":","demos","=","Demo",".","objects",".","filter","(","name__icontains","=","search_term",")","else",":","try",":","user","=","User",".","objects",".","get","(","username__iexact","=","search_term",")","demos","=","Demo",".","objects",".","filter","(","user_id","=","user",".","id",")","except","User",".","DoesNotExist",":","demos","=","[","]","serialize","=","DemoSerializer","(","demos",",","many","=","True",")","data","=","serialize",".","data","for","x","in","range","(","len","(","demos",")",")",":","data","[","x","]","[","\"username\"","]","=","User",".","objects",".","get","(","id","=","data","[","x","]","[","\"user_id\"","]",")",".","username","return","Response","(","data",",","status","=","response_status",".","HTTP_200_OK",")"],"url":"https:\/\/github.com\/Cloud-CV\/Origami\/blob\/8046898c1afdcc0d32ac3c4a0909f63e2133c3a0\/api\/views.py#L164-L186"}
5
+ {"nwo":"Cloud-CV\/Origami","sha":"8046898c1afdcc0d32ac3c4a0909f63e2133c3a0","path":"api\/views.py","language":"python","identifier":"custom_component_controller","parameters":"(request, type_req, user_id, demoid)","argument_list":"","return_statement":"return Response(\"Invalid URL\", status=response_status.HTTP_404_NOT_FOUND)","docstring":"Gets the properties of, adds, updates, or removes an\n InputComponent or OutputComponent given a\n GET, POST, PUT or DELETE request respectively.\n\n Keyword arguments:\n type_req (str): Specifies whether processing is for an\n InputComponent or OutputComponent.\n user_id (str): The id of the user\n demoid (str): The id of the demo","docstring_summary":"Gets the properties of, adds, updates, or removes an\n InputComponent or OutputComponent given a\n GET, POST, PUT or DELETE request respectively.","docstring_tokens":["Gets","the","properties","of","adds","updates","or","removes","an","InputComponent","or","OutputComponent","given","a","GET","POST","PUT","or","DELETE","request","respectively","."],"function":"def custom_component_controller(request, type_req, user_id, demoid):\n \"\"\"\n Gets the properties of, adds, updates, or removes an\n InputComponent or OutputComponent given a\n GET, POST, PUT or DELETE request respectively.\n\n Keyword arguments:\n type_req (str): Specifies whether processing is for an\n InputComponent or OutputComponent.\n user_id (str): The id of the user\n demoid (str): The id of the demo\n \"\"\"\n model = \"\"\n serializer = \"\"\n if type_req == \"input\":\n model = InputComponent\n serializer = InputComponentSerializer\n elif type_req == \"output\":\n model = OutputComponent\n serializer = OutputComponentSerializer\n\n if request.method == \"POST\":\n body = request.data\n demo_id = body[\"id\"]\n demo = Demo.objects.get(id=demo_id)\n base_comp_id = body[\"base_component_id\"]\n props = []\n for prop in body[\"props\"]:\n if prop:\n props.append({\n \"id\": prop[\"id\"].encode(\"ascii\", \"ignore\").decode('utf-8'),\n \"label\": prop[\"label\"].encode(\"ascii\", \"ignore\").decode('utf-8')\n })\n else:\n props.append({})\n user_id = body[\"user_id\"]\n component = model.objects.create(\n demo=demo, base_component_id=base_comp_id, props=json.dumps(props), user_id=user_id)\n serialize = serializer(component)\n return Response(serialize.data, status=response_status.HTTP_201_CREATED)\n elif request.method == \"GET\":\n if user_id:\n if demoid:\n demo = Demo.objects.get(id=demoid)\n try:\n component = model.objects.get(user_id=user_id, demo=demo)\n except Exception:\n return Response({\"text\": \"Not Found\"})\n\n serialize = serializer(component)\n data = serialize.data\n data[\"props\"] = json.loads(data[\"props\"].encode(\"ascii\", \"ignore\").decode('utf8'))\n data[\"demo\"] = DemoSerializer(component.demo).data\n data[\"id\"] = component.demo.id\n return Response([data], status=response_status.HTTP_200_OK)\n else:\n components = model.objects.filter(user_id=user_id)\n serialize = serializer(components, many=True)\n data = serialize.data\n for x in range(len(data)):\n data[x][\"props\"] = json.loads(data[x][\"props\"].encode(\"ascii\", \"ignore\").decode('utf8'))\n data[x][\"demo\"] = DemoSerializer(components[x].demo).data\n data[x][\"id\"] = components[x].demo.id\n return Response(serialize.data, status=response_status.HTTP_200_OK)\n else:\n return Response(\"Invalid URL\", status=response_status.HTTP_404_NOT_FOUND)\n elif request.method == \"PUT\":\n body = request.data\n if user_id and demoid:\n demo = Demo.objects.get(id=demoid)\n component = model.objects.get(demo=demo, user_id=user_id)\n component.base_component_id = body[\"base_component_id\"]\n props = []\n for prop in body[\"props\"]:\n if prop:\n props.append({\n \"id\": prop[\"id\"].encode(\"ascii\", \"ignore\").decode('utf-8'),\n \"label\": prop[\"label\"].encode(\"ascii\", \"ignore\").decode('utf-8')\n })\n else:\n props.append({})\n component.props = json.dumps(props)\n component.save()\n serialize = serializer(component)\n return Response(serialize.data, status=response_status.HTTP_200_OK)\n else:\n return Response(\"Invalid URL\", status=response_status.HTTP_404_NOT_FOUND)\n elif request.method == \"DELETE\":\n if user_id and demoid:\n model.objects.get(id=demoid, user_id=user_id).delete()\n return Response({\"removed\": True}, status=response_status.HTTP_200_OK)\n else:\n return Response(\"Invalid URL\", status=response_status.HTTP_404_NOT_FOUND)\n return Response(\"Invalid URL\", status=response_status.HTTP_404_NOT_FOUND)","function_tokens":["def","custom_component_controller","(","request",",","type_req",",","user_id",",","demoid",")",":","model","=","\"\"","serializer","=","\"\"","if","type_req","==","\"input\"",":","model","=","InputComponent","serializer","=","InputComponentSerializer","elif","type_req","==","\"output\"",":","model","=","OutputComponent","serializer","=","OutputComponentSerializer","if","request",".","method","==","\"POST\"",":","body","=","request",".","data","demo_id","=","body","[","\"id\"","]","demo","=","Demo",".","objects",".","get","(","id","=","demo_id",")","base_comp_id","=","body","[","\"base_component_id\"","]","props","=","[","]","for","prop","in","body","[","\"props\"","]",":","if","prop",":","props",".","append","(","{","\"id\"",":","prop","[","\"id\"","]",".","encode","(","\"ascii\"",",","\"ignore\"",")",".","decode","(","'utf-8'",")",",","\"label\"",":","prop","[","\"label\"","]",".","encode","(","\"ascii\"",",","\"ignore\"",")",".","decode","(","'utf-8'",")","}",")","else",":","props",".","append","(","{","}",")","user_id","=","body","[","\"user_id\"","]","component","=","model",".","objects",".","create","(","demo","=","demo",",","base_component_id","=","base_comp_id",",","props","=","json",".","dumps","(","props",")",",","user_id","=","user_id",")","serialize","=","serializer","(","component",")","return","Response","(","serialize",".","data",",","status","=","response_status",".","HTTP_201_CREATED",")","elif","request",".","method","==","\"GET\"",":","if","user_id",":","if","demoid",":","demo","=","Demo",".","objects",".","get","(","id","=","demoid",")","try",":","component","=","model",".","objects",".","get","(","user_id","=","user_id",",","demo","=","demo",")","except","Exception",":","return","Response","(","{","\"text\"",":","\"Not Found\"","}",")","serialize","=","serializer","(","component",")","data","=","serialize",".","data","data","[","\"props\"","]","=","json",".","loads","(","data","[","\"props\"","]",".","encode","(","\"ascii\"",",","\"ignore\"",")",".","decode","(","'utf8'",")",")","data","[","\"demo\"","]","=","DemoSerializer","(","component",".","demo",")",".","data","data","[","\"id\"","]","=","component",".","demo",".","id","return","Response","(","[","data","]",",","status","=","response_status",".","HTTP_200_OK",")","else",":","components","=","model",".","objects",".","filter","(","user_id","=","user_id",")","serialize","=","serializer","(","components",",","many","=","True",")","data","=","serialize",".","data","for","x","in","range","(","len","(","data",")",")",":","data","[","x","]","[","\"props\"","]","=","json",".","loads","(","data","[","x","]","[","\"props\"","]",".","encode","(","\"ascii\"",",","\"ignore\"",")",".","decode","(","'utf8'",")",")","data","[","x","]","[","\"demo\"","]","=","DemoSerializer","(","components","[","x","]",".","demo",")",".","data","data","[","x","]","[","\"id\"","]","=","components","[","x","]",".","demo",".","id","return","Response","(","serialize",".","data",",","status","=","response_status",".","HTTP_200_OK",")","else",":","return","Response","(","\"Invalid URL\"",",","status","=","response_status",".","HTTP_404_NOT_FOUND",")","elif","request",".","method","==","\"PUT\"",":","body","=","request",".","data","if","user_id","and","demoid",":","demo","=","Demo",".","objects",".","get","(","id","=","demoid",")","component","=","model",".","objects",".","get","(","demo","=","demo",",","user_id","=","user_id",")","component",".","base_component_id","=","body","[","\"base_component_id\"","]","props","=","[","]","for","prop","in","body","[","\"props\"","]",":","if","prop",":","props",".","append","(","{","\"id\"",":","prop","[","\"id\"","]",".","encode","(","\"ascii\"",",","\"ignore\"",")",".","decode","(","'utf-8'",")",",","\"label\"",":","prop","[","\"label\"","]",".","encode","(","\"ascii\"",",","\"ignore\"",")",".","decode","(","'utf-8'",")","}",")","else",":","props",".","append","(","{","}",")","component",".","props","=","json",".","dumps","(","props",")","component",".","save","(",")","serialize","=","serializer","(","component",")","return","Response","(","serialize",".","data",",","status","=","response_status",".","HTTP_200_OK",")","else",":","return","Response","(","\"Invalid URL\"",",","status","=","response_status",".","HTTP_404_NOT_FOUND",")","elif","request",".","method","==","\"DELETE\"",":","if","user_id","and","demoid",":","model",".","objects",".","get","(","id","=","demoid",",","user_id","=","user_id",")",".","delete","(",")","return","Response","(","{","\"removed\"",":","True","}",",","status","=","response_status",".","HTTP_200_OK",")","else",":","return","Response","(","\"Invalid URL\"",",","status","=","response_status",".","HTTP_404_NOT_FOUND",")","return","Response","(","\"Invalid URL\"",",","status","=","response_status",".","HTTP_404_NOT_FOUND",")"],"url":"https:\/\/github.com\/Cloud-CV\/Origami\/blob\/8046898c1afdcc0d32ac3c4a0909f63e2133c3a0\/api\/views.py#L190-L283"}
6
+ {"nwo":"Cloud-CV\/Origami","sha":"8046898c1afdcc0d32ac3c4a0909f63e2133c3a0","path":"api\/views.py","language":"python","identifier":"alive","parameters":"(request)","argument_list":"","return_statement":"return HttpResponse(status=200)","docstring":"Returns a status 200 if the server is running and 404 otherwise","docstring_summary":"Returns a status 200 if the server is running and 404 otherwise","docstring_tokens":["Returns","a","status","200","if","the","server","is","running","and","404","otherwise"],"function":"def alive(request):\n \"\"\"Returns a status 200 if the server is running and 404 otherwise\"\"\"\n return HttpResponse(status=200)","function_tokens":["def","alive","(","request",")",":","return","HttpResponse","(","status","=","200",")"],"url":"https:\/\/github.com\/Cloud-CV\/Origami\/blob\/8046898c1afdcc0d32ac3c4a0909f63e2133c3a0\/api\/views.py#L286-L288"}
7
+ {"nwo":"Cloud-CV\/Origami","sha":"8046898c1afdcc0d32ac3c4a0909f63e2133c3a0","path":"api\/views.py","language":"python","identifier":"custom_demo_controller","parameters":"(request, user_id, id)","argument_list":"","return_statement":"return Response(\"Invalid URL\", status=response_status.HTTP_404_NOT_FOUND)","docstring":"Gets the properties of, adds, updates, or removes a demo or\n demos given a GET, POST, PUT or DELETE request respectively.\n\n A GET request also returns all sample_inputs belonging to\n the demo if request parameter id is specified.\n A GET request returns all demo objects in the database if\n both the user_id and id of the demo are not specified.\n\n Keyword arguments:\n user_id (str): The id of the user\n id (str): The id of the demo","docstring_summary":"Gets the properties of, adds, updates, or removes a demo or\n demos given a GET, POST, PUT or DELETE request respectively.","docstring_tokens":["Gets","the","properties","of","adds","updates","or","removes","a","demo","or","demos","given","a","GET","POST","PUT","or","DELETE","request","respectively","."],"function":"def custom_demo_controller(request, user_id, id):\n \"\"\"\n Gets the properties of, adds, updates, or removes a demo or\n demos given a GET, POST, PUT or DELETE request respectively.\n\n A GET request also returns all sample_inputs belonging to\n the demo if request parameter id is specified.\n A GET request returns all demo objects in the database if\n both the user_id and id of the demo are not specified.\n\n Keyword arguments:\n user_id (str): The id of the user\n id (str): The id of the demo\n \"\"\"\n if request.method == \"GET\":\n if id and user_id:\n try:\n demo = Demo.objects.get(id=id, user_id=user_id)\n except Exception:\n return Response({\"text\": \"Not Found\"})\n serialize = DemoSerializer(demo).data\n try:\n sample_inputs = SampleInput.objects.filter(demo=demo)\n except Exception:\n sample_inputs = None\n if sample_inputs:\n sample_inputs_serialize = SampleInputSerializer(sample_inputs, many=True).data\n serialize[\"sampleinput\"] = sample_inputs_serialize\n return Response([serialize], status=response_status.HTTP_200_OK)\n elif user_id and not id:\n demos = Demo.objects.filter(user_id=user_id)\n serialize = DemoSerializer(demos, many=True)\n return Response(serialize.data, status=response_status.HTTP_200_OK)\n else:\n demos = Demo.objects.all()\n serialize = DemoSerializer(demos, many=True)\n data = serialize.data\n for x in range(len(demos)):\n data[x][\"username\"] = User.objects.get(id=data[x][\"user_id\"]).username\n return Response(data, status=response_status.HTTP_200_OK)\n elif request.method == \"POST\":\n body = request.data\n name = body[\"name\"]\n id = body[\"id\"]\n user_id = body[\"user_id\"]\n address = body[\"address\"]\n description = body[\"description\"]\n footer_message = body[\"footer_message\"]\n cover_image = body[\"cover_image\"]\n if not cover_image:\n cover_image = DEFAULT_IMAGE\n terminal = body[\"terminal\"]\n timestamp = body[\"timestamp\"]\n token = body[\"token\"]\n status = body[\"status\"]\n demo = Demo.objects.create(\n name=name,\n id=id,\n user_id=user_id,\n address=address,\n description=description,\n footer_message=footer_message,\n cover_image=cover_image,\n terminal=terminal,\n timestamp=timestamp,\n token=token,\n status=status)\n serialize = DemoSerializer(demo)\n return Response(serialize.data, status=response_status.HTTP_201_CREATED)\n\n elif request.method == \"PUT\":\n if id and user_id:\n body = request.data\n demo = Demo.objects.get(id=id, user_id=user_id)\n demo.name = body[\"name\"]\n demo.address = body[\"address\"]\n demo.description = body[\"description\"]\n demo.footer_message = body[\"footer_message\"]\n if not body[\"cover_image\"]:\n demo.cover_image = DEFAULT_IMAGE\n else:\n demo.cover_image = body[\"cover_image\"]\n demo.terminal = body[\"terminal\"]\n demo.token = body[\"token\"]\n demo.status = body[\"status\"]\n demo.save()\n serialize = DemoSerializer(demo)\n return Response(serialize.data, status=response_status.HTTP_200_OK)\n else:\n return Response(\"Invalid URL\", status=response_status.HTTP_404_NOT_FOUND)\n\n elif request.method == \"DELETE\":\n if user_id and id:\n Demo.objects.get(id=id, user_id=user_id).delete()\n return Response({\"removed\": True}, status=response_status.HTTP_200_OK)\n else:\n return Response(\"Invalid URL\", status=response_status.HTTP_404_NOT_FOUND)\n return Response(\"Invalid URL\", status=response_status.HTTP_404_NOT_FOUND)","function_tokens":["def","custom_demo_controller","(","request",",","user_id",",","id",")",":","if","request",".","method","==","\"GET\"",":","if","id","and","user_id",":","try",":","demo","=","Demo",".","objects",".","get","(","id","=","id",",","user_id","=","user_id",")","except","Exception",":","return","Response","(","{","\"text\"",":","\"Not Found\"","}",")","serialize","=","DemoSerializer","(","demo",")",".","data","try",":","sample_inputs","=","SampleInput",".","objects",".","filter","(","demo","=","demo",")","except","Exception",":","sample_inputs","=","None","if","sample_inputs",":","sample_inputs_serialize","=","SampleInputSerializer","(","sample_inputs",",","many","=","True",")",".","data","serialize","[","\"sampleinput\"","]","=","sample_inputs_serialize","return","Response","(","[","serialize","]",",","status","=","response_status",".","HTTP_200_OK",")","elif","user_id","and","not","id",":","demos","=","Demo",".","objects",".","filter","(","user_id","=","user_id",")","serialize","=","DemoSerializer","(","demos",",","many","=","True",")","return","Response","(","serialize",".","data",",","status","=","response_status",".","HTTP_200_OK",")","else",":","demos","=","Demo",".","objects",".","all","(",")","serialize","=","DemoSerializer","(","demos",",","many","=","True",")","data","=","serialize",".","data","for","x","in","range","(","len","(","demos",")",")",":","data","[","x","]","[","\"username\"","]","=","User",".","objects",".","get","(","id","=","data","[","x","]","[","\"user_id\"","]",")",".","username","return","Response","(","data",",","status","=","response_status",".","HTTP_200_OK",")","elif","request",".","method","==","\"POST\"",":","body","=","request",".","data","name","=","body","[","\"name\"","]","id","=","body","[","\"id\"","]","user_id","=","body","[","\"user_id\"","]","address","=","body","[","\"address\"","]","description","=","body","[","\"description\"","]","footer_message","=","body","[","\"footer_message\"","]","cover_image","=","body","[","\"cover_image\"","]","if","not","cover_image",":","cover_image","=","DEFAULT_IMAGE","terminal","=","body","[","\"terminal\"","]","timestamp","=","body","[","\"timestamp\"","]","token","=","body","[","\"token\"","]","status","=","body","[","\"status\"","]","demo","=","Demo",".","objects",".","create","(","name","=","name",",","id","=","id",",","user_id","=","user_id",",","address","=","address",",","description","=","description",",","footer_message","=","footer_message",",","cover_image","=","cover_image",",","terminal","=","terminal",",","timestamp","=","timestamp",",","token","=","token",",","status","=","status",")","serialize","=","DemoSerializer","(","demo",")","return","Response","(","serialize",".","data",",","status","=","response_status",".","HTTP_201_CREATED",")","elif","request",".","method","==","\"PUT\"",":","if","id","and","user_id",":","body","=","request",".","data","demo","=","Demo",".","objects",".","get","(","id","=","id",",","user_id","=","user_id",")","demo",".","name","=","body","[","\"name\"","]","demo",".","address","=","body","[","\"address\"","]","demo",".","description","=","body","[","\"description\"","]","demo",".","footer_message","=","body","[","\"footer_message\"","]","if","not","body","[","\"cover_image\"","]",":","demo",".","cover_image","=","DEFAULT_IMAGE","else",":","demo",".","cover_image","=","body","[","\"cover_image\"","]","demo",".","terminal","=","body","[","\"terminal\"","]","demo",".","token","=","body","[","\"token\"","]","demo",".","status","=","body","[","\"status\"","]","demo",".","save","(",")","serialize","=","DemoSerializer","(","demo",")","return","Response","(","serialize",".","data",",","status","=","response_status",".","HTTP_200_OK",")","else",":","return","Response","(","\"Invalid URL\"",",","status","=","response_status",".","HTTP_404_NOT_FOUND",")","elif","request",".","method","==","\"DELETE\"",":","if","user_id","and","id",":","Demo",".","objects",".","get","(","id","=","id",",","user_id","=","user_id",")",".","delete","(",")","return","Response","(","{","\"removed\"",":","True","}",",","status","=","response_status",".","HTTP_200_OK",")","else",":","return","Response","(","\"Invalid URL\"",",","status","=","response_status",".","HTTP_404_NOT_FOUND",")","return","Response","(","\"Invalid URL\"",",","status","=","response_status",".","HTTP_404_NOT_FOUND",")"],"url":"https:\/\/github.com\/Cloud-CV\/Origami\/blob\/8046898c1afdcc0d32ac3c4a0909f63e2133c3a0\/api\/views.py#L292-L389"}
8
+ {"nwo":"Cloud-CV\/Origami","sha":"8046898c1afdcc0d32ac3c4a0909f63e2133c3a0","path":"api\/views.py","language":"python","identifier":"get_permalink","parameters":"(request, shorturl)","argument_list":"","return_statement":"return Response([serialize.data], status=response_status.HTTP_200_OK)","docstring":"Returns the permalink corresponding to the given shorturl.","docstring_summary":"Returns the permalink corresponding to the given shorturl.","docstring_tokens":["Returns","the","permalink","corresponding","to","the","given","shorturl","."],"function":"def get_permalink(request, shorturl):\n \"\"\"Returns the permalink corresponding to the given shorturl.\"\"\"\n try:\n permalink = Permalink.objects.get(short_relative_url='\/p\/' + shorturl)\n\n except Exception:\n return Response({\"text\": \"Not Found\"})\n\n permalink.short_relative_url = permalink.short_relative_url.split('\/')[-1]\n serialize = PermalinkSerializer(permalink)\n return Response([serialize.data], status=response_status.HTTP_200_OK)","function_tokens":["def","get_permalink","(","request",",","shorturl",")",":","try",":","permalink","=","Permalink",".","objects",".","get","(","short_relative_url","=","'\/p\/'","+","shorturl",")","except","Exception",":","return","Response","(","{","\"text\"",":","\"Not Found\"","}",")","permalink",".","short_relative_url","=","permalink",".","short_relative_url",".","split","(","'\/'",")","[","-","1","]","serialize","=","PermalinkSerializer","(","permalink",")","return","Response","(","[","serialize",".","data","]",",","status","=","response_status",".","HTTP_200_OK",")"],"url":"https:\/\/github.com\/Cloud-CV\/Origami\/blob\/8046898c1afdcc0d32ac3c4a0909f63e2133c3a0\/api\/views.py#L393-L403"}
9
+ {"nwo":"Cloud-CV\/Origami","sha":"8046898c1afdcc0d32ac3c4a0909f63e2133c3a0","path":"api\/views.py","language":"python","identifier":"custom_permalink_controller","parameters":"(request, user_id, project_id)","argument_list":"","return_statement":"return Response(\"Invalid URL\", status=response_status.HTTP_404_NOT_FOUND)","docstring":"Gets properties of, adds, updates, or deletes a Permalink\n object given a GET, POST, PUT, or DELETE request respectively.\n\n A GET request returns the Permalink corresponding to the\n given user_id and project_id, if they are both specified.\n A GET request returns all Permalink objects otherwise.\n\n Keyword arguments:\n user_id (str): The id of the user\n project_id (str): The id of the project","docstring_summary":"Gets properties of, adds, updates, or deletes a Permalink\n object given a GET, POST, PUT, or DELETE request respectively.","docstring_tokens":["Gets","properties","of","adds","updates","or","deletes","a","Permalink","object","given","a","GET","POST","PUT","or","DELETE","request","respectively","."],"function":"def custom_permalink_controller(request, user_id, project_id):\n \"\"\"\n Gets properties of, adds, updates, or deletes a Permalink\n object given a GET, POST, PUT, or DELETE request respectively.\n\n A GET request returns the Permalink corresponding to the\n given user_id and project_id, if they are both specified.\n A GET request returns all Permalink objects otherwise.\n\n Keyword arguments:\n user_id (str): The id of the user\n project_id (str): The id of the project\n \"\"\"\n if request.method == \"GET\":\n if user_id and project_id:\n try:\n permalink = Permalink.objects.get(project_id=project_id, user_id=user_id)\n\n except Exception:\n return Response({\"text\": \"Not Found\"})\n serialize = PermalinkSerializer(permalink)\n return Response(serialize.data, status=response_status.HTTP_200_OK)\n else:\n try:\n permalinks = Permalink.objects.all()\n\n except Exception:\n return Response({\"text\": \"Not Found\"})\n serialize = PermalinkSerializer(permalinks, many=True)\n return Response(serialize.data, status=response_status.HTTP_200_OK)\n\n elif request.method == \"POST\":\n body = request.data\n short_relative_url = body[\"short_relative_url\"]\n full_relative_url = body[\"full_relative_url\"]\n project_id = body[\"project_id\"]\n user_id = body[\"user_id\"]\n permalink = Permalink.objects.create(\n short_relative_url=short_relative_url,\n full_relative_url=full_relative_url,\n project_id=project_id,\n user_id=user_id)\n serialize = PermalinkSerializer(permalink)\n return Response(serialize.data, status=response_status.HTTP_201_CREATED)\n\n elif request.method == \"PUT\":\n if user_id and project_id:\n body = request.data\n perm = Permalink.objects.get(user_id=user_id, project_id=project_id)\n perm.short_relative_url = body[\"short_relative_url\"]\n perm.full_relative_url = body[\"full_relative_url\"]\n perm.save()\n serialize = PermalinkSerializer(perm)\n return Response(serialize.data, status=response_status.HTTP_200_OK)\n else:\n return Response(\"Invalid URL\", status=response_status.HTTP_404_NOT_FOUND)\n\n elif request.method == \"DELETE\":\n if user_id and project_id:\n Permalink.objects.get(project_id=project_id, user_id=user_id).delete()\n return Response({\"removed\": True}, status=response_status.HTTP_200_OK)\n else:\n return Response(\"Invalid URL\", status=response_status.HTTP_404_NOT_FOUND)\n return Response(\"Invalid URL\", status=response_status.HTTP_404_NOT_FOUND)","function_tokens":["def","custom_permalink_controller","(","request",",","user_id",",","project_id",")",":","if","request",".","method","==","\"GET\"",":","if","user_id","and","project_id",":","try",":","permalink","=","Permalink",".","objects",".","get","(","project_id","=","project_id",",","user_id","=","user_id",")","except","Exception",":","return","Response","(","{","\"text\"",":","\"Not Found\"","}",")","serialize","=","PermalinkSerializer","(","permalink",")","return","Response","(","serialize",".","data",",","status","=","response_status",".","HTTP_200_OK",")","else",":","try",":","permalinks","=","Permalink",".","objects",".","all","(",")","except","Exception",":","return","Response","(","{","\"text\"",":","\"Not Found\"","}",")","serialize","=","PermalinkSerializer","(","permalinks",",","many","=","True",")","return","Response","(","serialize",".","data",",","status","=","response_status",".","HTTP_200_OK",")","elif","request",".","method","==","\"POST\"",":","body","=","request",".","data","short_relative_url","=","body","[","\"short_relative_url\"","]","full_relative_url","=","body","[","\"full_relative_url\"","]","project_id","=","body","[","\"project_id\"","]","user_id","=","body","[","\"user_id\"","]","permalink","=","Permalink",".","objects",".","create","(","short_relative_url","=","short_relative_url",",","full_relative_url","=","full_relative_url",",","project_id","=","project_id",",","user_id","=","user_id",")","serialize","=","PermalinkSerializer","(","permalink",")","return","Response","(","serialize",".","data",",","status","=","response_status",".","HTTP_201_CREATED",")","elif","request",".","method","==","\"PUT\"",":","if","user_id","and","project_id",":","body","=","request",".","data","perm","=","Permalink",".","objects",".","get","(","user_id","=","user_id",",","project_id","=","project_id",")","perm",".","short_relative_url","=","body","[","\"short_relative_url\"","]","perm",".","full_relative_url","=","body","[","\"full_relative_url\"","]","perm",".","save","(",")","serialize","=","PermalinkSerializer","(","perm",")","return","Response","(","serialize",".","data",",","status","=","response_status",".","HTTP_200_OK",")","else",":","return","Response","(","\"Invalid URL\"",",","status","=","response_status",".","HTTP_404_NOT_FOUND",")","elif","request",".","method","==","\"DELETE\"",":","if","user_id","and","project_id",":","Permalink",".","objects",".","get","(","project_id","=","project_id",",","user_id","=","user_id",")",".","delete","(",")","return","Response","(","{","\"removed\"",":","True","}",",","status","=","response_status",".","HTTP_200_OK",")","else",":","return","Response","(","\"Invalid URL\"",",","status","=","response_status",".","HTTP_404_NOT_FOUND",")","return","Response","(","\"Invalid URL\"",",","status","=","response_status",".","HTTP_404_NOT_FOUND",")"],"url":"https:\/\/github.com\/Cloud-CV\/Origami\/blob\/8046898c1afdcc0d32ac3c4a0909f63e2133c3a0\/api\/views.py#L407-L470"}
10
+ {"nwo":"Cloud-CV\/Origami","sha":"8046898c1afdcc0d32ac3c4a0909f63e2133c3a0","path":"api\/views.py","language":"python","identifier":"root_settings","parameters":"(request)","argument_list":"","return_statement":"return Response(serialize.data, status=response_status.HTTP_200_OK)","docstring":"A GET request returns the RootSettings object.\n A POST request creates the RootSettings object if there is\n no existent RootSettings object, and updates the existing\n object otherwise.\n\n If a RootSettings object is created, a SocialApp object is\n created as well.","docstring_summary":"A GET request returns the RootSettings object.\n A POST request creates the RootSettings object if there is\n no existent RootSettings object, and updates the existing\n object otherwise.","docstring_tokens":["A","GET","request","returns","the","RootSettings","object",".","A","POST","request","creates","the","RootSettings","object","if","there","is","no","existent","RootSettings","object","and","updates","the","existing","object","otherwise","."],"function":"def root_settings(request):\n \"\"\"\n A GET request returns the RootSettings object.\n A POST request creates the RootSettings object if there is\n no existent RootSettings object, and updates the existing\n object otherwise.\n\n If a RootSettings object is created, a SocialApp object is\n created as well.\n \"\"\"\n body = request.data\n root = RootSettings.objects.all().first()\n app = SocialApp.objects.all().first()\n if request.method == \"POST\":\n if root and app:\n root.root_user_github_login_id = body[\"root_user_github_login_id\"]\n root.root_user_github_login_name = \\\n body[\"root_user_github_login_name\"]\n root.client_id = body[\"client_id\"]\n root.client_secret = body[\"client_secret\"]\n root.is_cloudcv = body[\"is_cloudcv\"]\n root.allow_new_logins = body[\"allow_new_logins\"]\n root.app_ip = body[\"app_ip\"]\n root.port = body[\"port\"]\n root.save()\n app.client_id = body[\"client_id\"]\n app.secret = body[\"client_secret\"]\n app.save()\n else:\n root = RootSettings.objects.create(\n root_user_github_login_id=body[\"root_user_github_login_id\"],\n root_user_github_login_name=body[\"root_user_github_login_name\"],\n client_id=body[\"client_id\"],\n client_secret=body[\"client_secret\"],\n is_cloudcv=body[\"is_cloudcv\"],\n allow_new_logins=body[\"allow_new_logins\"],\n app_ip=body[\"app_ip\"],\n port=body[\"port\"])\n app = SocialApp.objects.create(\n provider=u'github',\n name=str(datetime.datetime.now().isoformat()),\n client_id=body[\"client_id\"],\n secret=body[\"client_secret\"])\n site = Site.objects.get(id=1)\n app.sites.add(site)\n app.save()\n serialize = RootSettingsSerializer(root)\n return Response(serialize.data, status=response_status.HTTP_200_OK)","function_tokens":["def","root_settings","(","request",")",":","body","=","request",".","data","root","=","RootSettings",".","objects",".","all","(",")",".","first","(",")","app","=","SocialApp",".","objects",".","all","(",")",".","first","(",")","if","request",".","method","==","\"POST\"",":","if","root","and","app",":","root",".","root_user_github_login_id","=","body","[","\"root_user_github_login_id\"","]","root",".","root_user_github_login_name","=","body","[","\"root_user_github_login_name\"","]","root",".","client_id","=","body","[","\"client_id\"","]","root",".","client_secret","=","body","[","\"client_secret\"","]","root",".","is_cloudcv","=","body","[","\"is_cloudcv\"","]","root",".","allow_new_logins","=","body","[","\"allow_new_logins\"","]","root",".","app_ip","=","body","[","\"app_ip\"","]","root",".","port","=","body","[","\"port\"","]","root",".","save","(",")","app",".","client_id","=","body","[","\"client_id\"","]","app",".","secret","=","body","[","\"client_secret\"","]","app",".","save","(",")","else",":","root","=","RootSettings",".","objects",".","create","(","root_user_github_login_id","=","body","[","\"root_user_github_login_id\"","]",",","root_user_github_login_name","=","body","[","\"root_user_github_login_name\"","]",",","client_id","=","body","[","\"client_id\"","]",",","client_secret","=","body","[","\"client_secret\"","]",",","is_cloudcv","=","body","[","\"is_cloudcv\"","]",",","allow_new_logins","=","body","[","\"allow_new_logins\"","]",",","app_ip","=","body","[","\"app_ip\"","]",",","port","=","body","[","\"port\"","]",")","app","=","SocialApp",".","objects",".","create","(","provider","=","u'github'",",","name","=","str","(","datetime",".","datetime",".","now","(",")",".","isoformat","(",")",")",",","client_id","=","body","[","\"client_id\"","]",",","secret","=","body","[","\"client_secret\"","]",")","site","=","Site",".","objects",".","get","(","id","=","1",")","app",".","sites",".","add","(","site",")","app",".","save","(",")","serialize","=","RootSettingsSerializer","(","root",")","return","Response","(","serialize",".","data",",","status","=","response_status",".","HTTP_200_OK",")"],"url":"https:\/\/github.com\/Cloud-CV\/Origami\/blob\/8046898c1afdcc0d32ac3c4a0909f63e2133c3a0\/api\/views.py#L474-L521"}
11
+ {"nwo":"Cloud-CV\/Origami","sha":"8046898c1afdcc0d32ac3c4a0909f63e2133c3a0","path":"api\/views.py","language":"python","identifier":"upload_sample_input","parameters":"(request)","argument_list":"","return_statement":"return Response(serialize.data, status=response_status.HTTP_200_OK)","docstring":"Creates a sample input. Only image input is supported currently.\n\n The data passed into the POST request needs to contain:\n demo_id (str): The demo that the sample input should belong to.\n sample-image-* (file): A value with its key having 'sample-image'\n as a prefix, containing the image file.","docstring_summary":"Creates a sample input. Only image input is supported currently.","docstring_tokens":["Creates","a","sample","input",".","Only","image","input","is","supported","currently","."],"function":"def upload_sample_input(request):\n \"\"\"\n Creates a sample input. Only image input is supported currently.\n\n The data passed into the POST request needs to contain:\n demo_id (str): The demo that the sample input should belong to.\n sample-image-* (file): A value with its key having 'sample-image'\n as a prefix, containing the image file.\n \"\"\"\n data = request.data\n demo_id = data[\"demo_id\"]\n demo = Demo.objects.get(id=demo_id)\n for key, value in data.items():\n if key.startswith(\"sample-image\"):\n img = request.FILES[key]\n absolute_path = default_storage.save(settings.MEDIA_ROOT, ContentFile(img.read()))\n relative_path = '\/media\/' + absolute_path.split('media\/')[-1]\n sample_input = SampleInput.objects.create(demo=demo, type_of_input=3, value=relative_path)\n serialize = SampleInputSerializer(sample_input)\n if (\"test\" in sys.argv):\n os.remove(absolute_path)\n sample_inputs = SampleInput.objects.filter(demo=demo)\n serialize = SampleInputSerializer(sample_inputs, many=True)\n return Response(serialize.data, status=response_status.HTTP_200_OK)","function_tokens":["def","upload_sample_input","(","request",")",":","data","=","request",".","data","demo_id","=","data","[","\"demo_id\"","]","demo","=","Demo",".","objects",".","get","(","id","=","demo_id",")","for","key",",","value","in","data",".","items","(",")",":","if","key",".","startswith","(","\"sample-image\"",")",":","img","=","request",".","FILES","[","key","]","absolute_path","=","default_storage",".","save","(","settings",".","MEDIA_ROOT",",","ContentFile","(","img",".","read","(",")",")",")","relative_path","=","'\/media\/'","+","absolute_path",".","split","(","'media\/'",")","[","-","1","]","sample_input","=","SampleInput",".","objects",".","create","(","demo","=","demo",",","type_of_input","=","3",",","value","=","relative_path",")","serialize","=","SampleInputSerializer","(","sample_input",")","if","(","\"test\"","in","sys",".","argv",")",":","os",".","remove","(","absolute_path",")","sample_inputs","=","SampleInput",".","objects",".","filter","(","demo","=","demo",")","serialize","=","SampleInputSerializer","(","sample_inputs",",","many","=","True",")","return","Response","(","serialize",".","data",",","status","=","response_status",".","HTTP_200_OK",")"],"url":"https:\/\/github.com\/Cloud-CV\/Origami\/blob\/8046898c1afdcc0d32ac3c4a0909f63e2133c3a0\/api\/views.py#L525-L548"}
Codility__cui.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ {"nwo":"Codility\/cui","sha":"48c6ee99f054dc1e33789723c03ae2d81bc54c87","path":"views.py","language":"python","identifier":"cui_sandbox","parameters":"(request)","argument_list":"","return_statement":"return render_cui({\n 'in_local': True,\n 'title': 'CUI sandbox'\n }, template='cui\/sandbox.html')","docstring":"Scaffolding to test various components of CUI.","docstring_summary":"Scaffolding to test various components of CUI.","docstring_tokens":["Scaffolding","to","test","various","components","of","CUI","."],"function":"def cui_sandbox(request):\n '''Scaffolding to test various components of CUI.'''\n return render_cui({\n 'in_local': True,\n 'title': 'CUI sandbox'\n }, template='cui\/sandbox.html')","function_tokens":["def","cui_sandbox","(","request",")",":","return","render_cui","(","{","'in_local'",":","True",",","'title'",":","'CUI sandbox'","}",",","template","=","'cui\/sandbox.html'",")"],"url":"https:\/\/github.com\/Codility\/cui\/blob\/48c6ee99f054dc1e33789723c03ae2d81bc54c87\/views.py#L35-L40"}
2
+ {"nwo":"Codility\/cui","sha":"48c6ee99f054dc1e33789723c03ae2d81bc54c87","path":"views.py","language":"python","identifier":"cui_test","parameters":"(request)","argument_list":"","return_statement":"return render_cui({\n 'in_test': True,\n 'title': 'CUI tests'\n })","docstring":"Scaffolding for candidate interface JS tests.","docstring_summary":"Scaffolding for candidate interface JS tests.","docstring_tokens":["Scaffolding","for","candidate","interface","JS","tests","."],"function":"def cui_test(request):\n '''Scaffolding for candidate interface JS tests.'''\n\n return render_cui({\n 'in_test': True,\n 'title': 'CUI tests'\n })","function_tokens":["def","cui_test","(","request",")",":","return","render_cui","(","{","'in_test'",":","True",",","'title'",":","'CUI tests'","}",")"],"url":"https:\/\/github.com\/Codility\/cui\/blob\/48c6ee99f054dc1e33789723c03ae2d81bc54c87\/views.py#L42-L48"}
3
+ {"nwo":"Codility\/cui","sha":"48c6ee99f054dc1e33789723c03ae2d81bc54c87","path":"views.py","language":"python","identifier":"cui_local","parameters":"(request)","argument_list":"","return_statement":"return render_cui({\n 'in_local': True,\n 'title': 'CUI'\n })","docstring":"Scaffolding for candidate interface with mock local server.","docstring_summary":"Scaffolding for candidate interface with mock local server.","docstring_tokens":["Scaffolding","for","candidate","interface","with","mock","local","server","."],"function":"def cui_local(request):\n '''Scaffolding for candidate interface with mock local server.'''\n\n return render_cui({\n 'in_local': True,\n 'title': 'CUI'\n })","function_tokens":["def","cui_local","(","request",")",":","return","render_cui","(","{","'in_local'",":","True",",","'title'",":","'CUI'","}",")"],"url":"https:\/\/github.com\/Codility\/cui\/blob\/48c6ee99f054dc1e33789723c03ae2d81bc54c87\/views.py#L50-L56"}
Crapworks__ceph-dash.jsonl ADDED
@@ -0,0 +1,2 @@
 
 
1
+ {"nwo":"Crapworks\/ceph-dash","sha":"216aed2769894b8caa6513997966445167fa56e4","path":"app\/dashboard\/views.py","language":"python","identifier":"find_host_for_osd","parameters":"(osd, osd_status)","argument_list":"","return_statement":"return 'unknown'","docstring":"find host for a given osd","docstring_summary":"find host for a given osd","docstring_tokens":["find","host","for","a","given","osd"],"function":"def find_host_for_osd(osd, osd_status):\n \"\"\" find host for a given osd \"\"\"\n\n for obj in osd_status['nodes']:\n if obj['type'] == 'host':\n if osd in obj['children']:\n return obj['name']\n\n return 'unknown'","function_tokens":["def","find_host_for_osd","(","osd",",","osd_status",")",":","for","obj","in","osd_status","[","'nodes'","]",":","if","obj","[","'type'","]","==","'host'",":","if","osd","in","obj","[","'children'","]",":","return","obj","[","'name'","]","return","'unknown'"],"url":"https:\/\/github.com\/Crapworks\/ceph-dash\/blob\/216aed2769894b8caa6513997966445167fa56e4\/app\/dashboard\/views.py#L54-L62"}
2
+ {"nwo":"Crapworks\/ceph-dash","sha":"216aed2769894b8caa6513997966445167fa56e4","path":"app\/dashboard\/views.py","language":"python","identifier":"get_unhealthy_osd_details","parameters":"(osd_status)","argument_list":"","return_statement":"return unhealthy_osds","docstring":"get all unhealthy osds from osd status","docstring_summary":"get all unhealthy osds from osd status","docstring_tokens":["get","all","unhealthy","osds","from","osd","status"],"function":"def get_unhealthy_osd_details(osd_status):\n \"\"\" get all unhealthy osds from osd status \"\"\"\n\n unhealthy_osds = list()\n\n for obj in osd_status['nodes']:\n if obj['type'] == 'osd':\n # if OSD does not exists (DNE in osd tree) skip this entry\n if obj['exists'] == 0:\n continue\n if obj['status'] == 'down' or obj['reweight'] == 0.0:\n # It is possible to have one host in more than one branch in the tree.\n # Add each unhealthy OSD only once in the list\n if obj['status'] == 'down':\n status = 'down'\n else:\n status = 'out'\n entry = {\n 'name': obj['name'],\n 'status': status,\n 'host': find_host_for_osd(obj['id'], osd_status)\n }\n if entry not in unhealthy_osds:\n unhealthy_osds.append(entry)\n\n return unhealthy_osds","function_tokens":["def","get_unhealthy_osd_details","(","osd_status",")",":","unhealthy_osds","=","list","(",")","for","obj","in","osd_status","[","'nodes'","]",":","if","obj","[","'type'","]","==","'osd'",":","# if OSD does not exists (DNE in osd tree) skip this entry","if","obj","[","'exists'","]","==","0",":","continue","if","obj","[","'status'","]","==","'down'","or","obj","[","'reweight'","]","==","0.0",":","# It is possible to have one host in more than one branch in the tree.","# Add each unhealthy OSD only once in the list","if","obj","[","'status'","]","==","'down'",":","status","=","'down'","else",":","status","=","'out'","entry","=","{","'name'",":","obj","[","'name'","]",",","'status'",":","status",",","'host'",":","find_host_for_osd","(","obj","[","'id'","]",",","osd_status",")","}","if","entry","not","in","unhealthy_osds",":","unhealthy_osds",".","append","(","entry",")","return","unhealthy_osds"],"url":"https:\/\/github.com\/Crapworks\/ceph-dash\/blob\/216aed2769894b8caa6513997966445167fa56e4\/app\/dashboard\/views.py#L65-L90"}
Creditas__challenge.jsonl ADDED
@@ -0,0 +1,2 @@
 
 
1
+ {"nwo":"Creditas\/challenge","sha":"2afd1c67fd572a5f3176d20e72ef4557cff1e557","path":"analytics-data-development\/Connection.py","language":"python","identifier":"Connection.create_conecction","parameters":"(db_file)","argument_list":"","return_statement":"return conn","docstring":"Creates a conection on the SQLite database\n :param db_file: Database name","docstring_summary":"Creates a conection on the SQLite database\n :param db_file: Database name","docstring_tokens":["Creates","a","conection","on","the","SQLite","database",":","param","db_file",":","Database","name"],"function":"def create_conecction(db_file):\n \"\"\" Creates a conection on the SQLite database\n :param db_file: Database name\n \"\"\"\n conn = None\n try:\n conn = sqlite3.connect(db_file)\n print('Database created')\n except Error as e:\n print(e)\n return conn","function_tokens":["def","create_conecction","(","db_file",")",":","conn","=","None","try",":","conn","=","sqlite3",".","connect","(","db_file",")","print","(","'Database created'",")","except","Error","as","e",":","print","(","e",")","return","conn"],"url":"https:\/\/github.com\/Creditas\/challenge\/blob\/2afd1c67fd572a5f3176d20e72ef4557cff1e557\/analytics-data-development\/Connection.py#L6-L16"}
2
+ {"nwo":"Creditas\/challenge","sha":"2afd1c67fd572a5f3176d20e72ef4557cff1e557","path":"analytics-data-development\/Connection.py","language":"python","identifier":"Connection.execute","parameters":"(self, conn, sql)","argument_list":"","return_statement":"","docstring":"Executes a command with a cursor\n :param conn: Connection object\n :param sql: SQL command","docstring_summary":"Executes a command with a cursor\n :param conn: Connection object\n :param sql: SQL command","docstring_tokens":["Executes","a","command","with","a","cursor",":","param","conn",":","Connection","object",":","param","sql",":","SQL","command"],"function":"def execute(self, conn, sql):\n \"\"\" Executes a command with a cursor\n :param conn: Connection object\n :param sql: SQL command\n \"\"\"\n try:\n c = conn.cursor()\n c.execute(sql)\n except Error as e:\n print(e)","function_tokens":["def","execute","(","self",",","conn",",","sql",")",":","try",":","c","=","conn",".","cursor","(",")","c",".","execute","(","sql",")","except","Error","as","e",":","print","(","e",")"],"url":"https:\/\/github.com\/Creditas\/challenge\/blob\/2afd1c67fd572a5f3176d20e72ef4557cff1e557\/analytics-data-development\/Connection.py#L18-L27"}
DFIRKuiper__Kuiper.jsonl ADDED
The diff for this file is too large to render. See raw diff
DaoCloud__daochain.jsonl ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/hubclient.py","language":"python","identifier":"Client.orgs","parameters":"(self)","argument_list":"","return_statement":"return orgs","docstring":":rtype: list(dict)","docstring_summary":":rtype: list(dict)","docstring_tokens":[":","rtype",":","list","(","dict",")"],"function":"def orgs(self):\n \"\"\"\n :rtype: list(dict)\n \"\"\"\n orgs = []\n for t in self.token_info['user']['tenants']:\n if t['is_org']:\n orgs.append(t)\n return orgs","function_tokens":["def","orgs","(","self",")",":","orgs","=","[","]","for","t","in","self",".","token_info","[","'user'","]","[","'tenants'","]",":","if","t","[","'is_org'","]",":","orgs",".","append","(","t",")","return","orgs"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/hubclient.py#L90-L98"}
2
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/utils.py","language":"python","identifier":"print_dict","parameters":"(d, prefix='')","argument_list":"","return_statement":"","docstring":":type d: dict","docstring_summary":":type d: dict","docstring_tokens":[":","type","d",":","dict"],"function":"def print_dict(d, prefix=''):\n \"\"\"\n :type d: dict\n \"\"\"\n for k, v in d.items():\n if isinstance(v, dict):\n print('%s%s:' % (prefix, k))\n print_dict(v, prefix + ' ' * 4)\n else:\n print('%s%s = %s' % (prefix, k, v))","function_tokens":["def","print_dict","(","d",",","prefix","=","''",")",":","for","k",",","v","in","d",".","items","(",")",":","if","isinstance","(","v",",","dict",")",":","print","(","'%s%s:'","%","(","prefix",",","k",")",")","print_dict","(","v",",","prefix","+","' '","*","4",")","else",":","print","(","'%s%s = %s'","%","(","prefix",",","k",",","v",")",")"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/utils.py#L38-L47"}
3
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/main.py","language":"python","identifier":"TopLevelCommand.version","parameters":"(self, options)","argument_list":"","return_statement":"","docstring":"Show the version information\n\n Usage: version","docstring_summary":"Show the version information","docstring_tokens":["Show","the","version","information"],"function":"def version(self, options):\n \"\"\"\n Show the version information\n\n Usage: version\n \"\"\"\n print('v0.1')","function_tokens":["def","version","(","self",",","options",")",":","print","(","'v0.1'",")"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/main.py#L58-L64"}
4
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/main.py","language":"python","identifier":"TopLevelCommand.login","parameters":"(self, options)","argument_list":"","return_statement":"","docstring":"Login to daolcoud daohub","docstring_summary":"Login to daolcoud daohub","docstring_tokens":["Login","to","daolcoud","daohub"],"function":"def login(self, options):\n \"\"\"\n Login to daolcoud daohub\n \"\"\"\n pass","function_tokens":["def","login","(","self",",","options",")",":","pass"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/main.py#L66-L70"}
5
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/main.py","language":"python","identifier":"TopLevelCommand.list","parameters":"(self, options)","argument_list":"","return_statement":"","docstring":"List local images and their verify stats.","docstring_summary":"List local images and their verify stats.","docstring_tokens":["List","local","images","and","their","verify","stats","."],"function":"def list(self, options):\n \"\"\"\n List local images and their verify stats.\n\n \"\"\"\n pass","function_tokens":["def","list","(","self",",","options",")",":","pass"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/main.py#L72-L77"}
6
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/blockchain.py","language":"python","identifier":"DaoHubVerify.regImage","parameters":"(self, callback)","argument_list":"","return_statement":"","docstring":"callback receive a dict:\n [{'address': u'0x8a1e16278f7695823962ada686ca13a202ee97d1',\n 'args': {u'imageHash': u'123123da\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00',\n u'imageId': u'123123\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00',\n u'owner': u'0x79eacb37490b7aa319b0bc405f2110c3b36259a9',\n u'repoTag': u'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x80'},\n 'blockHash': u'0x61cb83263400c11477edfcbaf637e55910038865b80009082b51460e38aa13fc',\n 'blockNumber': 8,\n 'event': u'regImage',\n 'logIndex': 0,\n 'transactionHash': u'0xfe0309c12fe33ce1b6c79bd6c5045e9ca16ae0d3d0799db86f2f5f90d44f4862',\n 'transactionIndex': 0}]","docstring_summary":"callback receive a dict:\n [{'address': u'0x8a1e16278f7695823962ada686ca13a202ee97d1',\n 'args': {u'imageHash': u'123123da\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00',\n u'imageId': u'123123\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00',\n u'owner': u'0x79eacb37490b7aa319b0bc405f2110c3b36259a9',\n u'repoTag': u'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x80'},\n 'blockHash': u'0x61cb83263400c11477edfcbaf637e55910038865b80009082b51460e38aa13fc',\n 'blockNumber': 8,\n 'event': u'regImage',\n 'logIndex': 0,\n 'transactionHash': u'0xfe0309c12fe33ce1b6c79bd6c5045e9ca16ae0d3d0799db86f2f5f90d44f4862',\n 'transactionIndex': 0}]","docstring_tokens":["callback","receive","a","dict",":","[","{","address",":","u","0x8a1e16278f7695823962ada686ca13a202ee97d1","args",":","{","u","imageHash",":","u","123123da","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","u","imageId",":","u","123123","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","u","owner",":","u","0x79eacb37490b7aa319b0bc405f2110c3b36259a9","u","repoTag",":","u","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x00","\\","x80","}","blockHash",":","u","0x61cb83263400c11477edfcbaf637e55910038865b80009082b51460e38aa13fc","blockNumber",":","8","event",":","u","regImage","logIndex",":","0","transactionHash",":","u","0xfe0309c12fe33ce1b6c79bd6c5045e9ca16ae0d3d0799db86f2f5f90d44f4862","transactionIndex",":","0","}","]"],"function":"def regImage(self, callback):\n \"\"\"\n callback receive a dict:\n [{'address': u'0x8a1e16278f7695823962ada686ca13a202ee97d1',\n 'args': {u'imageHash': u'123123da\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00',\n u'imageId': u'123123\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00',\n u'owner': u'0x79eacb37490b7aa319b0bc405f2110c3b36259a9',\n u'repoTag': u'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x80'},\n 'blockHash': u'0x61cb83263400c11477edfcbaf637e55910038865b80009082b51460e38aa13fc',\n 'blockNumber': 8,\n 'event': u'regImage',\n 'logIndex': 0,\n 'transactionHash': u'0xfe0309c12fe33ce1b6c79bd6c5045e9ca16ae0d3d0799db86f2f5f90d44f4862',\n 'transactionIndex': 0}]\n \"\"\"\n self.trans_filter.watch(callback)","function_tokens":["def","regImage","(","self",",","callback",")",":","self",".","trans_filter",".","watch","(","callback",")"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/blockchain.py#L59-L74"}
7
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py","language":"python","identifier":"mean","parameters":"(data)","argument_list":"","return_statement":"return sum(data) \/ float(n)","docstring":"Return the arithmetic mean of data","docstring_summary":"Return the arithmetic mean of data","docstring_tokens":["Return","the","arithmetic","mean","of","data"],"function":"def mean(data):\n \"\"\"\n Return the arithmetic mean of data\n \"\"\"\n n = len(data)\n if n < 1:\n return 0\n return sum(data) \/ float(n)","function_tokens":["def","mean","(","data",")",":","n","=","len","(","data",")","if","n","<","1",":","return","0","return","sum","(","data",")","\/","float","(","n",")"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py#L213-L220"}
8
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py","language":"python","identifier":"meanAndStandardDeviation","parameters":"(data)","argument_list":"","return_statement":"","docstring":"Return sum of square deviations of sequence data","docstring_summary":"Return sum of square deviations of sequence data","docstring_tokens":["Return","sum","of","square","deviations","of","sequence","data"],"function":"def meanAndStandardDeviation(data):\n \"\"\"\n Return sum of square deviations of sequence data\n \"\"\"\n c = mean(data)\n ss = sum((x - c) ** 2 for x in data)\n if abs(ss) < 1e-10:\n return c, 1.0\n else:\n return c, sqrt(ss \/ float(len(data)))","function_tokens":["def","meanAndStandardDeviation","(","data",")",":","c","=","mean","(","data",")","ss","=","sum","(","(","x","-","c",")","**","2","for","x","in","data",")","if","abs","(","ss",")","<","1e-10",":","return","c",",","1.0","else",":","return","c",",","sqrt","(","ss","\/","float","(","len","(","data",")",")",")"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py#L223-L232"}
9
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py","language":"python","identifier":"matrixMultiplication","parameters":"(A, B)","argument_list":"","return_statement":"return out","docstring":"return product of matrices A and B\n\n the input are two lists of lists where the sublists of matrix A\n have the length of matrix B","docstring_summary":"return product of matrices A and B","docstring_tokens":["return","product","of","matrices","A","and","B"],"function":"def matrixMultiplication(A, B):\n \"\"\"\n return product of matrices A and B\n\n the input are two lists of lists where the sublists of matrix A\n have the length of matrix B\n \"\"\"\n mA = len(A)\n mB = len(B)\n if mA <= 0:\n return []\n nA = len(A[0])\n if mB != nA:\n raise PolyFitException(\"shapes don't match %d vs %d\" % (nA, mB),\n EXCEPTION_MATRIX_MULTIPLICATION)\n if nA == 0:\n return []\n nB = len(B[0])\n\n for i, b in enumerate(B):\n if len(b) != nB:\n raise PolyFitException(\"matrix B: row %d doesn't match matrix \"\n \"shape (%d vs %d)\" % (i, len(b)),\n EXCEPTION_MATRIX_MULTIPLICATION)\n\n out = [[0.0 for x in range(nB)] for y in range(mA)]\n for row in range(mA):\n for col in range(nB):\n if len(A[row]) != nA:\n raise PolyFitException(\"matrix A: row %d doesn't match \"\n \"matrix shape (%d vs %d)\"\n % (row, nA, len(A[row])),\n EXCEPTION_MATRIX_MULTIPLICATION)\n for i in range(mB):\n out[row][col] += A[row][i] * B[i][col]\n return out","function_tokens":["def","matrixMultiplication","(","A",",","B",")",":","mA","=","len","(","A",")","mB","=","len","(","B",")","if","mA","<=","0",":","return","[","]","nA","=","len","(","A","[","0","]",")","if","mB","!=","nA",":","raise","PolyFitException","(","\"shapes don't match %d vs %d\"","%","(","nA",",","mB",")",",","EXCEPTION_MATRIX_MULTIPLICATION",")","if","nA","==","0",":","return","[","]","nB","=","len","(","B","[","0","]",")","for","i",",","b","in","enumerate","(","B",")",":","if","len","(","b",")","!=","nB",":","raise","PolyFitException","(","\"matrix B: row %d doesn't match matrix \"","\"shape (%d vs %d)\"","%","(","i",",","len","(","b",")",")",",","EXCEPTION_MATRIX_MULTIPLICATION",")","out","=","[","[","0.0","for","x","in","range","(","nB",")","]","for","y","in","range","(","mA",")","]","for","row","in","range","(","mA",")",":","for","col","in","range","(","nB",")",":","if","len","(","A","[","row","]",")","!=","nA",":","raise","PolyFitException","(","\"matrix A: row %d doesn't match \"","\"matrix shape (%d vs %d)\"","%","(","row",",","nA",",","len","(","A","[","row","]",")",")",",","EXCEPTION_MATRIX_MULTIPLICATION",")","for","i","in","range","(","mB",")",":","out","[","row","]","[","col","]","+=","A","[","row","]","[","i","]","*","B","[","i","]","[","col","]","return","out"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py#L235-L270"}
10
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py","language":"python","identifier":"eyeMatrix","parameters":"(m)","argument_list":"","return_statement":"return out","docstring":"return a list of lists which represents the identity matrix of size m","docstring_summary":"return a list of lists which represents the identity matrix of size m","docstring_tokens":["return","a","list","of","lists","which","represents","the","identity","matrix","of","size","m"],"function":"def eyeMatrix(m):\n \"\"\"\n return a list of lists which represents the identity matrix of size m\n \"\"\"\n out = [[0.0 for x in range(m)] for y in range(m)]\n for i in range(m):\n out[i][i] = 1.0\n return out","function_tokens":["def","eyeMatrix","(","m",")",":","out","=","[","[","0.0","for","x","in","range","(","m",")","]","for","y","in","range","(","m",")","]","for","i","in","range","(","m",")",":","out","[","i","]","[","i","]","=","1.0","return","out"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py#L273-L280"}
11
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py","language":"python","identifier":"norm","parameters":"(v)","argument_list":"","return_statement":"","docstring":"compute the square root of the sum of all squared components of a list v","docstring_summary":"compute the square root of the sum of all squared components of a list v","docstring_tokens":["compute","the","square","root","of","the","sum","of","all","squared","components","of","a","list","v"],"function":"def norm(v):\n \"\"\"\n compute the square root of the sum of all squared components of a list v\n \"\"\"\n\n if len(v) == 0:\n return 0\n if isinstance(v[0], list):\n return sqrt(sum([y ** 2.0 for x in v for y in x]))\n else:\n return sqrt(sum([y ** 2.0 for y in v]))","function_tokens":["def","norm","(","v",")",":","if","len","(","v",")","==","0",":","return","0","if","isinstance","(","v","[","0","]",",","list",")",":","return","sqrt","(","sum","(","[","y","**","2.0","for","x","in","v","for","y","in","x","]",")",")","else",":","return","sqrt","(","sum","(","[","y","**","2.0","for","y","in","v","]",")",")"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py#L283-L293"}
12
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py","language":"python","identifier":"elementWise","parameters":"(A, B, operation)","argument_list":"","return_statement":"return [[operation(x, y)\n for x, y in zip(rowA, rowB)]\n for rowA, rowB in zip(A, B)]","docstring":"execute an operate element wise and return result\n\n A and B are lists of lists (all lists of same lengths)\n operation is a function of two arguments and one return value","docstring_summary":"execute an operate element wise and return result","docstring_tokens":["execute","an","operate","element","wise","and","return","result"],"function":"def elementWise(A, B, operation):\n \"\"\"\n execute an operate element wise and return result\n\n A and B are lists of lists (all lists of same lengths)\n operation is a function of two arguments and one return value\n \"\"\"\n return [[operation(x, y)\n for x, y in zip(rowA, rowB)]\n for rowA, rowB in zip(A, B)]","function_tokens":["def","elementWise","(","A",",","B",",","operation",")",":","return","[","[","operation","(","x",",","y",")","for","x",",","y","in","zip","(","rowA",",","rowB",")","]","for","rowA",",","rowB","in","zip","(","A",",","B",")","]"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py#L296-L305"}
13
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py","language":"python","identifier":"transpose","parameters":"(A)","argument_list":"","return_statement":"return out","docstring":"return a list of lists for a Matrix A ( list of lists )\n with transposed representation of A","docstring_summary":"return a list of lists for a Matrix A ( list of lists )\n with transposed representation of A","docstring_tokens":["return","a","list","of","lists","for","a","Matrix","A","(","list","of","lists",")","with","transposed","representation","of","A"],"function":"def transpose(A):\n \"\"\"\n return a list of lists for a Matrix A ( list of lists )\n with transposed representation of A\n \"\"\"\n m = len(A)\n if m == 0:\n return []\n n = len(A[0])\n out = [[0.0 for x in range(m)] for y in range(n)]\n for r in range(m):\n for c in range(n):\n out[c][r] = A[r][c]\n return out","function_tokens":["def","transpose","(","A",")",":","m","=","len","(","A",")","if","m","==","0",":","return","[","]","n","=","len","(","A","[","0","]",")","out","=","[","[","0.0","for","x","in","range","(","m",")","]","for","y","in","range","(","n",")","]","for","r","in","range","(","m",")",":","for","c","in","range","(","n",")",":","out","[","c","]","[","r","]","=","A","[","r","]","[","c","]","return","out"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py#L308-L321"}
14
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py","language":"python","identifier":"qr","parameters":"(A, prec=1e-10)","argument_list":"","return_statement":"return Q, R","docstring":"computes a faster and economic qr decomposition similar to:\n http:\/\/www.iaa.ncku.edu.tw\/~dychiang\/lab\/program\/mohr3d\/source\/Jama%5CQRDecomposition.html","docstring_summary":"computes a faster and economic qr decomposition similar to:\n http:\/\/www.iaa.ncku.edu.tw\/~dychiang\/lab\/program\/mohr3d\/source\/Jama%5CQRDecomposition.html","docstring_tokens":["computes","a","faster","and","economic","qr","decomposition","similar","to",":","http",":","\/\/","www",".","iaa",".","ncku",".","edu",".","tw","\/","~dychiang","\/","lab","\/","program","\/","mohr3d","\/","source","\/","Jama%5CQRDecomposition",".","html"],"function":"def qr(A, prec=1e-10):\n \"\"\"\n computes a faster and economic qr decomposition similar to:\n http:\/\/www.iaa.ncku.edu.tw\/~dychiang\/lab\/program\/mohr3d\/source\/Jama%5CQRDecomposition.html\n \"\"\"\n m = len(A)\n if m <= 0:\n return [], A\n n = len(A[0])\n Rdiag = [0] * n;\n QR = copy.deepcopy(A)\n for k in range(n):\n # Compute 2-norm of k-th column without under\/overflow.\n nrm = 0.0\n for i in range(k, m):\n nrm = sqrt(nrm ** 2 + QR[i][k] ** 2)\n\n if abs(nrm) > prec:\n # Form k-th Householder vector.\n if k < m and QR[k][k] < 0:\n nrm = -nrm\n\n for i in range(k, m):\n QR[i][k] \/= nrm\n if k < m:\n QR[k][k] += 1.0\n\n # Apply transformation to remaining columns.\n for j in range(k + 1, n):\n s = 0.0\n for i in range(k, m):\n s += QR[i][k] * QR[i][j]\n if k < m:\n s = -s \/ QR[k][k]\n for i in range(k, m):\n QR[i][j] += s * QR[i][k]\n Rdiag[k] = -nrm;\n\n # compute R\n R = [[0] * n for z in range(min(m, n))]\n for i in range(m):\n for j in range(i, n):\n if i < j:\n R[i][j] = QR[i][j]\n if i == j:\n R[i][i] = Rdiag[i]\n\n # compute Q\n w = min(m, n)\n Q = [[0] * w for i in range(m)]\n for k in range(w - 1, -1, -1):\n if k < w:\n Q[k][k] = 1.0;\n for j in range(k, w):\n if k < m and abs(QR[k][k]) > prec:\n s = 0.0\n for i in range(k, m):\n s += QR[i][k] * Q[i][j]\n s = -s \/ QR[k][k]\n for i in range(k, m):\n Q[i][j] += s * QR[i][k]\n return Q, R","function_tokens":["def","qr","(","A",",","prec","=","1e-10",")",":","m","=","len","(","A",")","if","m","<=","0",":","return","[","]",",","A","n","=","len","(","A","[","0","]",")","Rdiag","=","[","0","]","*","n","QR","=","copy",".","deepcopy","(","A",")","for","k","in","range","(","n",")",":","# Compute 2-norm of k-th column without under\/overflow.","nrm","=","0.0","for","i","in","range","(","k",",","m",")",":","nrm","=","sqrt","(","nrm","**","2","+","QR","[","i","]","[","k","]","**","2",")","if","abs","(","nrm",")",">","prec",":","# Form k-th Householder vector.","if","k","<","m","and","QR","[","k","]","[","k","]","<","0",":","nrm","=","-","nrm","for","i","in","range","(","k",",","m",")",":","QR","[","i","]","[","k","]","\/=","nrm","if","k","<","m",":","QR","[","k","]","[","k","]","+=","1.0","# Apply transformation to remaining columns.","for","j","in","range","(","k","+","1",",","n",")",":","s","=","0.0","for","i","in","range","(","k",",","m",")",":","s","+=","QR","[","i","]","[","k","]","*","QR","[","i","]","[","j","]","if","k","<","m",":","s","=","-","s","\/","QR","[","k","]","[","k","]","for","i","in","range","(","k",",","m",")",":","QR","[","i","]","[","j","]","+=","s","*","QR","[","i","]","[","k","]","Rdiag","[","k","]","=","-","nrm","# compute R","R","=","[","[","0","]","*","n","for","z","in","range","(","min","(","m",",","n",")",")","]","for","i","in","range","(","m",")",":","for","j","in","range","(","i",",","n",")",":","if","i","<","j",":","R","[","i","]","[","j","]","=","QR","[","i","]","[","j","]","if","i","==","j",":","R","[","i","]","[","i","]","=","Rdiag","[","i","]","# compute Q","w","=","min","(","m",",","n",")","Q","=","[","[","0","]","*","w","for","i","in","range","(","m",")","]","for","k","in","range","(","w","-","1",",","-","1",",","-","1",")",":","if","k","<","w",":","Q","[","k","]","[","k","]","=","1.0","for","j","in","range","(","k",",","w",")",":","if","k","<","m","and","abs","(","QR","[","k","]","[","k","]",")",">","prec",":","s","=","0.0","for","i","in","range","(","k",",","m",")",":","s","+=","QR","[","i","]","[","k","]","*","Q","[","i","]","[","j","]","s","=","-","s","\/","QR","[","k","]","[","k","]","for","i","in","range","(","k",",","m",")",":","Q","[","i","]","[","j","]","+=","s","*","QR","[","i","]","[","k","]","return","Q",",","R"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py#L324-L385"}
15
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py","language":"python","identifier":"solveWithForwardReplacement","parameters":"(A, b, prec=1e-10)","argument_list":"","return_statement":"return res","docstring":"solve a system Ax = b with A = QR in least squares sense\n return x\n\n see http:\/\/de.wikipedia.org\/wiki\/QR-Zerlegung","docstring_summary":"solve a system Ax = b with A = QR in least squares sense\n return x","docstring_tokens":["solve","a","system","Ax","=","b","with","A","=","QR","in","least","squares","sense","return","x"],"function":"def solveWithForwardReplacement(A, b, prec=1e-10):\n \"\"\"\n solve a system Ax = b with A = QR in least squares sense\n return x\n\n see http:\/\/de.wikipedia.org\/wiki\/QR-Zerlegung\n \"\"\"\n if len(A) == 0:\n return []\n Q, R = qr(transpose(A))\n\n Rt = transpose(R)\n m = len(Rt)\n n = len(Rt[0])\n\n z = [0] * n\n for r in range(m):\n if abs(Rt[r][r]) < prec:\n z[r] = 1.0\n continue\n s = 0.0\n for c in range(m):\n s += z[c] * Rt[r][c]\n z[r] = (b[r] - s) \/ Rt[r][r]\n\n res = matrixMultiplication(Q, [[a] for a in z])\n res = [v for sublist in res for v in sublist] # flatten\n\n return res","function_tokens":["def","solveWithForwardReplacement","(","A",",","b",",","prec","=","1e-10",")",":","if","len","(","A",")","==","0",":","return","[","]","Q",",","R","=","qr","(","transpose","(","A",")",")","Rt","=","transpose","(","R",")","m","=","len","(","Rt",")","n","=","len","(","Rt","[","0","]",")","z","=","[","0","]","*","n","for","r","in","range","(","m",")",":","if","abs","(","Rt","[","r","]","[","r","]",")","<","prec",":","z","[","r","]","=","1.0","continue","s","=","0.0","for","c","in","range","(","m",")",":","s","+=","z","[","c","]","*","Rt","[","r","]","[","c","]","z","[","r","]","=","(","b","[","r","]","-","s",")","\/","Rt","[","r","]","[","r","]","res","=","matrixMultiplication","(","Q",",","[","[","a","]","for","a","in","z","]",")","res","=","[","v","for","sublist","in","res","for","v","in","sublist","]","# flatten","return","res"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py#L388-L416"}
16
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py","language":"python","identifier":"solveWithBackwardReplacement","parameters":"(A, b, prec=1e-10)","argument_list":"","return_statement":"return res","docstring":"solve a system Ax = b with A = QR in least squares sense\n return x\n\n see http:\/\/de.wikipedia.org\/wiki\/QR-Zerlegung","docstring_summary":"solve a system Ax = b with A = QR in least squares sense\n return x","docstring_tokens":["solve","a","system","Ax","=","b","with","A","=","QR","in","least","squares","sense","return","x"],"function":"def solveWithBackwardReplacement(A, b, prec=1e-10):\n \"\"\"\n solve a system Ax = b with A = QR in least squares sense\n return x\n\n see http:\/\/de.wikipedia.org\/wiki\/QR-Zerlegung\n \"\"\"\n n = len(A)\n if n == 0:\n return []\n\n Q, R = qr(A)\n\n n = len(R[0])\n res = [0] * n\n\n z = matrixMultiplication(transpose(Q), [[a] for a in b])\n\n for r in range(n - 1, -1, -1):\n if abs(R[r][r]) < prec:\n res[r] = 1.0\n continue\n s = 0.0\n for c in range(r + 1, n):\n s += res[c] * R[r][c]\n res[r] = (z[r][0] - s) \/ R[r][r]\n\n return res","function_tokens":["def","solveWithBackwardReplacement","(","A",",","b",",","prec","=","1e-10",")",":","n","=","len","(","A",")","if","n","==","0",":","return","[","]","Q",",","R","=","qr","(","A",")","n","=","len","(","R","[","0","]",")","res","=","[","0","]","*","n","z","=","matrixMultiplication","(","transpose","(","Q",")",",","[","[","a","]","for","a","in","b","]",")","for","r","in","range","(","n","-","1",",","-","1",",","-","1",")",":","if","abs","(","R","[","r","]","[","r","]",")","<","prec",":","res","[","r","]","=","1.0","continue","s","=","0.0","for","c","in","range","(","r","+","1",",","n",")",":","s","+=","res","[","c","]","*","R","[","r","]","[","c","]","res","[","r","]","=","(","z","[","r","]","[","0","]","-","s",")","\/","R","[","r","]","[","r","]","return","res"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py#L419-L446"}
17
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py","language":"python","identifier":"leastSquareSolution","parameters":"(A, b)","argument_list":"","return_statement":"return s, res","docstring":"return the least squares solution x for the system Ax = b\n\n A is a list of list while b is a list","docstring_summary":"return the least squares solution x for the system Ax = b","docstring_tokens":["return","the","least","squares","solution","x","for","the","system","Ax","=","b"],"function":"def leastSquareSolution(A, b):\n \"\"\"\n return the least squares solution x for the system Ax = b\n\n A is a list of list while b is a list\n \"\"\"\n m = len(A)\n if m == 0:\n return []\n n = len(A[0])\n\n if n > m:\n s = solveWithForwardReplacement(A, b)\n else:\n s = solveWithBackwardReplacement(A, b)\n remap = matrixMultiplication(A, [[a] for a in s])\n res = sum([z[0] ** 2.0 for z in elementWise(remap, [[a] for a in b],\n lambda x, y: x - y)])\n\n return s, res","function_tokens":["def","leastSquareSolution","(","A",",","b",")",":","m","=","len","(","A",")","if","m","==","0",":","return","[","]","n","=","len","(","A","[","0","]",")","if","n",">","m",":","s","=","solveWithForwardReplacement","(","A",",","b",")","else",":","s","=","solveWithBackwardReplacement","(","A",",","b",")","remap","=","matrixMultiplication","(","A",",","[","[","a","]","for","a","in","s","]",")","res","=","sum","(","[","z","[","0","]","**","2.0","for","z","in","elementWise","(","remap",",","[","[","a","]","for","a","in","b","]",",","lambda","x",",","y",":","x","-","y",")","]",")","return","s",",","res"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py#L449-L468"}
18
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py","language":"python","identifier":"PolyFit.__init__","parameters":"(self, x, values, order=1)","argument_list":"","return_statement":"","docstring":"initialize a polyfitting with x and y coordinates\n and respective functino values\n (all simple lists)","docstring_summary":"initialize a polyfitting with x and y coordinates\n and respective functino values\n (all simple lists)","docstring_tokens":["initialize","a","polyfitting","with","x","and","y","coordinates","and","respective","functino","values","(","all","simple","lists",")"],"function":"def __init__(self, x, values, order=1):\n \"\"\"\n initialize a polyfitting with x and y coordinates\n and respective functino values\n (all simple lists)\n \"\"\"\n n = len(x)\n if n != len(values):\n raise PolyFitException(\"input values have different lengths\",\n self.TAG)\n\n self.mIn, self.sIn = meanAndStandardDeviation(x)\n self.mVal, self.sVal = meanAndStandardDeviation(values)\n x = [(y - self.mIn) \/ self.sIn for y in x]\n values = [(y - self.mVal) \/ self.sVal for y in values]\n\n A = [[x[i] ** float(j) for j in range(order + 1)] for i in range(n)]\n self.coeffs, self.residual = leastSquareSolution(A, values)\n self.order = order","function_tokens":["def","__init__","(","self",",","x",",","values",",","order","=","1",")",":","n","=","len","(","x",")","if","n","!=","len","(","values",")",":","raise","PolyFitException","(","\"input values have different lengths\"",",","self",".","TAG",")","self",".","mIn",",","self",".","sIn","=","meanAndStandardDeviation","(","x",")","self",".","mVal",",","self",".","sVal","=","meanAndStandardDeviation","(","values",")","x","=","[","(","y","-","self",".","mIn",")","\/","self",".","sIn","for","y","in","x","]","values","=","[","(","y","-","self",".","mVal",")","\/","self",".","sVal","for","y","in","values","]","A","=","[","[","x","[","i","]","**","float","(","j",")","for","j","in","range","(","order","+","1",")","]","for","i","in","range","(","n",")","]","self",".","coeffs",",","self",".","residual","=","leastSquareSolution","(","A",",","values",")","self",".","order","=","order"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py#L49-L67"}
19
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py","language":"python","identifier":"PolyFit.__getitem__","parameters":"(self, x)","argument_list":"","return_statement":"return val * self.sVal + self.mVal","docstring":"return the estimated function value for position x","docstring_summary":"return the estimated function value for position x","docstring_tokens":["return","the","estimated","function","value","for","position","x"],"function":"def __getitem__(self, x):\n \"\"\"\n return the estimated function value for position x\n \"\"\"\n x = (x - self.mIn) \/ self.sIn\n val = sum([self.coeffs[i] * x ** float(i) for i in range(self.order + 1)])\n return val * self.sVal + self.mVal","function_tokens":["def","__getitem__","(","self",",","x",")",":","x","=","(","x","-","self",".","mIn",")","\/","self",".","sIn","val","=","sum","(","[","self",".","coeffs","[","i","]","*","x","**","float","(","i",")","for","i","in","range","(","self",".","order","+","1",")","]",")","return","val","*","self",".","sVal","+","self",".","mVal"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py#L69-L75"}
20
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py","language":"python","identifier":"PolyFit2D.__init__","parameters":"(self, pts, values, order=1)","argument_list":"","return_statement":"","docstring":"initialize a polyfitting with pts = [[x1,x2], [y1,y2], ...] coordinates\n and respective function values [v1, ...]\n (all simple lists)","docstring_summary":"initialize a polyfitting with pts = [[x1,x2], [y1,y2], ...] coordinates\n and respective function values [v1, ...]\n (all simple lists)","docstring_tokens":["initialize","a","polyfitting","with","pts","=","[[","x1","x2","]","[","y1","y2","]","...","]","coordinates","and","respective","function","values","[","v1","...","]","(","all","simple","lists",")"],"function":"def __init__(self, pts, values, order=1):\n \"\"\"\n initialize a polyfitting with pts = [[x1,x2], [y1,y2], ...] coordinates\n and respective function values [v1, ...]\n (all simple lists)\n \"\"\"\n n = len(pts)\n for i in range(n):\n if 2 != len(pts[i]):\n raise PolyFitException(\"input values have different lengths\",\n self.TAG)\n\n mons = [x for x in product(range(order + 1), range(order + 1))\n if x[0] + x[1] <= order]\n self.monomials = mons\n self.n = len(self.monomials)\n\n # scale for better approximation\n self.mInX, self.sInX = meanAndStandardDeviation([z[0] for z in pts])\n self.mInY, self.sInY = meanAndStandardDeviation([z[1] for z in pts])\n self.mVal, self.sVal = meanAndStandardDeviation(values)\n pts = [((z[0] - self.mInX) \/ self.sInX, (z[1] - self.mInY) \/ self.sInY)\n for z in pts]\n values = [(z - self.mVal) \/ self.sVal for z in values]\n\n m = self.monomials\n A = [[pts[u][0] ** m[i][0] * pts[u][1] ** m[i][1] for i in range(self.n)]\n for u in range(n)]\n self.coeffs, self.residual = leastSquareSolution(A, values)\n self.order = order","function_tokens":["def","__init__","(","self",",","pts",",","values",",","order","=","1",")",":","n","=","len","(","pts",")","for","i","in","range","(","n",")",":","if","2","!=","len","(","pts","[","i","]",")",":","raise","PolyFitException","(","\"input values have different lengths\"",",","self",".","TAG",")","mons","=","[","x","for","x","in","product","(","range","(","order","+","1",")",",","range","(","order","+","1",")",")","if","x","[","0","]","+","x","[","1","]","<=","order","]","self",".","monomials","=","mons","self",".","n","=","len","(","self",".","monomials",")","# scale for better approximation","self",".","mInX",",","self",".","sInX","=","meanAndStandardDeviation","(","[","z","[","0","]","for","z","in","pts","]",")","self",".","mInY",",","self",".","sInY","=","meanAndStandardDeviation","(","[","z","[","1","]","for","z","in","pts","]",")","self",".","mVal",",","self",".","sVal","=","meanAndStandardDeviation","(","values",")","pts","=","[","(","(","z","[","0","]","-","self",".","mInX",")","\/","self",".","sInX",",","(","z","[","1","]","-","self",".","mInY",")","\/","self",".","sInY",")","for","z","in","pts","]","values","=","[","(","z","-","self",".","mVal",")","\/","self",".","sVal","for","z","in","values","]","m","=","self",".","monomials","A","=","[","[","pts","[","u","]","[","0","]","**","m","[","i","]","[","0","]","*","pts","[","u","]","[","1","]","**","m","[","i","]","[","1","]","for","i","in","range","(","self",".","n",")","]","for","u","in","range","(","n",")","]","self",".","coeffs",",","self",".","residual","=","leastSquareSolution","(","A",",","values",")","self",".","order","=","order"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py#L86-L115"}
21
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py","language":"python","identifier":"PolyFit2D.__getitem__","parameters":"(self, x)","argument_list":"","return_statement":"return val * self.sVal + self.mVal","docstring":"return the estimated function value for position x","docstring_summary":"return the estimated function value for position x","docstring_tokens":["return","the","estimated","function","value","for","position","x"],"function":"def __getitem__(self, x):\n \"\"\"\n return the estimated function value for position x\n \"\"\"\n m = self.monomials\n x = ((x[0] - self.mInX) \/ self.sInX, (x[1] - self.mInY) \/ self.sInY)\n val = sum([self.coeffs[i] * x[0] ** m[i][0] * x[1] ** m[i][1]\n for i in range(self.n)])\n return val * self.sVal + self.mVal","function_tokens":["def","__getitem__","(","self",",","x",")",":","m","=","self",".","monomials","x","=","(","(","x","[","0","]","-","self",".","mInX",")","\/","self",".","sInX",",","(","x","[","1","]","-","self",".","mInY",")","\/","self",".","sInY",")","val","=","sum","(","[","self",".","coeffs","[","i","]","*","x","[","0","]","**","m","[","i","]","[","0","]","*","x","[","1","]","**","m","[","i","]","[","1","]","for","i","in","range","(","self",".","n",")","]",")","return","val","*","self",".","sVal","+","self",".","mVal"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py#L117-L125"}
22
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py","language":"python","identifier":"PolyFitND.__init__","parameters":"(self, pts, values, order=1)","argument_list":"","return_statement":"","docstring":"initialize a polyfitting with pts = [[x1,x2 ...], [y1,y2,...], ...]\n coordinates and respective function values [v1, ...]\n (all simple lists)","docstring_summary":"initialize a polyfitting with pts = [[x1,x2 ...], [y1,y2,...], ...]\n coordinates and respective function values [v1, ...]\n (all simple lists)","docstring_tokens":["initialize","a","polyfitting","with","pts","=","[[","x1","x2","...","]","[","y1","y2","...","]","...","]","coordinates","and","respective","function","values","[","v1","...","]","(","all","simple","lists",")"],"function":"def __init__(self, pts, values, order=1):\n \"\"\"\n initialize a polyfitting with pts = [[x1,x2 ...], [y1,y2,...], ...]\n coordinates and respective function values [v1, ...]\n (all simple lists)\n \"\"\"\n n = len(pts)\n if n <= 0:\n raise PolyFitException(\"no input values given\",\n self.TAG)\n dimension = len(pts[0])\n for i in range(n):\n if dimension != len(pts[i]):\n raise PolyFitException(\"input values have different lengths\",\n self.TAG)\n\n self.dimension = dimension\n\n mons = [x for x in product(*[range(order + 1)] * dimension)\n if sum(x) <= order]\n self.monomials = mons\n self.n = len(self.monomials)\n\n m = self.monomials\n\n # scales\n self.scales = [(c, s) for c, s in [meanAndStandardDeviation(\n [pts[j][i] for j in range(n)])\n for i in range(dimension)]]\n pts = [[(pts[j][i] - self.scales[i][0]) \/ self.scales[i][1]\n for i in range(dimension)]\n for j in range(n)]\n self.mVal, self.sVal = meanAndStandardDeviation(values)\n values = [(z - self.mVal) \/ self.sVal for z in values]\n\n A = [[functools.reduce(operator.mul,\n [pts[u][d] ** m[i][d] for d in range(dimension)],\n 1)\n for i in range(self.n)]\n for u in range(n)]\n self.coeffs, self.residual = leastSquareSolution(A, values)\n self.order = order","function_tokens":["def","__init__","(","self",",","pts",",","values",",","order","=","1",")",":","n","=","len","(","pts",")","if","n","<=","0",":","raise","PolyFitException","(","\"no input values given\"",",","self",".","TAG",")","dimension","=","len","(","pts","[","0","]",")","for","i","in","range","(","n",")",":","if","dimension","!=","len","(","pts","[","i","]",")",":","raise","PolyFitException","(","\"input values have different lengths\"",",","self",".","TAG",")","self",".","dimension","=","dimension","mons","=","[","x","for","x","in","product","(","*","[","range","(","order","+","1",")","]","*","dimension",")","if","sum","(","x",")","<=","order","]","self",".","monomials","=","mons","self",".","n","=","len","(","self",".","monomials",")","m","=","self",".","monomials","# scales","self",".","scales","=","[","(","c",",","s",")","for","c",",","s","in","[","meanAndStandardDeviation","(","[","pts","[","j","]","[","i","]","for","j","in","range","(","n",")","]",")","for","i","in","range","(","dimension",")","]","]","pts","=","[","[","(","pts","[","j","]","[","i","]","-","self",".","scales","[","i","]","[","0","]",")","\/","self",".","scales","[","i","]","[","1","]","for","i","in","range","(","dimension",")","]","for","j","in","range","(","n",")","]","self",".","mVal",",","self",".","sVal","=","meanAndStandardDeviation","(","values",")","values","=","[","(","z","-","self",".","mVal",")","\/","self",".","sVal","for","z","in","values","]","A","=","[","[","functools",".","reduce","(","operator",".","mul",",","[","pts","[","u","]","[","d","]","**","m","[","i","]","[","d","]","for","d","in","range","(","dimension",")","]",",","1",")","for","i","in","range","(","self",".","n",")","]","for","u","in","range","(","n",")","]","self",".","coeffs",",","self",".","residual","=","leastSquareSolution","(","A",",","values",")","self",".","order","=","order"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py#L136-L177"}
23
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py","language":"python","identifier":"PolyFitND.__getitem__","parameters":"(self, x)","argument_list":"","return_statement":"return val * self.sVal + self.mVal","docstring":"return the estimated function value for position x","docstring_summary":"return the estimated function value for position x","docstring_tokens":["return","the","estimated","function","value","for","position","x"],"function":"def __getitem__(self, x):\n \"\"\"\n return the estimated function value for position x\n \"\"\"\n if len(x) != self.dimension:\n raise PolyFitException(\"input value has different length than \"\n \"initialization data\",\n self.TAG)\n\n m = self.monomials\n d = len(x)\n x = [(x[i] - self.scales[i][0]) \/ self.scales[i][1]\n for i in range(self.dimension)]\n val = sum([self.coeffs[i]\n * functools.reduce(operator.mul,\n [x[d] ** m[i][d]\n for d in range(self.dimension)],\n 1)\n for i in range(self.n)])\n return val * self.sVal + self.mVal","function_tokens":["def","__getitem__","(","self",",","x",")",":","if","len","(","x",")","!=","self",".","dimension",":","raise","PolyFitException","(","\"input value has different length than \"","\"initialization data\"",",","self",".","TAG",")","m","=","self",".","monomials","d","=","len","(","x",")","x","=","[","(","x","[","i","]","-","self",".","scales","[","i","]","[","0","]",")","\/","self",".","scales","[","i","]","[","1","]","for","i","in","range","(","self",".","dimension",")","]","val","=","sum","(","[","self",".","coeffs","[","i","]","*","functools",".","reduce","(","operator",".","mul",",","[","x","[","d","]","**","m","[","i","]","[","d","]","for","d","in","range","(","self",".","dimension",")","]",",","1",")","for","i","in","range","(","self",".","n",")","]",")","return","val","*","self",".","sVal","+","self",".","mVal"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/thirdparty\/purepythonpolyfit\/purePythonPolyFit.py#L179-L198"}
24
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/thirdparty\/purepythonpolyfit\/timing.py","language":"python","identifier":"timed","parameters":"(f)","argument_list":"","return_statement":"return wrapper","docstring":"measure the clock time of functions as well as the pure times,\n without the subfunction calls\n (However, the latter is not as accurate since it includes some management\n of the timing)","docstring_summary":"measure the clock time of functions as well as the pure times,\n without the subfunction calls\n (However, the latter is not as accurate since it includes some management\n of the timing)","docstring_tokens":["measure","the","clock","time","of","functions","as","well","as","the","pure","times","without","the","subfunction","calls","(","However","the","latter","is","not","as","accurate","since","it","includes","some","management","of","the","timing",")"],"function":"def timed(f):\n \"\"\"\n measure the clock time of functions as well as the pure times,\n without the subfunction calls\n (However, the latter is not as accurate since it includes some management\n of the timing)\n \"\"\"\n @wraps(f)\n def wrapper(*args, **kwds):\n startOverall = clock()\n global currentCallStack\n global times\n name = f.__name__\n currentCallStack.append(name)\n if name not in times:\n times[name] = {\"numCalls\": 0, \"totalTime\": 0, \"subprocesses\": 0, \"numSub\" : 0}\n start = clock()\n result = f(*args, **kwds)\n elapsed = clock() - start\n currentCallStack = currentCallStack[:-1]\n times[name][\"numCalls\"] += 1\n times[name][\"totalTime\"] += elapsed\n if len(currentCallStack) > 1:\n times[currentCallStack[-2]][\"numSub\"] += 1\n times[currentCallStack[-2]][\"subprocesses\"] += clock() - startOverall\n return result\n return wrapper","function_tokens":["def","timed","(","f",")",":","@","wraps","(","f",")","def","wrapper","(","*","args",",","*","*","kwds",")",":","startOverall","=","clock","(",")","global","currentCallStack","global","times","name","=","f",".","__name__","currentCallStack",".","append","(","name",")","if","name","not","in","times",":","times","[","name","]","=","{","\"numCalls\"",":","0",",","\"totalTime\"",":","0",",","\"subprocesses\"",":","0",",","\"numSub\"",":","0","}","start","=","clock","(",")","result","=","f","(","*","args",",","*","*","kwds",")","elapsed","=","clock","(",")","-","start","currentCallStack","=","currentCallStack","[",":","-","1","]","times","[","name","]","[","\"numCalls\"","]","+=","1","times","[","name","]","[","\"totalTime\"","]","+=","elapsed","if","len","(","currentCallStack",")",">","1",":","times","[","currentCallStack","[","-","2","]","]","[","\"numSub\"","]","+=","1","times","[","currentCallStack","[","-","2","]","]","[","\"subprocesses\"","]","+=","clock","(",")","-","startOverall","return","result","return","wrapper"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/thirdparty\/purepythonpolyfit\/timing.py#L44-L70"}
25
+ {"nwo":"DaoCloud\/daochain","sha":"3499d34eab12237c7b97e3df550c3e0b33d154a5","path":"app\/thirdparty\/purepythonpolyfit\/timing.py","language":"python","identifier":"printTimes","parameters":"()","argument_list":"","return_statement":"","docstring":"pretty print timing results","docstring_summary":"pretty print timing results","docstring_tokens":["pretty","print","timing","results"],"function":"def printTimes():\n \"\"\"\n pretty print timing results\n \"\"\"\n global times\n # determine maximum length:\n header = \"function name\"\n ma = len(header)\n sum = 0\n sumOverall = 0\n for name, ts in times.items():\n ma = max(ma, len(name))\n net = (ts['totalTime'] - ts['subprocesses'])\/float(ts['numCalls'])\n sum += net\n sumOverall += (ts['totalTime'] - ts['subprocesses'])\n ma += 2\n \n print(\"\\033[1moverall (mean) processor time\\033[0m: %0.5fs (%0.5fs)\" %(sumOverall, sum))\n print(\"listing processor time per method:\" )\n print(\"\\033[1m%s%s\\t %% Overall time\\t Mean w.o. Sub[s]\\t Mean[s]\\tNum-Calls\\033[0m\" % (header, ' '*(ma - len(header))))\n for name in sorted(times.keys()):\n ts = times[name]\n m = ts['totalTime']\/float(ts['numCalls'])\n net = (ts['totalTime'] - ts['subprocesses'])\/float(ts['numCalls'])\n perc = 100.0*net\/float(sum)\n print(\"%s%s\\t% 15.2f\\t% 17.5f\\t% 9.5f\\t% 9d\" %(name,\n ' '*(ma - len(name)),\n perc,\n net,\n m,\n\n ts['numCalls']))","function_tokens":["def","printTimes","(",")",":","global","times","# determine maximum length:","header","=","\"function name\"","ma","=","len","(","header",")","sum","=","0","sumOverall","=","0","for","name",",","ts","in","times",".","items","(",")",":","ma","=","max","(","ma",",","len","(","name",")",")","net","=","(","ts","[","'totalTime'","]","-","ts","[","'subprocesses'","]",")","\/","float","(","ts","[","'numCalls'","]",")","sum","+=","net","sumOverall","+=","(","ts","[","'totalTime'","]","-","ts","[","'subprocesses'","]",")","ma","+=","2","print","(","\"\\033[1moverall (mean) processor time\\033[0m: %0.5fs (%0.5fs)\"","%","(","sumOverall",",","sum",")",")","print","(","\"listing processor time per method:\"",")","print","(","\"\\033[1m%s%s\\t %% Overall time\\t Mean w.o. Sub[s]\\t Mean[s]\\tNum-Calls\\033[0m\"","%","(","header",",","' '","*","(","ma","-","len","(","header",")",")",")",")","for","name","in","sorted","(","times",".","keys","(",")",")",":","ts","=","times","[","name","]","m","=","ts","[","'totalTime'","]","\/","float","(","ts","[","'numCalls'","]",")","net","=","(","ts","[","'totalTime'","]","-","ts","[","'subprocesses'","]",")","\/","float","(","ts","[","'numCalls'","]",")","perc","=","100.0","*","net","\/","float","(","sum",")","print","(","\"%s%s\\t% 15.2f\\t% 17.5f\\t% 9.5f\\t% 9d\"","%","(","name",",","' '","*","(","ma","-","len","(","name",")",")",",","perc",",","net",",","m",",","ts","[","'numCalls'","]",")",")"],"url":"https:\/\/github.com\/DaoCloud\/daochain\/blob\/3499d34eab12237c7b97e3df550c3e0b33d154a5\/app\/thirdparty\/purepythonpolyfit\/timing.py#L72-L103"}
DataDog__documentation.jsonl ADDED
The diff for this file is too large to render. See raw diff
Dav1dde__glad-web.jsonl ADDED
@@ -0,0 +1,2 @@
 
 
1
+ {"nwo":"Dav1dde\/glad-web","sha":"c9a566df91e54086884a34f6ce6e031fce1d69e1","path":"gladweb\/__init__.py","language":"python","identifier":"create_application","parameters":"(debug=False, verbose=False)","argument_list":"","return_statement":"return app","docstring":"Creates fully configured flask application\n\n :param debug: Launch the app in debug-mode.\n :param verbose: True enables logging,\n None (default) only enables logging if not in debug mode\n False no logging configured.\n :return: The created Flask application","docstring_summary":"Creates fully configured flask application","docstring_tokens":["Creates","fully","configured","flask","application"],"function":"def create_application(debug=False, verbose=False):\n \"\"\"\n Creates fully configured flask application\n\n :param debug: Launch the app in debug-mode.\n :param verbose: True enables logging,\n None (default) only enables logging if not in debug mode\n False no logging configured.\n :return: The created Flask application\n \"\"\"\n import gladweb.config\n\n app = Flask(__name__)\n app.config.from_object('gladweb.config')\n if app.config.get('WITH_PROXY_FIX'):\n app.wsgi_app = ProxyFix(app.wsgi_app)\n app.debug = debug\n app.freezer = Freezer(app)\n\n if not os.path.exists(app.config['TEMP']):\n os.makedirs(app.config['TEMP'])\n\n if verbose or (not app.debug and verbose is None):\n setup_logging()\n\n if sentry is not None:\n sentry.init_app(app)\n\n @app.before_request\n def before_request():\n g.cache = app.config['CACHE']\n g.metadata = Metadata(g.cache)\n\n from gladweb.views.index import index\n app.register_blueprint(index)\n\n from gladweb.views.generated import generated\n idx = AutoIndexBlueprint(generated, browse_root=app.config['TEMP'], add_url_rules=False, silk_options={'silk_path': '\/icons'})\n\n @generated.route('\/<root>\/')\n @generated.route('\/<root>\/<path:path>')\n def autoindex(root, path='.'):\n root = werkzeug.utils.secure_filename(root)\n browse_root = os.path.join(app.config['TEMP'], root)\n serialized_path = os.path.join(browse_root, '.serialized')\n if os.path.exists(serialized_path):\n with open(serialized_path) as fobj:\n g.serialized = json.load(fobj)\n return idx.render_autoindex(\n path,\n browse_root=browse_root,\n template='autoindex.html',\n template_context={'root': root}\n )\n\n app.register_blueprint(generated, url_prefix='\/generated')\n\n app.jinja_env.filters['pretty_date'] = gladweb.util.pretty_date\n app.jinja_env.globals.update(glad_version=glad.__version__)\n\n return app","function_tokens":["def","create_application","(","debug","=","False",",","verbose","=","False",")",":","import","gladweb",".","config","app","=","Flask","(","__name__",")","app",".","config",".","from_object","(","'gladweb.config'",")","if","app",".","config",".","get","(","'WITH_PROXY_FIX'",")",":","app",".","wsgi_app","=","ProxyFix","(","app",".","wsgi_app",")","app",".","debug","=","debug","app",".","freezer","=","Freezer","(","app",")","if","not","os",".","path",".","exists","(","app",".","config","[","'TEMP'","]",")",":","os",".","makedirs","(","app",".","config","[","'TEMP'","]",")","if","verbose","or","(","not","app",".","debug","and","verbose","is","None",")",":","setup_logging","(",")","if","sentry","is","not","None",":","sentry",".","init_app","(","app",")","@","app",".","before_request","def","before_request","(",")",":","g",".","cache","=","app",".","config","[","'CACHE'","]","g",".","metadata","=","Metadata","(","g",".","cache",")","from","gladweb",".","views",".","index","import","index","app",".","register_blueprint","(","index",")","from","gladweb",".","views",".","generated","import","generated","idx","=","AutoIndexBlueprint","(","generated",",","browse_root","=","app",".","config","[","'TEMP'","]",",","add_url_rules","=","False",",","silk_options","=","{","'silk_path'",":","'\/icons'","}",")","@","generated",".","route","(","'\/<root>\/'",")","@","generated",".","route","(","'\/<root>\/<path:path>'",")","def","autoindex","(","root",",","path","=","'.'",")",":","root","=","werkzeug",".","utils",".","secure_filename","(","root",")","browse_root","=","os",".","path",".","join","(","app",".","config","[","'TEMP'","]",",","root",")","serialized_path","=","os",".","path",".","join","(","browse_root",",","'.serialized'",")","if","os",".","path",".","exists","(","serialized_path",")",":","with","open","(","serialized_path",")","as","fobj",":","g",".","serialized","=","json",".","load","(","fobj",")","return","idx",".","render_autoindex","(","path",",","browse_root","=","browse_root",",","template","=","'autoindex.html'",",","template_context","=","{","'root'",":","root","}",")","app",".","register_blueprint","(","generated",",","url_prefix","=","'\/generated'",")","app",".","jinja_env",".","filters","[","'pretty_date'","]","=","gladweb",".","util",".","pretty_date","app",".","jinja_env",".","globals",".","update","(","glad_version","=","glad",".","__version__",")","return","app"],"url":"https:\/\/github.com\/Dav1dde\/glad-web\/blob\/c9a566df91e54086884a34f6ce6e031fce1d69e1\/gladweb\/__init__.py#L58-L118"}
2
+ {"nwo":"Dav1dde\/glad-web","sha":"c9a566df91e54086884a34f6ce6e031fce1d69e1","path":"gladweb\/util.py","language":"python","identifier":"pretty_date","parameters":"(time, now=None)","argument_list":"","return_statement":"return str(day_diff \/\/ 365) + \" years ago\"","docstring":"Get a datetime object or a int() Epoch timestamp and return a\n pretty string like 'an hour ago', 'Yesterday', '3 months ago',\n 'just now', etc","docstring_summary":"Get a datetime object or a int() Epoch timestamp and return a\n pretty string like 'an hour ago', 'Yesterday', '3 months ago',\n 'just now', etc","docstring_tokens":["Get","a","datetime","object","or","a","int","()","Epoch","timestamp","and","return","a","pretty","string","like","an","hour","ago","Yesterday","3","months","ago","just","now","etc"],"function":"def pretty_date(time, now=None):\n \"\"\"\n Get a datetime object or a int() Epoch timestamp and return a\n pretty string like 'an hour ago', 'Yesterday', '3 months ago',\n 'just now', etc\n \"\"\"\n\n if now is None:\n now = timestamp()\n\n now = convert_if_timestamp(now)\n time = convert_if_timestamp(time)\n\n diff = now - time\n second_diff = diff.seconds\n day_diff = diff.days\n\n if day_diff < 0:\n return ''\n\n if day_diff == 0:\n if second_diff < 10:\n return \"just now\"\n if second_diff < 60:\n return str(second_diff) + \" seconds ago\"\n if second_diff < 120:\n return \"a minute ago\"\n if second_diff < 3600:\n return str(second_diff \/\/ 60) + \" minutes ago\"\n if second_diff < 7200:\n return \"an hour ago\"\n if second_diff < 86400:\n return str(second_diff \/\/ 3600) + \" hours ago\"\n if day_diff == 1:\n return \"Yesterday\"\n if day_diff < 7:\n return str(day_diff) + \" days ago\"\n if day_diff < 31:\n return str(day_diff \/\/ 7) + \" weeks ago\"\n if day_diff < 365:\n return str(day_diff \/\/ 30) + \" months ago\"\n return str(day_diff \/\/ 365) + \" years ago\"","function_tokens":["def","pretty_date","(","time",",","now","=","None",")",":","if","now","is","None",":","now","=","timestamp","(",")","now","=","convert_if_timestamp","(","now",")","time","=","convert_if_timestamp","(","time",")","diff","=","now","-","time","second_diff","=","diff",".","seconds","day_diff","=","diff",".","days","if","day_diff","<","0",":","return","''","if","day_diff","==","0",":","if","second_diff","<","10",":","return","\"just now\"","if","second_diff","<","60",":","return","str","(","second_diff",")","+","\" seconds ago\"","if","second_diff","<","120",":","return","\"a minute ago\"","if","second_diff","<","3600",":","return","str","(","second_diff","\/\/","60",")","+","\" minutes ago\"","if","second_diff","<","7200",":","return","\"an hour ago\"","if","second_diff","<","86400",":","return","str","(","second_diff","\/\/","3600",")","+","\" hours ago\"","if","day_diff","==","1",":","return","\"Yesterday\"","if","day_diff","<","7",":","return","str","(","day_diff",")","+","\" days ago\"","if","day_diff","<","31",":","return","str","(","day_diff","\/\/","7",")","+","\" weeks ago\"","if","day_diff","<","365",":","return","str","(","day_diff","\/\/","30",")","+","\" months ago\"","return","str","(","day_diff","\/\/","365",")","+","\" years ago\""],"url":"https:\/\/github.com\/Dav1dde\/glad-web\/blob\/c9a566df91e54086884a34f6ce6e031fce1d69e1\/gladweb\/util.py#L11-L52"}
Dieterbe__anthracite.jsonl ADDED
The diff for this file is too large to render. See raw diff
DingZaiHub__PythonSpider.jsonl ADDED
@@ -0,0 +1 @@
 
1
+ {"nwo":"DingZaiHub\/PythonSpider","sha":"207a47e8ab5fe6ab2cc1f43bd0a98b67b30ea3f1","path":"01-\u5b89\u5fbd\u62db\u6295\u6807(sojson)\/sojson\u66ff\u6362\u65b9\u6cd5.py","language":"python","identifier":"change","parameters":"(s)","argument_list":"","return_statement":"return ctx.call(\"change\", value)","docstring":"\u66ff\u6362\u51fd\u6570\uff0cjs\u6587\u4ef6\u4e2d\u5199\u6cd5\u5982\u4e0b\uff1a\n function change(s) {\n return '\"' + eval(s) + '\"'\n }","docstring_summary":"\u66ff\u6362\u51fd\u6570\uff0cjs\u6587\u4ef6\u4e2d\u5199\u6cd5\u5982\u4e0b\uff1a\n function change(s) {\n return '\"' + eval(s) + '\"'\n }","docstring_tokens":["\u66ff\u6362\u51fd\u6570\uff0cjs\u6587\u4ef6\u4e2d\u5199\u6cd5\u5982\u4e0b\uff1a","function","change","(","s",")","{","return","+","eval","(","s",")","+","}"],"function":"def change(s):\n \"\"\"\n \u66ff\u6362\u51fd\u6570\uff0cjs\u6587\u4ef6\u4e2d\u5199\u6cd5\u5982\u4e0b\uff1a\n function change(s) {\n return '\"' + eval(s) + '\"'\n }\n \"\"\"\n value = s.group('value')\n return ctx.call(\"change\", value)","function_tokens":["def","change","(","s",")",":","value","=","s",".","group","(","'value'",")","return","ctx",".","call","(","\"change\"",",","value",")"],"url":"https:\/\/github.com\/DingZaiHub\/PythonSpider\/blob\/207a47e8ab5fe6ab2cc1f43bd0a98b67b30ea3f1\/01-\u5b89\u5fbd\u62db\u6295\u6807(sojson)\/sojson\u66ff\u6362\u65b9\u6cd5.py#L4-L12"}
DocSavage__bloog.jsonl ADDED
The diff for this file is too large to render. See raw diff
E2OpenPlugins__e2openplugin-OpenWebif.jsonl ADDED
The diff for this file is too large to render. See raw diff
EDCD__EDDN.jsonl ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"EDCD\/EDDN","sha":"e23d5d3b29405a5154811876358c7170d6cd3ee0","path":"setup.py","language":"python","identifier":"open_file_perms_recursive","parameters":"(dirname)","argument_list":"","return_statement":"","docstring":"Open up file perms on the given directory and its contents.","docstring_summary":"Open up file perms on the given directory and its contents.","docstring_tokens":["Open","up","file","perms","on","the","given","directory","and","its","contents","."],"function":"def open_file_perms_recursive(dirname):\n \"\"\"Open up file perms on the given directory and its contents.\"\"\"\n print 'open_file_perms_recursive: %s' % ( dirname )\n names = os.listdir(dirname)\n for name in names:\n n = '%s\/%s' % ( dirname, name )\n print 'open_file_perms_recursive: %s' % ( n )\n if (os.path.isdir(n)):\n os.chmod(n, 0755)\n # Recurse\n open_file_perms_recursive(n)\n \n else:\n os.chmod(n, 0644)","function_tokens":["def","open_file_perms_recursive","(","dirname",")",":","print","'open_file_perms_recursive: %s'","%","(","dirname",")","names","=","os",".","listdir","(","dirname",")","for","name","in","names",":","n","=","'%s\/%s'","%","(","dirname",",","name",")","print","'open_file_perms_recursive: %s'","%","(","n",")","if","(","os",".","path",".","isdir","(","n",")",")",":","os",".","chmod","(","n",",","0755",")","# Recurse","open_file_perms_recursive","(","n",")","else",":","os",".","chmod","(","n",",","0644",")"],"url":"https:\/\/github.com\/EDCD\/EDDN\/blob\/e23d5d3b29405a5154811876358c7170d6cd3ee0\/setup.py#L116-L129"}
2
+ {"nwo":"EDCD\/EDDN","sha":"e23d5d3b29405a5154811876358c7170d6cd3ee0","path":"src\/eddn\/Gateway.py","language":"python","identifier":"push_message","parameters":"(parsed_message, topic)","argument_list":"","return_statement":"","docstring":"Spawned as a greenlet to push messages (strings) through ZeroMQ.\n This is a dumb method that just pushes strings; it assumes you've already validated\n and serialised as you want to.","docstring_summary":"Spawned as a greenlet to push messages (strings) through ZeroMQ.\n This is a dumb method that just pushes strings; it assumes you've already validated\n and serialised as you want to.","docstring_tokens":["Spawned","as","a","greenlet","to","push","messages","(","strings",")","through","ZeroMQ",".","This","is","a","dumb","method","that","just","pushes","strings",";","it","assumes","you","ve","already","validated","and","serialised","as","you","want","to","."],"function":"def push_message(parsed_message, topic):\n \"\"\"\n Spawned as a greenlet to push messages (strings) through ZeroMQ.\n This is a dumb method that just pushes strings; it assumes you've already validated\n and serialised as you want to.\n \"\"\"\n string_message = simplejson.dumps(parsed_message, ensure_ascii=False).encode('utf-8')\n\n # Push a zlib compressed JSON representation of the message to\n # announcers with schema as topic\n compressed_msg = zlib.compress(string_message)\n \n send_message = \"%s |-| %s\" % (str(topic), compressed_msg)\n \n sender.send(send_message)\n statsCollector.tally(\"outbound\")","function_tokens":["def","push_message","(","parsed_message",",","topic",")",":","string_message","=","simplejson",".","dumps","(","parsed_message",",","ensure_ascii","=","False",")",".","encode","(","'utf-8'",")","# Push a zlib compressed JSON representation of the message to","# announcers with schema as topic","compressed_msg","=","zlib",".","compress","(","string_message",")","send_message","=","\"%s |-| %s\"","%","(","str","(","topic",")",",","compressed_msg",")","sender",".","send","(","send_message",")","statsCollector",".","tally","(","\"outbound\"",")"],"url":"https:\/\/github.com\/EDCD\/EDDN\/blob\/e23d5d3b29405a5154811876358c7170d6cd3ee0\/src\/eddn\/Gateway.py#L118-L133"}
3
+ {"nwo":"EDCD\/EDDN","sha":"e23d5d3b29405a5154811876358c7170d6cd3ee0","path":"src\/eddn\/Gateway.py","language":"python","identifier":"get_remote_address","parameters":"()","argument_list":"","return_statement":"return request.headers.get('X-Forwarded-For', request.remote_addr)","docstring":"Determines the address of the uploading client. First checks the for\n proxy-forwarded headers, then falls back to request.remote_addr.\n :rtype: str","docstring_summary":"Determines the address of the uploading client. First checks the for\n proxy-forwarded headers, then falls back to request.remote_addr.\n :rtype: str","docstring_tokens":["Determines","the","address","of","the","uploading","client",".","First","checks","the","for","proxy","-","forwarded","headers","then","falls","back","to","request",".","remote_addr",".",":","rtype",":","str"],"function":"def get_remote_address():\n \"\"\"\n Determines the address of the uploading client. First checks the for\n proxy-forwarded headers, then falls back to request.remote_addr.\n :rtype: str\n \"\"\"\n return request.headers.get('X-Forwarded-For', request.remote_addr)","function_tokens":["def","get_remote_address","(",")",":","return","request",".","headers",".","get","(","'X-Forwarded-For'",",","request",".","remote_addr",")"],"url":"https:\/\/github.com\/EDCD\/EDDN\/blob\/e23d5d3b29405a5154811876358c7170d6cd3ee0\/src\/eddn\/Gateway.py#L136-L142"}
4
+ {"nwo":"EDCD\/EDDN","sha":"e23d5d3b29405a5154811876358c7170d6cd3ee0","path":"src\/eddn\/Gateway.py","language":"python","identifier":"get_decompressed_message","parameters":"()","argument_list":"","return_statement":"return message_body","docstring":"For upload formats that support it, detect gzip Content-Encoding headers\n and de-compress on the fly.\n :rtype: str\n :returns: The de-compressed request body.","docstring_summary":"For upload formats that support it, detect gzip Content-Encoding headers\n and de-compress on the fly.\n :rtype: str\n :returns: The de-compressed request body.","docstring_tokens":["For","upload","formats","that","support","it","detect","gzip","Content","-","Encoding","headers","and","de","-","compress","on","the","fly",".",":","rtype",":","str",":","returns",":","The","de","-","compressed","request","body","."],"function":"def get_decompressed_message():\n \"\"\"\n For upload formats that support it, detect gzip Content-Encoding headers\n and de-compress on the fly.\n :rtype: str\n :returns: The de-compressed request body.\n \"\"\"\n content_encoding = request.headers.get('Content-Encoding', '')\n logger.debug('Content-Encoding: ' + content_encoding)\n\n if content_encoding in ['gzip', 'deflate']:\n logger.debug('Content-Encoding of gzip or deflate...')\n # Compressed request. We have to decompress the body, then figure out\n # if it's form-encoded.\n try:\n # Auto header checking.\n logger.debug('Trying zlib.decompress (15 + 32)...')\n message_body = zlib.decompress(request.body.read(), 15 + 32)\n\n except zlib.error:\n logger.error('zlib.error, trying zlib.decompress (-15)')\n # Negative wbits suppresses adler32 checksumming.\n message_body = zlib.decompress(request.body.read(), -15)\n logger.debug('Resulting message_body:\\n%s\\n' % (message_body))\n\n # At this point, we're not sure whether we're dealing with a straight\n # un-encoded POST body, or a form-encoded POST. Attempt to parse the\n # body. If it's not form-encoded, this will return an empty dict.\n form_enc_parsed = urlparse.parse_qs(message_body)\n if form_enc_parsed:\n logger.info('Request is form-encoded, compressed, from %s' % (get_remote_address()))\n # This is a form-encoded POST. The value of the data attrib will\n # be the body we're looking for.\n try:\n message_body = form_enc_parsed['data'][0]\n\n except (KeyError, IndexError):\n logger.error('form-encoded, compressed, upload did not contain a \"data\" key. From %s', get_remote_address())\n raise MalformedUploadError(\n \"No 'data' POST key\/value found. Check your POST key \"\n \"name for spelling, and make sure you're passing a value.\"\n )\n\n else:\n logger.debug('Request is *NOT* form-encoded')\n\n else:\n logger.debug('Content-Encoding indicates *not* compressed...')\n\n # Uncompressed request. Bottle handles all of the parsing of the\n # POST key\/vals, or un-encoded body.\n data_key = request.forms.get('data')\n if data_key:\n logger.info('Request is form-encoded, uncompressed, from %s' % (get_remote_address()))\n # This is a form-encoded POST. Support the silly people.\n message_body = data_key\n\n else:\n logger.debug('Plain POST request detected...')\n # This is a non form-encoded POST body.\n message_body = request.body.read()\n\n return message_body","function_tokens":["def","get_decompressed_message","(",")",":","content_encoding","=","request",".","headers",".","get","(","'Content-Encoding'",",","''",")","logger",".","debug","(","'Content-Encoding: '","+","content_encoding",")","if","content_encoding","in","[","'gzip'",",","'deflate'","]",":","logger",".","debug","(","'Content-Encoding of gzip or deflate...'",")","# Compressed request. We have to decompress the body, then figure out","# if it's form-encoded.","try",":","# Auto header checking.","logger",".","debug","(","'Trying zlib.decompress (15 + 32)...'",")","message_body","=","zlib",".","decompress","(","request",".","body",".","read","(",")",",","15","+","32",")","except","zlib",".","error",":","logger",".","error","(","'zlib.error, trying zlib.decompress (-15)'",")","# Negative wbits suppresses adler32 checksumming.","message_body","=","zlib",".","decompress","(","request",".","body",".","read","(",")",",","-","15",")","logger",".","debug","(","'Resulting message_body:\\n%s\\n'","%","(","message_body",")",")","# At this point, we're not sure whether we're dealing with a straight","# un-encoded POST body, or a form-encoded POST. Attempt to parse the","# body. If it's not form-encoded, this will return an empty dict.","form_enc_parsed","=","urlparse",".","parse_qs","(","message_body",")","if","form_enc_parsed",":","logger",".","info","(","'Request is form-encoded, compressed, from %s'","%","(","get_remote_address","(",")",")",")","# This is a form-encoded POST. The value of the data attrib will","# be the body we're looking for.","try",":","message_body","=","form_enc_parsed","[","'data'","]","[","0","]","except","(","KeyError",",","IndexError",")",":","logger",".","error","(","'form-encoded, compressed, upload did not contain a \"data\" key. From %s'",",","get_remote_address","(",")",")","raise","MalformedUploadError","(","\"No 'data' POST key\/value found. Check your POST key \"","\"name for spelling, and make sure you're passing a value.\"",")","else",":","logger",".","debug","(","'Request is *NOT* form-encoded'",")","else",":","logger",".","debug","(","'Content-Encoding indicates *not* compressed...'",")","# Uncompressed request. Bottle handles all of the parsing of the","# POST key\/vals, or un-encoded body.","data_key","=","request",".","forms",".","get","(","'data'",")","if","data_key",":","logger",".","info","(","'Request is form-encoded, uncompressed, from %s'","%","(","get_remote_address","(",")",")",")","# This is a form-encoded POST. Support the silly people.","message_body","=","data_key","else",":","logger",".","debug","(","'Plain POST request detected...'",")","# This is a non form-encoded POST body.","message_body","=","request",".","body",".","read","(",")","return","message_body"],"url":"https:\/\/github.com\/EDCD\/EDDN\/blob\/e23d5d3b29405a5154811876358c7170d6cd3ee0\/src\/eddn\/Gateway.py#L145-L207"}
5
+ {"nwo":"EDCD\/EDDN","sha":"e23d5d3b29405a5154811876358c7170d6cd3ee0","path":"src\/eddn\/Gateway.py","language":"python","identifier":"health_check","parameters":"()","argument_list":"","return_statement":"return Settings.EDDN_VERSION","docstring":"This should only be used by the gateway monitoring script. It is used\n to detect whether the gateway is still alive, and whether it should remain\n in the DNS rotation.","docstring_summary":"This should only be used by the gateway monitoring script. It is used\n to detect whether the gateway is still alive, and whether it should remain\n in the DNS rotation.","docstring_tokens":["This","should","only","be","used","by","the","gateway","monitoring","script",".","It","is","used","to","detect","whether","the","gateway","is","still","alive","and","whether","it","should","remain","in","the","DNS","rotation","."],"function":"def health_check():\n \"\"\"\n This should only be used by the gateway monitoring script. It is used\n to detect whether the gateway is still alive, and whether it should remain\n in the DNS rotation.\n \"\"\"\n return Settings.EDDN_VERSION","function_tokens":["def","health_check","(",")",":","return","Settings",".","EDDN_VERSION"],"url":"https:\/\/github.com\/EDCD\/EDDN\/blob\/e23d5d3b29405a5154811876358c7170d6cd3ee0\/src\/eddn\/Gateway.py#L326-L332"}
6
+ {"nwo":"EDCD\/EDDN","sha":"e23d5d3b29405a5154811876358c7170d6cd3ee0","path":"src\/eddn\/Relay.py","language":"python","identifier":"Relay.run","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Fires up the relay process.","docstring_summary":"Fires up the relay process.","docstring_tokens":["Fires","up","the","relay","process","."],"function":"def run(self):\n \"\"\"\n Fires up the relay process.\n \"\"\"\n # These form the connection to the Gateway daemon(s) upstream.\n context = zmq.Context()\n\n receiver = context.socket(zmq.SUB)\n\n # Filters on topics or not...\n if Settings.RELAY_RECEIVE_ONLY_GATEWAY_EXTRA_JSON is True:\n for schemaRef, schemaFile in Settings.GATEWAY_JSON_SCHEMAS.iteritems():\n receiver.setsockopt(zmq.SUBSCRIBE, schemaRef)\n for schemaRef, schemaFile in Settings.RELAY_EXTRA_JSON_SCHEMAS.iteritems():\n receiver.setsockopt(zmq.SUBSCRIBE, schemaRef)\n else:\n receiver.setsockopt(zmq.SUBSCRIBE, '')\n\n for binding in Settings.RELAY_RECEIVER_BINDINGS:\n # Relays bind upstream to an Announcer, or another Relay.\n receiver.connect(binding)\n\n sender = context.socket(zmq.PUB)\n sender.setsockopt(zmq.SNDHWM, 500)\n\n for binding in Settings.RELAY_SENDER_BINDINGS:\n # End users, or other relays, may attach here.\n sender.bind(binding)\n\n def relay_worker(message):\n \"\"\"\n This is the worker function that re-sends the incoming messages out\n to any subscribers.\n :param str message: A JSON string to re-broadcast.\n \"\"\"\n # Separate topic from message\n message = message.split(' |-| ')\n\n # Handle gateway not sending topic\n if len(message) > 1:\n message = message[1]\n else:\n message = message[0]\n\n message = zlib.decompress(message)\n json = simplejson.loads(message)\n\n # Handle duplicate message\n if Settings.RELAY_DUPLICATE_MAX_MINUTES:\n if duplicateMessages.isDuplicated(json):\n # We've already seen this message recently. Discard it.\n statsCollector.tally(\"duplicate\")\n return\n\n # Mask the uploader with a randomised nonce but still make it unique\n # for each uploader\n if 'uploaderID' in json['header']:\n json['header']['uploaderID'] = self.scramble_uploader(json['header']['uploaderID'])\n\n # Remove IP to end consumer\n if 'uploaderIP' in json['header']:\n del json['header']['uploaderIP']\n\n # Convert message back to JSON\n message = simplejson.dumps(json, sort_keys=True)\n\n # Recompress message\n message = zlib.compress(message)\n\n # Send message\n sender.send(message)\n statsCollector.tally(\"outbound\")\n\n while True:\n # For each incoming message, spawn a greenlet using the relay_worker\n # function.\n inboundMessage = receiver.recv()\n statsCollector.tally(\"inbound\")\n gevent.spawn(relay_worker, inboundMessage)","function_tokens":["def","run","(","self",")",":","# These form the connection to the Gateway daemon(s) upstream.","context","=","zmq",".","Context","(",")","receiver","=","context",".","socket","(","zmq",".","SUB",")","# Filters on topics or not...","if","Settings",".","RELAY_RECEIVE_ONLY_GATEWAY_EXTRA_JSON","is","True",":","for","schemaRef",",","schemaFile","in","Settings",".","GATEWAY_JSON_SCHEMAS",".","iteritems","(",")",":","receiver",".","setsockopt","(","zmq",".","SUBSCRIBE",",","schemaRef",")","for","schemaRef",",","schemaFile","in","Settings",".","RELAY_EXTRA_JSON_SCHEMAS",".","iteritems","(",")",":","receiver",".","setsockopt","(","zmq",".","SUBSCRIBE",",","schemaRef",")","else",":","receiver",".","setsockopt","(","zmq",".","SUBSCRIBE",",","''",")","for","binding","in","Settings",".","RELAY_RECEIVER_BINDINGS",":","# Relays bind upstream to an Announcer, or another Relay.","receiver",".","connect","(","binding",")","sender","=","context",".","socket","(","zmq",".","PUB",")","sender",".","setsockopt","(","zmq",".","SNDHWM",",","500",")","for","binding","in","Settings",".","RELAY_SENDER_BINDINGS",":","# End users, or other relays, may attach here.","sender",".","bind","(","binding",")","def","relay_worker","(","message",")",":","\"\"\"\n This is the worker function that re-sends the incoming messages out\n to any subscribers.\n :param str message: A JSON string to re-broadcast.\n \"\"\"","# Separate topic from message","message","=","message",".","split","(","' |-| '",")","# Handle gateway not sending topic","if","len","(","message",")",">","1",":","message","=","message","[","1","]","else",":","message","=","message","[","0","]","message","=","zlib",".","decompress","(","message",")","json","=","simplejson",".","loads","(","message",")","# Handle duplicate message","if","Settings",".","RELAY_DUPLICATE_MAX_MINUTES",":","if","duplicateMessages",".","isDuplicated","(","json",")",":","# We've already seen this message recently. Discard it.","statsCollector",".","tally","(","\"duplicate\"",")","return","# Mask the uploader with a randomised nonce but still make it unique","# for each uploader","if","'uploaderID'","in","json","[","'header'","]",":","json","[","'header'","]","[","'uploaderID'","]","=","self",".","scramble_uploader","(","json","[","'header'","]","[","'uploaderID'","]",")","# Remove IP to end consumer","if","'uploaderIP'","in","json","[","'header'","]",":","del","json","[","'header'","]","[","'uploaderIP'","]","# Convert message back to JSON","message","=","simplejson",".","dumps","(","json",",","sort_keys","=","True",")","# Recompress message","message","=","zlib",".","compress","(","message",")","# Send message","sender",".","send","(","message",")","statsCollector",".","tally","(","\"outbound\"",")","while","True",":","# For each incoming message, spawn a greenlet using the relay_worker","# function.","inboundMessage","=","receiver",".","recv","(",")","statsCollector",".","tally","(","\"inbound\"",")","gevent",".","spawn","(","relay_worker",",","inboundMessage",")"],"url":"https:\/\/github.com\/EDCD\/EDDN\/blob\/e23d5d3b29405a5154811876358c7170d6cd3ee0\/src\/eddn\/Relay.py#L100-L178"}
7
+ {"nwo":"EDCD\/EDDN","sha":"e23d5d3b29405a5154811876358c7170d6cd3ee0","path":"src\/eddn\/Relay.py","language":"python","identifier":"EnableCors.apply","parameters":"(self, fn, context)","argument_list":"","return_statement":"return _enable_cors","docstring":"Apply a CORS handler.\n\n Ref: <https:\/\/stackoverflow.com\/a\/17262900>","docstring_summary":"Apply a CORS handler.","docstring_tokens":["Apply","a","CORS","handler","."],"function":"def apply(self, fn, context):\n \"\"\"\n Apply a CORS handler.\n\n Ref: <https:\/\/stackoverflow.com\/a\/17262900>\n \"\"\"\n def _enable_cors(*args, **kwargs):\n \"\"\"Set CORS Headers.\"\"\"\n response.headers['Access-Control-Allow-Origin'] = '*'\n response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'\n response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'\n\n if request.method != 'OPTIONS':\n # actual request; reply with the actual response\n return fn(*args, **kwargs)\n\n return _enable_cors","function_tokens":["def","apply","(","self",",","fn",",","context",")",":","def","_enable_cors","(","*","args",",","*","*","kwargs",")",":","\"\"\"Set CORS Headers.\"\"\"","response",".","headers","[","'Access-Control-Allow-Origin'","]","=","'*'","response",".","headers","[","'Access-Control-Allow-Methods'","]","=","'GET, POST, PUT, OPTIONS'","response",".","headers","[","'Access-Control-Allow-Headers'","]","=","'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'","if","request",".","method","!=","'OPTIONS'",":","# actual request; reply with the actual response","return","fn","(","*","args",",","*","*","kwargs",")","return","_enable_cors"],"url":"https:\/\/github.com\/EDCD\/EDDN\/blob\/e23d5d3b29405a5154811876358c7170d6cd3ee0\/src\/eddn\/Relay.py#L187-L203"}
8
+ {"nwo":"EDCD\/EDDN","sha":"e23d5d3b29405a5154811876358c7170d6cd3ee0","path":"src\/eddn\/Bouncer.py","language":"python","identifier":"push_message","parameters":"(message_body)","argument_list":"","return_statement":"","docstring":"Spawned as a greenlet to push messages (strings) through ZeroMQ.\n This is a dumb method that just pushes strings; it assumes you've already validated\n and serialised as you want to.","docstring_summary":"Spawned as a greenlet to push messages (strings) through ZeroMQ.\n This is a dumb method that just pushes strings; it assumes you've already validated\n and serialised as you want to.","docstring_tokens":["Spawned","as","a","greenlet","to","push","messages","(","strings",")","through","ZeroMQ",".","This","is","a","dumb","method","that","just","pushes","strings",";","it","assumes","you","ve","already","validated","and","serialised","as","you","want","to","."],"function":"def push_message(message_body):\n \"\"\"\n Spawned as a greenlet to push messages (strings) through ZeroMQ.\n This is a dumb method that just pushes strings; it assumes you've already validated\n and serialised as you want to.\n \"\"\"\n try:\n r = requests.post(\n Settings.BOUNCER_LIVE_GATEWAY_URL,\n data=message_body,\n )\n\n except Exception as e:\n logger.error('Failed sending message on', exc_info=e)\n\n else:\n if r.status_code != requests.codes.ok:\n logger.error('Response from %s:\\n%s\\n' % (BOUNCER_LIVE_GATEWAY_URL,\n r.text))\n\n else:\n statsCollector.tally(\"outbound\")","function_tokens":["def","push_message","(","message_body",")",":","try",":","r","=","requests",".","post","(","Settings",".","BOUNCER_LIVE_GATEWAY_URL",",","data","=","message_body",",",")","except","Exception","as","e",":","logger",".","error","(","'Failed sending message on'",",","exc_info","=","e",")","else",":","if","r",".","status_code","!=","requests",".","codes",".","ok",":","logger",".","error","(","'Response from %s:\\n%s\\n'","%","(","BOUNCER_LIVE_GATEWAY_URL",",","r",".","text",")",")","else",":","statsCollector",".","tally","(","\"outbound\"",")"],"url":"https:\/\/github.com\/EDCD\/EDDN\/blob\/e23d5d3b29405a5154811876358c7170d6cd3ee0\/src\/eddn\/Bouncer.py#L89-L110"}
9
+ {"nwo":"EDCD\/EDDN","sha":"e23d5d3b29405a5154811876358c7170d6cd3ee0","path":"src\/eddn\/Bouncer.py","language":"python","identifier":"get_remote_address","parameters":"()","argument_list":"","return_statement":"return request.headers.get('X-Forwarded-For', request.remote_addr)","docstring":"Determines the address of the uploading client. First checks the for\n proxy-forwarded headers, then falls back to request.remote_addr.\n :rtype: str","docstring_summary":"Determines the address of the uploading client. First checks the for\n proxy-forwarded headers, then falls back to request.remote_addr.\n :rtype: str","docstring_tokens":["Determines","the","address","of","the","uploading","client",".","First","checks","the","for","proxy","-","forwarded","headers","then","falls","back","to","request",".","remote_addr",".",":","rtype",":","str"],"function":"def get_remote_address():\n \"\"\"\n Determines the address of the uploading client. First checks the for\n proxy-forwarded headers, then falls back to request.remote_addr.\n :rtype: str\n \"\"\"\n return request.headers.get('X-Forwarded-For', request.remote_addr)","function_tokens":["def","get_remote_address","(",")",":","return","request",".","headers",".","get","(","'X-Forwarded-For'",",","request",".","remote_addr",")"],"url":"https:\/\/github.com\/EDCD\/EDDN\/blob\/e23d5d3b29405a5154811876358c7170d6cd3ee0\/src\/eddn\/Bouncer.py#L113-L119"}
10
+ {"nwo":"EDCD\/EDDN","sha":"e23d5d3b29405a5154811876358c7170d6cd3ee0","path":"src\/eddn\/Bouncer.py","language":"python","identifier":"get_decompressed_message","parameters":"()","argument_list":"","return_statement":"return message_body","docstring":"For upload formats that support it, detect gzip Content-Encoding headers\n and de-compress on the fly.\n :rtype: str\n :returns: The de-compressed request body.","docstring_summary":"For upload formats that support it, detect gzip Content-Encoding headers\n and de-compress on the fly.\n :rtype: str\n :returns: The de-compressed request body.","docstring_tokens":["For","upload","formats","that","support","it","detect","gzip","Content","-","Encoding","headers","and","de","-","compress","on","the","fly",".",":","rtype",":","str",":","returns",":","The","de","-","compressed","request","body","."],"function":"def get_decompressed_message():\n \"\"\"\n For upload formats that support it, detect gzip Content-Encoding headers\n and de-compress on the fly.\n :rtype: str\n :returns: The de-compressed request body.\n \"\"\"\n content_encoding = request.headers.get('Content-Encoding', '')\n\n if content_encoding in ['gzip', 'deflate']:\n # Compressed request. We have to decompress the body, then figure out\n # if it's form-encoded.\n try:\n # Auto header checking.\n message_body = zlib.decompress(request.body.read(), 15 + 32)\n except zlib.error:\n # Negative wbits suppresses adler32 checksumming.\n message_body = zlib.decompress(request.body.read(), -15)\n\n # At this point, we're not sure whether we're dealing with a straight\n # un-encoded POST body, or a form-encoded POST. Attempt to parse the\n # body. If it's not form-encoded, this will return an empty dict.\n form_enc_parsed = urlparse.parse_qs(message_body)\n if form_enc_parsed:\n # This is a form-encoded POST. The value of the data attrib will\n # be the body we're looking for.\n try:\n message_body = form_enc_parsed['data'][0]\n except (KeyError, IndexError):\n raise MalformedUploadError(\n \"No 'data' POST key\/value found. Check your POST key \"\n \"name for spelling, and make sure you're passing a value.\"\n )\n else:\n # Uncompressed request. Bottle handles all of the parsing of the\n # POST key\/vals, or un-encoded body.\n data_key = request.forms.get('data')\n if data_key:\n # This is a form-encoded POST. Support the silly people.\n message_body = data_key\n else:\n # This is a non form-encoded POST body.\n message_body = request.body.read()\n\n return message_body","function_tokens":["def","get_decompressed_message","(",")",":","content_encoding","=","request",".","headers",".","get","(","'Content-Encoding'",",","''",")","if","content_encoding","in","[","'gzip'",",","'deflate'","]",":","# Compressed request. We have to decompress the body, then figure out","# if it's form-encoded.","try",":","# Auto header checking.","message_body","=","zlib",".","decompress","(","request",".","body",".","read","(",")",",","15","+","32",")","except","zlib",".","error",":","# Negative wbits suppresses adler32 checksumming.","message_body","=","zlib",".","decompress","(","request",".","body",".","read","(",")",",","-","15",")","# At this point, we're not sure whether we're dealing with a straight","# un-encoded POST body, or a form-encoded POST. Attempt to parse the","# body. If it's not form-encoded, this will return an empty dict.","form_enc_parsed","=","urlparse",".","parse_qs","(","message_body",")","if","form_enc_parsed",":","# This is a form-encoded POST. The value of the data attrib will","# be the body we're looking for.","try",":","message_body","=","form_enc_parsed","[","'data'","]","[","0","]","except","(","KeyError",",","IndexError",")",":","raise","MalformedUploadError","(","\"No 'data' POST key\/value found. Check your POST key \"","\"name for spelling, and make sure you're passing a value.\"",")","else",":","# Uncompressed request. Bottle handles all of the parsing of the","# POST key\/vals, or un-encoded body.","data_key","=","request",".","forms",".","get","(","'data'",")","if","data_key",":","# This is a form-encoded POST. Support the silly people.","message_body","=","data_key","else",":","# This is a non form-encoded POST body.","message_body","=","request",".","body",".","read","(",")","return","message_body"],"url":"https:\/\/github.com\/EDCD\/EDDN\/blob\/e23d5d3b29405a5154811876358c7170d6cd3ee0\/src\/eddn\/Bouncer.py#L122-L166"}
11
+ {"nwo":"EDCD\/EDDN","sha":"e23d5d3b29405a5154811876358c7170d6cd3ee0","path":"src\/eddn\/Bouncer.py","language":"python","identifier":"health_check","parameters":"()","argument_list":"","return_statement":"return Settings.EDDN_VERSION","docstring":"This should only be used by the gateway monitoring script. It is used\n to detect whether the gateway is still alive, and whether it should remain\n in the DNS rotation.","docstring_summary":"This should only be used by the gateway monitoring script. It is used\n to detect whether the gateway is still alive, and whether it should remain\n in the DNS rotation.","docstring_tokens":["This","should","only","be","used","by","the","gateway","monitoring","script",".","It","is","used","to","detect","whether","the","gateway","is","still","alive","and","whether","it","should","remain","in","the","DNS","rotation","."],"function":"def health_check():\n \"\"\"\n This should only be used by the gateway monitoring script. It is used\n to detect whether the gateway is still alive, and whether it should remain\n in the DNS rotation.\n \"\"\"\n return Settings.EDDN_VERSION","function_tokens":["def","health_check","(",")",":","return","Settings",".","EDDN_VERSION"],"url":"https:\/\/github.com\/EDCD\/EDDN\/blob\/e23d5d3b29405a5154811876358c7170d6cd3ee0\/src\/eddn\/Bouncer.py#L203-L209"}
12
+ {"nwo":"EDCD\/EDDN","sha":"e23d5d3b29405a5154811876358c7170d6cd3ee0","path":"src\/eddn\/Monitor.py","language":"python","identifier":"EnableCors.apply","parameters":"(self, fn, context)","argument_list":"","return_statement":"return _enable_cors","docstring":"Apply a CORS handler.\n\n Ref: <https:\/\/stackoverflow.com\/a\/17262900>","docstring_summary":"Apply a CORS handler.","docstring_tokens":["Apply","a","CORS","handler","."],"function":"def apply(self, fn, context):\n \"\"\"\n Apply a CORS handler.\n\n Ref: <https:\/\/stackoverflow.com\/a\/17262900>\n \"\"\"\n def _enable_cors(*args, **kwargs):\n \"\"\"Set CORS Headers.\"\"\"\n response.headers['Access-Control-Allow-Origin'] = '*'\n response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'\n response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'\n\n if request.method != 'OPTIONS':\n # actual request; reply with the actual response\n return fn(*args, **kwargs)\n\n return _enable_cors","function_tokens":["def","apply","(","self",",","fn",",","context",")",":","def","_enable_cors","(","*","args",",","*","*","kwargs",")",":","\"\"\"Set CORS Headers.\"\"\"","response",".","headers","[","'Access-Control-Allow-Origin'","]","=","'*'","response",".","headers","[","'Access-Control-Allow-Methods'","]","=","'GET, POST, PUT, OPTIONS'","response",".","headers","[","'Access-Control-Allow-Headers'","]","=","'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'","if","request",".","method","!=","'OPTIONS'",":","# actual request; reply with the actual response","return","fn","(","*","args",",","*","*","kwargs",")","return","_enable_cors"],"url":"https:\/\/github.com\/EDCD\/EDDN\/blob\/e23d5d3b29405a5154811876358c7170d6cd3ee0\/src\/eddn\/Monitor.py#L242-L258"}
13
+ {"nwo":"EDCD\/EDDN","sha":"e23d5d3b29405a5154811876358c7170d6cd3ee0","path":"src\/eddn\/conf\/Settings.py","language":"python","identifier":"loadConfig","parameters":"(cl_args)","argument_list":"","return_statement":"","docstring":"Load in a commandline-specified settings file, if applicable.\n\n A convenience method if you don't need other things specified as commandline\n options. Otherwise, point the filename to Settings.loadFrom().\n\n :param cl_args: An `argparse.parse_args()` return.","docstring_summary":"Load in a commandline-specified settings file, if applicable.","docstring_tokens":["Load","in","a","commandline","-","specified","settings","file","if","applicable","."],"function":"def loadConfig(cl_args):\n \"\"\"\n Load in a commandline-specified settings file, if applicable.\n\n A convenience method if you don't need other things specified as commandline\n options. Otherwise, point the filename to Settings.loadFrom().\n\n :param cl_args: An `argparse.parse_args()` return.\n \"\"\"\n if cl_args.config:\n Settings.loadFrom(cl_args.config)","function_tokens":["def","loadConfig","(","cl_args",")",":","if","cl_args",".","config",":","Settings",".","loadFrom","(","cl_args",".","config",")"],"url":"https:\/\/github.com\/EDCD\/EDDN\/blob\/e23d5d3b29405a5154811876358c7170d6cd3ee0\/src\/eddn\/conf\/Settings.py#L136-L146"}
EFForg__OpenWireless.jsonl ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/set_timezone.py","language":"python","identifier":"jsonrpc_set_timezone","parameters":"(etc=common.get_etc())","argument_list":"","return_statement":"","docstring":"Accept an olson-style set timezone, with parameters like so:\n\n {\"jsonrpc\":\"2.0\",\"method\":\"set_timezone\",\"params\":[\"timezonestring\"],\"id\":1}\n\n Set the local timezone on the router by looking up and placing the POSIX compatible timezone string\n in the \/etc\/TZ file.","docstring_summary":"Accept an olson-style set timezone, with parameters like so:","docstring_tokens":["Accept","an","olson","-","style","set","timezone","with","parameters","like","so",":"],"function":"def jsonrpc_set_timezone(etc=common.get_etc()):\n \"\"\"Accept an olson-style set timezone, with parameters like so:\n\n {\"jsonrpc\":\"2.0\",\"method\":\"set_timezone\",\"params\":[\"timezonestring\"],\"id\":1}\n\n Set the local timezone on the router by looking up and placing the POSIX compatible timezone string\n in the \/etc\/TZ file.\n \"\"\"\n\n data = json.loads(sys.stdin.read())\n try:\n params = data[\"params\"]\n tz_string = tz_info[params[0]]\n except KeyError, e:\n common.render_error(e.__str__())\n except IndexError, e:\n common.render_error(e.__str__())\n\n with open(os.path.join(etc, 'TZ'), \"w\") as tz_file:\n tz_file.write(tz_string)\n common.render_success({})\n return true","function_tokens":["def","jsonrpc_set_timezone","(","etc","=","common",".","get_etc","(",")",")",":","data","=","json",".","loads","(","sys",".","stdin",".","read","(",")",")","try",":","params","=","data","[","\"params\"","]","tz_string","=","tz_info","[","params","[","0","]","]","except","KeyError",",","e",":","common",".","render_error","(","e",".","__str__","(",")",")","except","IndexError",",","e",":","common",".","render_error","(","e",".","__str__","(",")",")","with","open","(","os",".","path",".","join","(","etc",",","'TZ'",")",",","\"w\"",")","as","tz_file",":","tz_file",".","write","(","tz_string",")","common",".","render_success","(","{","}",")","return","true"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/set_timezone.py#L9-L30"}
2
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/gen_tz_dictionary.py","language":"python","identifier":"get_zone_info","parameters":"(zone_dir=TZ_DB)","argument_list":"","return_statement":"","docstring":"get_zone_info - parse zone info from zoneinfo database into\n a python dictionary","docstring_summary":"get_zone_info - parse zone info from zoneinfo database into\n a python dictionary","docstring_tokens":["get_zone_info","-","parse","zone","info","from","zoneinfo","database","into","a","python","dictionary"],"function":"def get_zone_info(zone_dir=TZ_DB):\n \"\"\"\n get_zone_info - parse zone info from zoneinfo database into\n a python dictionary\n \"\"\"\n tzd = {}\n try:\n with open(os.path.join(zone_dir, \"zone.tab\"), \"r\") as zonetab:\n for line in zonetab:\n # Skip comments and whitespace\n if re.match(\"^#\", line) or re.match(\"^\\s+$\", line):\n continue\n\n # Olson zone paths are the third column in the table\n zone = re.split(\"\\s+\", line)[2]\n\n try:\n tzd[zone] = read_posix_zone(zone)\n except EnvironmentError: # IOError or OSError\n continue\n \n return tzd\n\n except EnvironmentError: # IOError or OSError\n return False","function_tokens":["def","get_zone_info","(","zone_dir","=","TZ_DB",")",":","tzd","=","{","}","try",":","with","open","(","os",".","path",".","join","(","zone_dir",",","\"zone.tab\"",")",",","\"r\"",")","as","zonetab",":","for","line","in","zonetab",":","# Skip comments and whitespace","if","re",".","match","(","\"^#\"",",","line",")","or","re",".","match","(","\"^\\s+$\"",",","line",")",":","continue","# Olson zone paths are the third column in the table","zone","=","re",".","split","(","\"\\s+\"",",","line",")","[","2","]","try",":","tzd","[","zone","]","=","read_posix_zone","(","zone",")","except","EnvironmentError",":","# IOError or OSError","continue","return","tzd","except","EnvironmentError",":","# IOError or OSError","return","False"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/gen_tz_dictionary.py#L25-L49"}
3
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/gen_tz_dictionary.py","language":"python","identifier":"read_posix_zone","parameters":"(zone)","argument_list":"","return_statement":"","docstring":"read_posix_zone - return the posix time zone for a give olson time zone\n @param string zone - olson time zone string","docstring_summary":"read_posix_zone - return the posix time zone for a give olson time zone","docstring_tokens":["read_posix_zone","-","return","the","posix","time","zone","for","a","give","olson","time","zone"],"function":"def read_posix_zone(zone):\n \"\"\"\n read_posix_zone - return the posix time zone for a give olson time zone\n @param string zone - olson time zone string\n \"\"\"\n with open(os.path.join(TZ_DB, zone), \"r\") as zonefile:\n # Return last line of file\n return list(zonefile)[-1].rstrip()","function_tokens":["def","read_posix_zone","(","zone",")",":","with","open","(","os",".","path",".","join","(","TZ_DB",",","zone",")",",","\"r\"",")","as","zonefile",":","# Return last line of file","return","list","(","zonefile",")","[","-","1","]",".","rstrip","(",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/gen_tz_dictionary.py#L52-L59"}
4
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/gen_tz_dictionary.py","language":"python","identifier":"write_zone_file","parameters":"(tz_dict)","argument_list":"","return_statement":"","docstring":"write_zone_file - write a timezone dictionary to a new python file\n @param dictionary tz_info - a dictionary mapping olson timezones to POSIX \n equivalents","docstring_summary":"write_zone_file - write a timezone dictionary to a new python file","docstring_tokens":["write_zone_file","-","write","a","timezone","dictionary","to","a","new","python","file"],"function":"def write_zone_file(tz_dict):\n \"\"\"\n write_zone_file - write a timezone dictionary to a new python file\n @param dictionary tz_info - a dictionary mapping olson timezones to POSIX \n equivalents\n \"\"\"\n with open(PY_TZ_FILE_PATH, 'w') as py_file:\n header = (\"#!\/usr\/bin\/python\\n\"\n \"\\\"\\\"\\\"\\ntz_info - maps Olson time zones to POSIX equivalents\\nAutogenerated by gen_tz_dictionary.py\\n\\\"\\\"\\\"\\n\"\n \"tz_info = {\\n\")\n\n footer = \"}\\n\"\n\n py_file.write(header)\n\n for otz in tz_dict:\n py_file.write(\" \\\"{0}\\\": \\\"{1}\\\",\\n\".format(otz,tz_dict[otz]))\n\n py_file.write(footer)","function_tokens":["def","write_zone_file","(","tz_dict",")",":","with","open","(","PY_TZ_FILE_PATH",",","'w'",")","as","py_file",":","header","=","(","\"#!\/usr\/bin\/python\\n\"","\"\\\"\\\"\\\"\\ntz_info - maps Olson time zones to POSIX equivalents\\nAutogenerated by gen_tz_dictionary.py\\n\\\"\\\"\\\"\\n\"","\"tz_info = {\\n\"",")","footer","=","\"}\\n\"","py_file",".","write","(","header",")","for","otz","in","tz_dict",":","py_file",".","write","(","\" \\\"{0}\\\": \\\"{1}\\\",\\n\"",".","format","(","otz",",","tz_dict","[","otz","]",")",")","py_file",".","write","(","footer",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/gen_tz_dictionary.py#L62-L80"}
5
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"default_path","parameters":"()","argument_list":"","return_statement":"return os.path.join(os.environ.get('OVERRIDE_ETC', '\/etc'), 'auth')","docstring":"The default path for auth files.\n\n Since auth is imported by common, not all functions from common are available\n yet, so we have to duplicate common.get_etc().","docstring_summary":"The default path for auth files.","docstring_tokens":["The","default","path","for","auth","files","."],"function":"def default_path():\n \"\"\"\n The default path for auth files.\n\n Since auth is imported by common, not all functions from common are available\n yet, so we have to duplicate common.get_etc().\n \"\"\"\n return os.path.join(os.environ.get('OVERRIDE_ETC', '\/etc'), 'auth')","function_tokens":["def","default_path","(",")",":","return","os",".","path",".","join","(","os",".","environ",".","get","(","'OVERRIDE_ETC'",",","'\/etc'",")",",","'auth'",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L45-L52"}
6
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"check_request","parameters":"(auth_dir = default_path())","argument_list":"","return_statement":"return True","docstring":"When processing a CGI request, validate that request is authenticated and, if\n it's a POST request, has a CSRF token.","docstring_summary":"When processing a CGI request, validate that request is authenticated and, if\n it's a POST request, has a CSRF token.","docstring_tokens":["When","processing","a","CGI","request","validate","that","request","is","authenticated","and","if","it","s","a","POST","request","has","a","CSRF","token","."],"function":"def check_request(auth_dir = default_path()):\n \"\"\"\n When processing a CGI request, validate that request is authenticated and, if\n it's a POST request, has a CSRF token.\n \"\"\"\n if (REQUEST_URI in os.environ and\n not os.environ[REQUEST_URI] in LOGGED_OUT_ENDPOINTS):\n a = Auth(auth_dir)\n a.check_authentication()\n if REQUEST_METHOD in os.environ and os.environ[REQUEST_METHOD] == \"POST\":\n a.check_csrf()\n return True","function_tokens":["def","check_request","(","auth_dir","=","default_path","(",")",")",":","if","(","REQUEST_URI","in","os",".","environ","and","not","os",".","environ","[","REQUEST_URI","]","in","LOGGED_OUT_ENDPOINTS",")",":","a","=","Auth","(","auth_dir",")","a",".","check_authentication","(",")","if","REQUEST_METHOD","in","os",".","environ","and","os",".","environ","[","REQUEST_METHOD","]","==","\"POST\"",":","a",".","check_csrf","(",")","return","True"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L54-L65"}
7
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"constant_time_equals","parameters":"(a, b)","argument_list":"","return_statement":"return result == 0","docstring":"Return True iff a == b, and do it in constant time.","docstring_summary":"Return True iff a == b, and do it in constant time.","docstring_tokens":["Return","True","iff","a","==","b","and","do","it","in","constant","time","."],"function":"def constant_time_equals(a, b):\n \"\"\"Return True iff a == b, and do it in constant time.\"\"\"\n a = bytearray(a)\n b = bytearray(b)\n if len(a) != len(b):\n return False\n\n result = 0\n for x, y in zip(a, b):\n result |= x ^ y\n return result == 0","function_tokens":["def","constant_time_equals","(","a",",","b",")",":","a","=","bytearray","(","a",")","b","=","bytearray","(","b",")","if","len","(","a",")","!=","len","(","b",")",":","return","False","result","=","0","for","x",",","y","in","zip","(","a",",","b",")",":","result","|=","x","^","y","return","result","==","0"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L67-L77"}
8
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.check_sane","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Check that the authentication data directory is owned by current user,\n with safe permissions. throw exception if not.","docstring_summary":"Check that the authentication data directory is owned by current user,\n with safe permissions. throw exception if not.","docstring_tokens":["Check","that","the","authentication","data","directory","is","owned","by","current","user","with","safe","permissions",".","throw","exception","if","not","."],"function":"def check_sane(self):\n \"\"\"\n Check that the authentication data directory is owned by current user,\n with safe permissions. throw exception if not.\n \"\"\"\n st = os.stat(self.path)\n if st.st_uid != os.getuid():\n raise Exception('Auth dir %s not owned by user %d.' % (\n self.path, os.getuid()))\n # Mode 16832 is equal to (stat.S_IFDIR | stat.S_IRWXU)\n # In other words, a directory with mode bits rwx------\n if st.st_mode != 16832:\n raise Exception('Auth dir %s not a dir or wrong permissions.' % self.path)","function_tokens":["def","check_sane","(","self",")",":","st","=","os",".","stat","(","self",".","path",")","if","st",".","st_uid","!=","os",".","getuid","(",")",":","raise","Exception","(","'Auth dir %s not owned by user %d.'","%","(","self",".","path",",","os",".","getuid","(",")",")",")","# Mode 16832 is equal to (stat.S_IFDIR | stat.S_IRWXU)","# In other words, a directory with mode bits rwx------","if","st",".","st_mode","!=","16832",":","raise","Exception","(","'Auth dir %s not a dir or wrong permissions.'","%","self",".","path",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L97-L109"}
9
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.write","parameters":"(self, filename, data)","argument_list":"","return_statement":"","docstring":"Save data into file, with mode bits rw-------.","docstring_summary":"Save data into file, with mode bits rw-------.","docstring_tokens":["Save","data","into","file","with","mode","bits","rw","-------","."],"function":"def write(self, filename, data):\n \"\"\"\n Save data into file, with mode bits rw-------.\n \"\"\"\n owner_rw = 0600\n fd = os.open(filename, os.O_WRONLY | os.O_CREAT, owner_rw)\n # In case file existed already with wrong permissions, fix them.\n os.chmod(filename, owner_rw)\n os.write(fd, data)\n os.close(fd)","function_tokens":["def","write","(","self",",","filename",",","data",")",":","owner_rw","=","0600","fd","=","os",".","open","(","filename",",","os",".","O_WRONLY","|","os",".","O_CREAT",",","owner_rw",")","# In case file existed already with wrong permissions, fix them.","os",".","chmod","(","filename",",","owner_rw",")","os",".","write","(","fd",",","data",")","os",".","close","(","fd",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L111-L120"}
10
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.rate_limit_remaining","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Return the number of failed passwords the can be entered before\n logins attempts are disabled for a day.\n\n The rate limit information is stored as a count of failed attempts so far.\n\n If there have been no failed attempts, or they were more than a day ago,\n treat that as zero failed attempts.","docstring_summary":"Return the number of failed passwords the can be entered before\n logins attempts are disabled for a day.","docstring_tokens":["Return","the","number","of","failed","passwords","the","can","be","entered","before","logins","attempts","are","disabled","for","a","day","."],"function":"def rate_limit_remaining(self):\n \"\"\"\n Return the number of failed passwords the can be entered before\n logins attempts are disabled for a day.\n\n The rate limit information is stored as a count of failed attempts so far.\n\n If there have been no failed attempts, or they were more than a day ago,\n treat that as zero failed attempts.\n \"\"\"\n if os.path.isfile(self.rate_limit_filename):\n st = os.stat(self.rate_limit_filename)\n if time.time() - st.st_ctime > self.RATE_LIMIT_DURATION:\n return self.RATE_LIMIT_COUNT\n else:\n with open(self.rate_limit_filename, 'r') as f:\n failed_login_attempts = int(f.read())\n return max(0, self.RATE_LIMIT_COUNT - failed_login_attempts)\n else:\n return self.RATE_LIMIT_COUNT","function_tokens":["def","rate_limit_remaining","(","self",")",":","if","os",".","path",".","isfile","(","self",".","rate_limit_filename",")",":","st","=","os",".","stat","(","self",".","rate_limit_filename",")","if","time",".","time","(",")","-","st",".","st_ctime",">","self",".","RATE_LIMIT_DURATION",":","return","self",".","RATE_LIMIT_COUNT","else",":","with","open","(","self",".","rate_limit_filename",",","'r'",")","as","f",":","failed_login_attempts","=","int","(","f",".","read","(",")",")","return","max","(","0",",","self",".","RATE_LIMIT_COUNT","-","failed_login_attempts",")","else",":","return","self",".","RATE_LIMIT_COUNT"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L122-L141"}
11
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.increment_rate_limit","parameters":"(self)","argument_list":"","return_statement":"","docstring":"On failed login attempt, increment the number of failed attempts.","docstring_summary":"On failed login attempt, increment the number of failed attempts.","docstring_tokens":["On","failed","login","attempt","increment","the","number","of","failed","attempts","."],"function":"def increment_rate_limit(self):\n \"\"\"On failed login attempt, increment the number of failed attempts.\"\"\"\n attempts = self.RATE_LIMIT_COUNT - self.rate_limit_remaining()\n attempts += 1\n self.write(self.rate_limit_filename, \"%d\" % attempts)","function_tokens":["def","increment_rate_limit","(","self",")",":","attempts","=","self",".","RATE_LIMIT_COUNT","-","self",".","rate_limit_remaining","(",")","attempts","+=","1","self",".","write","(","self",".","rate_limit_filename",",","\"%d\"","%","attempts",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L143-L147"}
12
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.password_exists","parameters":"(self)","argument_list":"","return_statement":"return os.path.isfile(self.password_filename)","docstring":"Return whether a password file exists.","docstring_summary":"Return whether a password file exists.","docstring_tokens":["Return","whether","a","password","file","exists","."],"function":"def password_exists(self):\n \"\"\"Return whether a password file exists.\"\"\"\n return os.path.isfile(self.password_filename)","function_tokens":["def","password_exists","(","self",")",":","return","os",".","path",".","isfile","(","self",".","password_filename",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L149-L151"}
13
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.is_password","parameters":"(self, candidate)","argument_list":"","return_statement":"","docstring":"Returns true iff the candidate password equals the stored one.","docstring_summary":"Returns true iff the candidate password equals the stored one.","docstring_tokens":["Returns","true","iff","the","candidate","password","equals","the","stored","one","."],"function":"def is_password(self, candidate):\n \"\"\"\n Returns true iff the candidate password equals the stored one.\n \"\"\"\n if self.rate_limit_remaining() > 0:\n with open(self.password_filename, 'r') as f:\n hashed = f.read().strip()\n b_valid = bytearray(hashed)\n b_guess = bytearray(pbkdf2.crypt(candidate, unicode(hashed)), 'utf-8')\n if constant_time_equals(b_valid, b_guess):\n return True\n else:\n # Increment rate limit on failures.\n self.increment_rate_limit()\n return False\n else:\n common.render_error('Too many failed login attempts. Try again tomorrow.')","function_tokens":["def","is_password","(","self",",","candidate",")",":","if","self",".","rate_limit_remaining","(",")",">","0",":","with","open","(","self",".","password_filename",",","'r'",")","as","f",":","hashed","=","f",".","read","(",")",".","strip","(",")","b_valid","=","bytearray","(","hashed",")","b_guess","=","bytearray","(","pbkdf2",".","crypt","(","candidate",",","unicode","(","hashed",")",")",",","'utf-8'",")","if","constant_time_equals","(","b_valid",",","b_guess",")",":","return","True","else",":","# Increment rate limit on failures.","self",".","increment_rate_limit","(",")","return","False","else",":","common",".","render_error","(","'Too many failed login attempts. Try again tomorrow.'",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L153-L169"}
14
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.save_password","parameters":"(self, new_password)","argument_list":"","return_statement":"return True","docstring":"Store a new password.\n Returns True is the password was stored and False if the password \n didn't fulfil all criteria.","docstring_summary":"Store a new password.\n Returns True is the password was stored and False if the password \n didn't fulfil all criteria.","docstring_tokens":["Store","a","new","password",".","Returns","True","is","the","password","was","stored","and","False","if","the","password","didn","t","fulfil","all","criteria","."],"function":"def save_password(self, new_password):\n \"\"\"\n Store a new password.\n Returns True is the password was stored and False if the password \n didn't fulfil all criteria.\n \"\"\"\n if len(new_password) < self.PASSWORD_LENGTH_MIN:\n return False\n # 55 iterations takes about 100 ms on a Netgear WNDR3800 or about 8ms on a\n # Core2 Duo at 1200 MHz.\n hashed = pbkdf2.crypt(new_password, iterations=55)\n self.write(self.password_filename, hashed)\n return True","function_tokens":["def","save_password","(","self",",","new_password",")",":","if","len","(","new_password",")","<","self",".","PASSWORD_LENGTH_MIN",":","return","False","# 55 iterations takes about 100 ms on a Netgear WNDR3800 or about 8ms on a","# Core2 Duo at 1200 MHz.","hashed","=","pbkdf2",".","crypt","(","new_password",",","iterations","=","55",")","self",".","write","(","self",".","password_filename",",","hashed",")","return","True"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L171-L183"}
15
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.get_csrf_token","parameters":"(self)","argument_list":"","return_statement":"return h.hexdigest()","docstring":"Generate a CSRF prevention token. We derive this token as the SHA256 hash\n of the auth token, which ensures the two are bound together, preventing\n cookie forcing attacks.\n\n Returns a valid CSRF prevention token.","docstring_summary":"Generate a CSRF prevention token. We derive this token as the SHA256 hash\n of the auth token, which ensures the two are bound together, preventing\n cookie forcing attacks.","docstring_tokens":["Generate","a","CSRF","prevention","token",".","We","derive","this","token","as","the","SHA256","hash","of","the","auth","token","which","ensures","the","two","are","bound","together","preventing","cookie","forcing","attacks","."],"function":"def get_csrf_token(self):\n \"\"\"\n Generate a CSRF prevention token. We derive this token as the SHA256 hash\n of the auth token, which ensures the two are bound together, preventing\n cookie forcing attacks.\n\n Returns a valid CSRF prevention token.\n \"\"\"\n h = hashlib.new('sha256')\n h.update(self.__current_authentication_token())\n return h.hexdigest()","function_tokens":["def","get_csrf_token","(","self",")",":","h","=","hashlib",".","new","(","'sha256'",")","h",".","update","(","self",".","__current_authentication_token","(",")",")","return","h",".","hexdigest","(",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L185-L195"}
16
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.is_csrf_token","parameters":"(self, candidate_csrf_token)","argument_list":"","return_statement":"return constant_time_equals(valid_token, candidate)","docstring":"Validate a presented CSRF token. Note that we validate by re-hashing the\n auth_token, rather than comparing directly to the csrf_token cookie. This\n prevents cookie forcing by requiring that the auth token and CSRF token be\n related.","docstring_summary":"Validate a presented CSRF token. Note that we validate by re-hashing the\n auth_token, rather than comparing directly to the csrf_token cookie. This\n prevents cookie forcing by requiring that the auth token and CSRF token be\n related.","docstring_tokens":["Validate","a","presented","CSRF","token",".","Note","that","we","validate","by","re","-","hashing","the","auth_token","rather","than","comparing","directly","to","the","csrf_token","cookie",".","This","prevents","cookie","forcing","by","requiring","that","the","auth","token","and","CSRF","token","be","related","."],"function":"def is_csrf_token(self, candidate_csrf_token):\n \"\"\"\n Validate a presented CSRF token. Note that we validate by re-hashing the\n auth_token, rather than comparing directly to the csrf_token cookie. This\n prevents cookie forcing by requiring that the auth token and CSRF token be\n related.\n \"\"\"\n valid_token = bytearray(self.get_csrf_token())\n candidate = bytearray(candidate_csrf_token)\n return constant_time_equals(valid_token, candidate)","function_tokens":["def","is_csrf_token","(","self",",","candidate_csrf_token",")",":","valid_token","=","bytearray","(","self",".","get_csrf_token","(",")",")","candidate","=","bytearray","(","candidate_csrf_token",")","return","constant_time_equals","(","valid_token",",","candidate",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L197-L206"}
17
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.check_csrf","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Get a CSRF token from CGI request headers and validate it. If validation\n fails, render an error and exit early.\n\n In our current JSONRPC style, we can send custom headers, so we look for the\n CSRF token in a header. We may switch to a form-submission-based approach,\n in which case we would need to update this code to look for a CSRF token in\n the POST parameters.","docstring_summary":"Get a CSRF token from CGI request headers and validate it. If validation\n fails, render an error and exit early.","docstring_tokens":["Get","a","CSRF","token","from","CGI","request","headers","and","validate","it",".","If","validation","fails","render","an","error","and","exit","early","."],"function":"def check_csrf(self):\n \"\"\"\n Get a CSRF token from CGI request headers and validate it. If validation\n fails, render an error and exit early.\n\n In our current JSONRPC style, we can send custom headers, so we look for the\n CSRF token in a header. We may switch to a form-submission-based approach,\n in which case we would need to update this code to look for a CSRF token in\n the POST parameters.\n \"\"\"\n if (self.HTTP_X_CSRF_TOKEN in os.environ and\n self.is_csrf_token(os.environ[self.HTTP_X_CSRF_TOKEN])):\n pass\n else:\n common.render_error('Invalid CSRF token.')","function_tokens":["def","check_csrf","(","self",")",":","if","(","self",".","HTTP_X_CSRF_TOKEN","in","os",".","environ","and","self",".","is_csrf_token","(","os",".","environ","[","self",".","HTTP_X_CSRF_TOKEN","]",")",")",":","pass","else",":","common",".","render_error","(","'Invalid CSRF token.'",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L208-L222"}
18
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.login_headers","parameters":"(self, tokens)","argument_list":"","return_statement":"return ('Set-Cookie: %s=true; path=\/\\n'\n 'Set-Cookie: %s=%s; path=\/; HttpOnly;%s\\n'\n 'Set-Cookie: %s=%s; path=\/;%s\\n' % (\n LOGGED_IN_COOKIE_NAME,\n AUTH_COOKIE_NAME, tokens.auth_token, secure_suffix,\n CSRF_COOKIE_NAME, tokens.csrf_token, secure_suffix))","docstring":"Return the HTTP headers required to log the user in. Specifically, set the\n auth cookie, the csrf token cookie, and an unsecured cookie logged_in=true,\n indicating the user is logged in even if the current request context doesn't\n have the auth cookies. The server should redirect users with the logged-in\n cookie to the HTTPS version of the site.\n\n Calling this method immediately regenerates the stored auth token,\n invalidating other active sessions.","docstring_summary":"Return the HTTP headers required to log the user in. Specifically, set the\n auth cookie, the csrf token cookie, and an unsecured cookie logged_in=true,\n indicating the user is logged in even if the current request context doesn't\n have the auth cookies. The server should redirect users with the logged-in\n cookie to the HTTPS version of the site.","docstring_tokens":["Return","the","HTTP","headers","required","to","log","the","user","in",".","Specifically","set","the","auth","cookie","the","csrf","token","cookie","and","an","unsecured","cookie","logged_in","=","true","indicating","the","user","is","logged","in","even","if","the","current","request","context","doesn","t","have","the","auth","cookies",".","The","server","should","redirect","users","with","the","logged","-","in","cookie","to","the","HTTPS","version","of","the","site","."],"function":"def login_headers(self, tokens):\n \"\"\"\n Return the HTTP headers required to log the user in. Specifically, set the\n auth cookie, the csrf token cookie, and an unsecured cookie logged_in=true,\n indicating the user is logged in even if the current request context doesn't\n have the auth cookies. The server should redirect users with the logged-in\n cookie to the HTTPS version of the site.\n\n Calling this method immediately regenerates the stored auth token,\n invalidating other active sessions.\n \"\"\"\n secure = 'HTTPS' in os.environ\n secure_suffix = ' secure;' if secure else ''\n return ('Set-Cookie: %s=true; path=\/\\n'\n 'Set-Cookie: %s=%s; path=\/; HttpOnly;%s\\n'\n 'Set-Cookie: %s=%s; path=\/;%s\\n' % (\n LOGGED_IN_COOKIE_NAME,\n AUTH_COOKIE_NAME, tokens.auth_token, secure_suffix,\n CSRF_COOKIE_NAME, tokens.csrf_token, secure_suffix))","function_tokens":["def","login_headers","(","self",",","tokens",")",":","secure","=","'HTTPS'","in","os",".","environ","secure_suffix","=","' secure;'","if","secure","else","''","return","(","'Set-Cookie: %s=true; path=\/\\n'","'Set-Cookie: %s=%s; path=\/; HttpOnly;%s\\n'","'Set-Cookie: %s=%s; path=\/;%s\\n'","%","(","LOGGED_IN_COOKIE_NAME",",","AUTH_COOKIE_NAME",",","tokens",".","auth_token",",","secure_suffix",",","CSRF_COOKIE_NAME",",","tokens",".","csrf_token",",","secure_suffix",")",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L224-L242"}
19
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.logout_headers","parameters":"(self)","argument_list":"","return_statement":"return ('Set-Cookie: %s=; path=\/; expires=Thu, 01 Jan 1970 00:00:00 GMT\\n'\n 'Set-Cookie: %s=; path=\/; expires=Thu, 01 Jan 1970 00:00:00 GMT\\n'\n 'Set-Cookie: %s=; path=\/; expires=Thu, 01 Jan 1970 00:00:00 GMT\\n' % (\n LOGGED_IN_COOKIE_NAME, AUTH_COOKIE_NAME,\n CSRF_COOKIE_NAME))","docstring":"Return the HTTP headers required to log the user out.\n\n Specifically, delete and invalidate the auth token and CSRF token.","docstring_summary":"Return the HTTP headers required to log the user out.","docstring_tokens":["Return","the","HTTP","headers","required","to","log","the","user","out","."],"function":"def logout_headers(self):\n \"\"\"\n Return the HTTP headers required to log the user out.\n\n Specifically, delete and invalidate the auth token and CSRF token.\n \"\"\"\n self.regenerate_authentication_token()\n return ('Set-Cookie: %s=; path=\/; expires=Thu, 01 Jan 1970 00:00:00 GMT\\n'\n 'Set-Cookie: %s=; path=\/; expires=Thu, 01 Jan 1970 00:00:00 GMT\\n'\n 'Set-Cookie: %s=; path=\/; expires=Thu, 01 Jan 1970 00:00:00 GMT\\n' % (\n LOGGED_IN_COOKIE_NAME, AUTH_COOKIE_NAME,\n CSRF_COOKIE_NAME))","function_tokens":["def","logout_headers","(","self",")",":","self",".","regenerate_authentication_token","(",")","return","(","'Set-Cookie: %s=; path=\/; expires=Thu, 01 Jan 1970 00:00:00 GMT\\n'","'Set-Cookie: %s=; path=\/; expires=Thu, 01 Jan 1970 00:00:00 GMT\\n'","'Set-Cookie: %s=; path=\/; expires=Thu, 01 Jan 1970 00:00:00 GMT\\n'","%","(","LOGGED_IN_COOKIE_NAME",",","AUTH_COOKIE_NAME",",","CSRF_COOKIE_NAME",")",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L252-L263"}
20
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.__current_authentication_token","parameters":"(self)","argument_list":"","return_statement":"return None","docstring":"Return the current authentication token if it still valid, else None.","docstring_summary":"Return the current authentication token if it still valid, else None.","docstring_tokens":["Return","the","current","authentication","token","if","it","still","valid","else","None","."],"function":"def __current_authentication_token(self):\n \"\"\"Return the current authentication token if it still valid, else None.\"\"\"\n if os.path.isfile(self.token_filename):\n with open(self.token_filename, 'r') as f:\n (stored_token, expires) = f.read().split(' ')\n t = time.time()\n if int(expires) > t:\n return stored_token\n return None","function_tokens":["def","__current_authentication_token","(","self",")",":","if","os",".","path",".","isfile","(","self",".","token_filename",")",":","with","open","(","self",".","token_filename",",","'r'",")","as","f",":","(","stored_token",",","expires",")","=","f",".","read","(",")",".","split","(","' '",")","t","=","time",".","time","(",")","if","int","(","expires",")",">","t",":","return","stored_token","return","None"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L265-L273"}
21
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.__valid_token_format","parameters":"(self, token)","argument_list":"","return_statement":"return True","docstring":"Basic length and character checking on tokens.","docstring_summary":"Basic length and character checking on tokens.","docstring_tokens":["Basic","length","and","character","checking","on","tokens","."],"function":"def __valid_token_format(self, token):\n \"\"\"Basic length and character checking on tokens.\"\"\"\n if len(token) != self.TOKEN_LENGTH * 2:\n return False\n for c in token:\n if c not in '01234567890abcdef':\n return False\n return True","function_tokens":["def","__valid_token_format","(","self",",","token",")",":","if","len","(","token",")","!=","self",".","TOKEN_LENGTH","*","2",":","return","False","for","c","in","token",":","if","c","not","in","'01234567890abcdef'",":","return","False","return","True"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L275-L282"}
22
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.is_authentication_token","parameters":"(self, candidate)","argument_list":"","return_statement":"","docstring":"Return true iff candidate authentication token matches stored one.","docstring_summary":"Return true iff candidate authentication token matches stored one.","docstring_tokens":["Return","true","iff","candidate","authentication","token","matches","stored","one","."],"function":"def is_authentication_token(self, candidate):\n \"\"\"Return true iff candidate authentication token matches stored one.\"\"\"\n current_token = self.__current_authentication_token()\n # TODO: Add expiry checking\n if (current_token and\n self.__valid_token_format(current_token) and\n self.__valid_token_format(candidate) and\n constant_time_equals(current_token, candidate)):\n return True\n else:\n return False","function_tokens":["def","is_authentication_token","(","self",",","candidate",")",":","current_token","=","self",".","__current_authentication_token","(",")","# TODO: Add expiry checking","if","(","current_token","and","self",".","__valid_token_format","(","current_token",")","and","self",".","__valid_token_format","(","candidate",")","and","constant_time_equals","(","current_token",",","candidate",")",")",":","return","True","else",":","return","False"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L284-L294"}
23
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.regenerate_authentication_token","parameters":"(self)","argument_list":"","return_statement":"return new_token","docstring":"Create and store a new random authentication token. Expires old sessions.","docstring_summary":"Create and store a new random authentication token. Expires old sessions.","docstring_tokens":["Create","and","store","a","new","random","authentication","token",".","Expires","old","sessions","."],"function":"def regenerate_authentication_token(self):\n \"\"\"\n Create and store a new random authentication token. Expires old sessions.\n \"\"\"\n new_token = os.urandom(self.TOKEN_LENGTH).encode('hex')\n expires = int(time.time()) + Auth.SESSION_DURATION\n self.write(self.token_filename, ('%s %d' % (new_token, expires)))\n return new_token","function_tokens":["def","regenerate_authentication_token","(","self",")",":","new_token","=","os",".","urandom","(","self",".","TOKEN_LENGTH",")",".","encode","(","'hex'",")","expires","=","int","(","time",".","time","(",")",")","+","Auth",".","SESSION_DURATION","self",".","write","(","self",".","token_filename",",","(","'%s %d'","%","(","new_token",",","expires",")",")",")","return","new_token"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L296-L303"}
24
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.check_authentication","parameters":"(self)","argument_list":"","return_statement":"","docstring":"In the context of a CGI request, check whether an authentication\n cookie is present and valid. If not, render an error.","docstring_summary":"In the context of a CGI request, check whether an authentication\n cookie is present and valid. If not, render an error.","docstring_tokens":["In","the","context","of","a","CGI","request","check","whether","an","authentication","cookie","is","present","and","valid",".","If","not","render","an","error","."],"function":"def check_authentication(self):\n \"\"\"\n In the context of a CGI request, check whether an authentication\n cookie is present and valid. If not, render an error.\n \"\"\"\n try:\n cookies = os.environ['HTTP_COOKIE'].split('; ')\n except KeyError:\n cookies = []\n for c in cookies:\n prefix = AUTH_COOKIE_NAME + '='\n if (c.startswith(prefix) and\n self.is_authentication_token(c[len(prefix):])):\n return True\n print 'Status: 403 Forbidden'\n print 'Content-Type: application\/json'\n print self.logout_headers()\n print json.JSONEncoder().encode({'error': 'Not authenticated.'})\n sys.exit(1)","function_tokens":["def","check_authentication","(","self",")",":","try",":","cookies","=","os",".","environ","[","'HTTP_COOKIE'","]",".","split","(","'; '",")","except","KeyError",":","cookies","=","[","]","for","c","in","cookies",":","prefix","=","AUTH_COOKIE_NAME","+","'='","if","(","c",".","startswith","(","prefix",")","and","self",".","is_authentication_token","(","c","[","len","(","prefix",")",":","]",")",")",":","return","True","print","'Status: 403 Forbidden'","print","'Content-Type: application\/json'","print","self",".","logout_headers","(",")","print","json",".","JSONEncoder","(",")",".","encode","(","{","'error'",":","'Not authenticated.'","}",")","sys",".","exit","(","1",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L305-L323"}
25
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/change_password.py","language":"python","identifier":"jsonrpc_change_password","parameters":"()","argument_list":"","return_statement":"","docstring":"Accept a JSONRPC-style change password, with parameters like so:\n\n {\"jsonrpc\":\"2.0\",\"method\":\"use.setpassword\",\"params\":[\"username\",\"password\", \"oldpassword\"],\"id\":1}\n\n On successful login, set two cookies: The auth cookie, used for primary\n authentication, is HttpOnly so JS cannot access it in case of an XSS. The\n CSRF token, used to validate that POSTs come from the same origin, is\n accessible to JS so it can be included in <form>'s.","docstring_summary":"Accept a JSONRPC-style change password, with parameters like so:","docstring_tokens":["Accept","a","JSONRPC","-","style","change","password","with","parameters","like","so",":"],"function":"def jsonrpc_change_password():\n \"\"\"Accept a JSONRPC-style change password, with parameters like so:\n\n {\"jsonrpc\":\"2.0\",\"method\":\"use.setpassword\",\"params\":[\"username\",\"password\", \"oldpassword\"],\"id\":1}\n\n On successful login, set two cookies: The auth cookie, used for primary\n authentication, is HttpOnly so JS cannot access it in case of an XSS. The\n CSRF token, used to validate that POSTs come from the same origin, is\n accessible to JS so it can be included in <form>'s.\n \"\"\"\n data = json.loads(sys.stdin.read())\n try:\n params = data[\"params\"]\n username = params[0]\n new_password = params[1]\n old_password = params[2]\n except KeyError, e:\n common.render_error(e.__str__())\n except IndexError, e:\n common.render_error(e.__str__())\n\n a = auth.Auth()\n if a.is_password(old_password):\n if not a.save_password(new_password):\n common.render_error(\"Invalid password supplied.\")\n remote_address = os.environ.get('REMOTE_ADDR')\n tokens = a.authenticate(new_password, remote_address)\n print \"Content-Type: application\/json\"\n print a.login_headers(tokens)\n print\n print \"{}\"\n else:\n common.render_error(\"Old password is incorrect.\")","function_tokens":["def","jsonrpc_change_password","(",")",":","data","=","json",".","loads","(","sys",".","stdin",".","read","(",")",")","try",":","params","=","data","[","\"params\"","]","username","=","params","[","0","]","new_password","=","params","[","1","]","old_password","=","params","[","2","]","except","KeyError",",","e",":","common",".","render_error","(","e",".","__str__","(",")",")","except","IndexError",",","e",":","common",".","render_error","(","e",".","__str__","(",")",")","a","=","auth",".","Auth","(",")","if","a",".","is_password","(","old_password",")",":","if","not","a",".","save_password","(","new_password",")",":","common",".","render_error","(","\"Invalid password supplied.\"",")","remote_address","=","os",".","environ",".","get","(","'REMOTE_ADDR'",")","tokens","=","a",".","authenticate","(","new_password",",","remote_address",")","print","\"Content-Type: application\/json\"","print","a",".","login_headers","(","tokens",")","print","print","\"{}\"","else",":","common",".","render_error","(","\"Old password is incorrect.\"",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/change_password.py#L9-L41"}
26
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/login.py","language":"python","identifier":"jsonrpc_login","parameters":"()","argument_list":"","return_statement":"","docstring":"Accept a JSONRPC-style login, with parameters like so:\n\n {\"jsonrpc\":\"2.0\",\"method\":\"login\",\"params\":[\"username\",\"password\"],\"id\":1}","docstring_summary":"Accept a JSONRPC-style login, with parameters like so:","docstring_tokens":["Accept","a","JSONRPC","-","style","login","with","parameters","like","so",":"],"function":"def jsonrpc_login():\n \"\"\"Accept a JSONRPC-style login, with parameters like so:\n\n {\"jsonrpc\":\"2.0\",\"method\":\"login\",\"params\":[\"username\",\"password\"],\"id\":1}\n \"\"\"\n data = json.loads(sys.stdin.read())\n try:\n params = data[\"params\"]\n username = params[0]\n password = params[1]\n except KeyError, e:\n common.render_error(e.__str__())\n a = auth.Auth()\n remote_address = os.environ.get('REMOTE_ADDR')\n tokens = a.authenticate(password, remote_address)\n if tokens:\n print \"Content-Type: application\/json\"\n print a.login_headers(tokens)\n print\n print \"{}\"\n else:\n common.render_error(\"Bad password.\")","function_tokens":["def","jsonrpc_login","(",")",":","data","=","json",".","loads","(","sys",".","stdin",".","read","(",")",")","try",":","params","=","data","[","\"params\"","]","username","=","params","[","0","]","password","=","params","[","1","]","except","KeyError",",","e",":","common",".","render_error","(","e",".","__str__","(",")",")","a","=","auth",".","Auth","(",")","remote_address","=","os",".","environ",".","get","(","'REMOTE_ADDR'",")","tokens","=","a",".","authenticate","(","password",",","remote_address",")","if","tokens",":","print","\"Content-Type: application\/json\"","print","a",".","login_headers","(","tokens",")","print","print","\"{}\"","else",":","common",".","render_error","(","\"Bad password.\"",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/login.py#L9-L30"}
27
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/settings.py","language":"python","identifier":"openwrt_release","parameters":"()","argument_list":"","return_statement":"return (items.get('DISTRIB_DESCRIPTION', 'Unknown'),\n items.get('DISTRIB_RELEASE_DATE', 0))","docstring":"Returns a tuple of (software_version, release date)","docstring_summary":"Returns a tuple of (software_version, release date)","docstring_tokens":["Returns","a","tuple","of","(","software_version","release","date",")"],"function":"def openwrt_release():\n \"\"\"Returns a tuple of (software_version, release date)\"\"\"\n items = {}\n try:\n with open(os.path.join(common.get_etc(), 'openwrt_release')) as f:\n for line in f:\n key, val = line.split('=')\n # Strip trailing newline, and any wrapping quotes.\n items[key] = val.strip('\"\\n')\n except IOError:\n pass\n return (items.get('DISTRIB_DESCRIPTION', 'Unknown'),\n items.get('DISTRIB_RELEASE_DATE', 0))","function_tokens":["def","openwrt_release","(",")",":","items","=","{","}","try",":","with","open","(","os",".","path",".","join","(","common",".","get_etc","(",")",",","'openwrt_release'",")",")","as","f",":","for","line","in","f",":","key",",","val","=","line",".","split","(","'='",")","# Strip trailing newline, and any wrapping quotes.","items","[","key","]","=","val",".","strip","(","'\"\\n'",")","except","IOError",":","pass","return","(","items",".","get","(","'DISTRIB_DESCRIPTION'",",","'Unknown'",")",",","items",".","get","(","'DISTRIB_RELEASE_DATE'",",","0",")",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/settings.py#L11-L23"}
28
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/dashboard.py","language":"python","identifier":"get_dashboard","parameters":"()","argument_list":"","return_statement":"","docstring":"Render JSON dashboard data response.","docstring_summary":"Render JSON dashboard data response.","docstring_tokens":["Render","JSON","dashboard","data","response","."],"function":"def get_dashboard():\n \"\"\"Render JSON dashboard data response.\"\"\"\n def get_ping_output():\n \"\"\"Ping a server and return the output\"\"\"\n try:\n return run.check_output(\n ['\/usr\/bin\/sudo', '\/bin\/ping', '-c1', 'eff.org'])\n except subprocess.CalledProcessError:\n return 'N\/A'\n\n ping_output = get_ping_output()\n\n if \"N\/A\" in ping_output:\n connected = False\n ping_speed = \"N\/A\"\n else:\n connected = True\n ping_speed = int(float(ping_output.split(' ')[11].split('=')[1]))\n\n wan_ip = ip_address_retriever.get_external_ip_address()\n lan_ip = ip_address_retriever.get_internal_ip_address(\"ge00\")\n\n ssid = uci.get(\"wireless.@wifi-iface[2].ssid\")\n\n private_wifi_on = check_interface_connection.enabled(2)\n openwireless_on = check_interface_connection.enabled(1)\n\n def get_openwireless_use():\n use_in_bytes = float(uci.get(\"openwireless.use_since_last_ui_reset\"))\n use_in_mbs = use_in_bytes\/1000000.0\n return(str(int(use_in_mbs)))\n\n openwireless_use = get_openwireless_use()\n\n last_update_path = os.path.join(common.get_etc(), \"last_update_check\")\n if os.path.exists(last_update_path):\n [last_check_date,avail] = open(last_update_path).read().split()\n else:\n [last_check_date, avail] = (0, \"N\")\n\n update_check_datetime = datetime.datetime.utcfromtimestamp(float(last_check_date)\/1000)\n\n if (avail==\"Y\"):\n update_available = True\n else:\n update_available = False\n\n activateCap = (uci.get(\"openwireless.activatedatacap\") == \"Yes\")\n\n result = {\n \"id\": 1,\n \"jsonrpc\": \"2.0\",\n \"result\": {\n \"internet\": {\n \"name\": \"Internet\",\n \"uploadSpeed\": \"...\",\n \"uploadSpeedMetric\": \"Mb\/s\",\n \"downloadSpeed\": \"...\",\n \"downloadSpeedMetric\": \"Mb\/s\",\n \"pingSpeed\": ping_speed,\n \"pingSpeedMetric\": \"ms\",\n \"connected\": connected\n },\n \"lanNetwork\": {\n \"name\": \"LAN Network\",\n \"uploadSpeed\": \"...\",\n \"uploadSpeedMetric\": \"Mb\/s\",\n \"downloadSpeed\": \"...\",\n \"downloadSpeedMetric\": \"Mb\/s\",\n \"devices\": \"0\"\n },\n \"privateWifi\": {\n \"name\": \"Private WiFi\",\n \"uploadSpeed\": \"...\",\n \"uploadSpeedMetric\": \"Mb\/s\",\n \"downloadSpeed\": \"...\",\n \"downloadSpeedMetric\": \"Mb\/s\",\n \"devices\": \"0\",\n \"on\": private_wifi_on,\n \"ssid\": ssid\n },\n \"openWireless\": {\n \"name\": \"Openwireless.org\",\n \"uploadSpeed\": \"...\",\n \"uploadSpeedMetric\": \"Mb\/s\",\n \"downloadSpeed\": \"...\",\n \"downloadSpeedMetric\": \"Mb\/s\",\n \"maxBandwidthPercent\":\n uci.get(\"openwireless.maxbandwidthpercentage\"),\n \"activateDataCap\": activateCap,\n \"maxMonthlyBandwidth\":\n uci.get(\"openwireless.maxmonthlybandwidth\"),\n \"maxMonthlyBandwidthMetric\": \"Mb\",\n \"monthlyBandwidthUsage\": openwireless_use,\n \"on\": openwireless_on\n },\n \"updateAvailable\": update_available,\n \"lastCheckDate\": update_check_datetime,\n \"wanIp\": wan_ip,\n \"lanIp\": lan_ip,\n \"previousLogin\" : audit.previous_login(),\n }\n }\n common.render_success(result)","function_tokens":["def","get_dashboard","(",")",":","def","get_ping_output","(",")",":","\"\"\"Ping a server and return the output\"\"\"","try",":","return","run",".","check_output","(","[","'\/usr\/bin\/sudo'",",","'\/bin\/ping'",",","'-c1'",",","'eff.org'","]",")","except","subprocess",".","CalledProcessError",":","return","'N\/A'","ping_output","=","get_ping_output","(",")","if","\"N\/A\"","in","ping_output",":","connected","=","False","ping_speed","=","\"N\/A\"","else",":","connected","=","True","ping_speed","=","int","(","float","(","ping_output",".","split","(","' '",")","[","11","]",".","split","(","'='",")","[","1","]",")",")","wan_ip","=","ip_address_retriever",".","get_external_ip_address","(",")","lan_ip","=","ip_address_retriever",".","get_internal_ip_address","(","\"ge00\"",")","ssid","=","uci",".","get","(","\"wireless.@wifi-iface[2].ssid\"",")","private_wifi_on","=","check_interface_connection",".","enabled","(","2",")","openwireless_on","=","check_interface_connection",".","enabled","(","1",")","def","get_openwireless_use","(",")",":","use_in_bytes","=","float","(","uci",".","get","(","\"openwireless.use_since_last_ui_reset\"",")",")","use_in_mbs","=","use_in_bytes","\/","1000000.0","return","(","str","(","int","(","use_in_mbs",")",")",")","openwireless_use","=","get_openwireless_use","(",")","last_update_path","=","os",".","path",".","join","(","common",".","get_etc","(",")",",","\"last_update_check\"",")","if","os",".","path",".","exists","(","last_update_path",")",":","[","last_check_date",",","avail","]","=","open","(","last_update_path",")",".","read","(",")",".","split","(",")","else",":","[","last_check_date",",","avail","]","=","(","0",",","\"N\"",")","update_check_datetime","=","datetime",".","datetime",".","utcfromtimestamp","(","float","(","last_check_date",")","\/","1000",")","if","(","avail","==","\"Y\"",")",":","update_available","=","True","else",":","update_available","=","False","activateCap","=","(","uci",".","get","(","\"openwireless.activatedatacap\"",")","==","\"Yes\"",")","result","=","{","\"id\"",":","1",",","\"jsonrpc\"",":","\"2.0\"",",","\"result\"",":","{","\"internet\"",":","{","\"name\"",":","\"Internet\"",",","\"uploadSpeed\"",":","\"...\"",",","\"uploadSpeedMetric\"",":","\"Mb\/s\"",",","\"downloadSpeed\"",":","\"...\"",",","\"downloadSpeedMetric\"",":","\"Mb\/s\"",",","\"pingSpeed\"",":","ping_speed",",","\"pingSpeedMetric\"",":","\"ms\"",",","\"connected\"",":","connected","}",",","\"lanNetwork\"",":","{","\"name\"",":","\"LAN Network\"",",","\"uploadSpeed\"",":","\"...\"",",","\"uploadSpeedMetric\"",":","\"Mb\/s\"",",","\"downloadSpeed\"",":","\"...\"",",","\"downloadSpeedMetric\"",":","\"Mb\/s\"",",","\"devices\"",":","\"0\"","}",",","\"privateWifi\"",":","{","\"name\"",":","\"Private WiFi\"",",","\"uploadSpeed\"",":","\"...\"",",","\"uploadSpeedMetric\"",":","\"Mb\/s\"",",","\"downloadSpeed\"",":","\"...\"",",","\"downloadSpeedMetric\"",":","\"Mb\/s\"",",","\"devices\"",":","\"0\"",",","\"on\"",":","private_wifi_on",",","\"ssid\"",":","ssid","}",",","\"openWireless\"",":","{","\"name\"",":","\"Openwireless.org\"",",","\"uploadSpeed\"",":","\"...\"",",","\"uploadSpeedMetric\"",":","\"Mb\/s\"",",","\"downloadSpeed\"",":","\"...\"",",","\"downloadSpeedMetric\"",":","\"Mb\/s\"",",","\"maxBandwidthPercent\"",":","uci",".","get","(","\"openwireless.maxbandwidthpercentage\"",")",",","\"activateDataCap\"",":","activateCap",",","\"maxMonthlyBandwidth\"",":","uci",".","get","(","\"openwireless.maxmonthlybandwidth\"",")",",","\"maxMonthlyBandwidthMetric\"",":","\"Mb\"",",","\"monthlyBandwidthUsage\"",":","openwireless_use",",","\"on\"",":","openwireless_on","}",",","\"updateAvailable\"",":","update_available",",","\"lastCheckDate\"",":","update_check_datetime",",","\"wanIp\"",":","wan_ip",",","\"lanIp\"",":","lan_ip",",","\"previousLogin\"",":","audit",".","previous_login","(",")",",","}","}","common",".","render_success","(","result",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/dashboard.py#L15-L118"}
29
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/ssh_key.py","language":"python","identifier":"key_locked","parameters":"(authorized_keys = AUTHORIZED_KEYS)","argument_list":"","return_statement":"return (os.path.exists(authorized_keys) and\n uci.get('openwireless.ssh_success') == 'true')","docstring":"Return whether a key is locked in place - i.e. a key is stored and\n user has logged in once via SSH.","docstring_summary":"Return whether a key is locked in place - i.e. a key is stored and\n user has logged in once via SSH.","docstring_tokens":["Return","whether","a","key","is","locked","in","place","-","i",".","e",".","a","key","is","stored","and","user","has","logged","in","once","via","SSH","."],"function":"def key_locked(authorized_keys = AUTHORIZED_KEYS):\n \"\"\"\n Return whether a key is locked in place - i.e. a key is stored and\n user has logged in once via SSH.\n \"\"\"\n return (os.path.exists(authorized_keys) and\n uci.get('openwireless.ssh_success') == 'true')","function_tokens":["def","key_locked","(","authorized_keys","=","AUTHORIZED_KEYS",")",":","return","(","os",".","path",".","exists","(","authorized_keys",")","and","uci",".","get","(","'openwireless.ssh_success'",")","==","'true'",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/ssh_key.py#L27-L33"}
30
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/pbkdf2.py","language":"python","identifier":"crypt","parameters":"(word, salt=None, iterations=None)","argument_list":"","return_statement":"return salt + \"$\" + b64encode(rawhash, \".\/\")","docstring":"PBKDF2-based unix crypt(3) replacement.\n\n The number of iterations specified in the salt overrides the 'iterations'\n parameter.\n\n The effective hash length is 192 bits.","docstring_summary":"PBKDF2-based unix crypt(3) replacement.","docstring_tokens":["PBKDF2","-","based","unix","crypt","(","3",")","replacement","."],"function":"def crypt(word, salt=None, iterations=None):\n \"\"\"PBKDF2-based unix crypt(3) replacement.\n\n The number of iterations specified in the salt overrides the 'iterations'\n parameter.\n\n The effective hash length is 192 bits.\n \"\"\"\n\n # Generate a (pseudo-)random salt if the user hasn't provided one.\n if salt is None:\n salt = _makesalt()\n\n # salt must be a string or the us-ascii subset of unicode\n if isunicode(salt):\n salt = salt.encode('us-ascii').decode('us-ascii')\n elif isbytes(salt):\n salt = salt.decode('us-ascii')\n else:\n raise TypeError(\"salt must be a string\")\n\n # word must be a string or unicode (in the latter case, we convert to UTF-8)\n if isunicode(word):\n word = word.encode(\"UTF-8\")\n elif not isbytes(word):\n raise TypeError(\"word must be a string or unicode\")\n\n # Try to extract the real salt and iteration count from the salt\n if salt.startswith(\"$p5k2$\"):\n (iterations, salt, dummy) = salt.split(\"$\")[2:5]\n if iterations == \"\":\n iterations = 400\n else:\n converted = int(iterations, 16)\n if iterations != \"%x\" % converted: # lowercase hex, minimum digits\n raise ValueError(\"Invalid salt\")\n iterations = converted\n if not (iterations >= 1):\n raise ValueError(\"Invalid salt\")\n\n # Make sure the salt matches the allowed character set\n allowed = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.\/\"\n for ch in salt:\n if ch not in allowed:\n raise ValueError(\"Illegal character %r in salt\" % (ch,))\n\n if iterations is None or iterations == 400:\n iterations = 400\n salt = \"$p5k2$$\" + salt\n else:\n salt = \"$p5k2$%x$%s\" % (iterations, salt)\n rawhash = PBKDF2(word, salt, iterations).read(24)\n return salt + \"$\" + b64encode(rawhash, \".\/\")","function_tokens":["def","crypt","(","word",",","salt","=","None",",","iterations","=","None",")",":","# Generate a (pseudo-)random salt if the user hasn't provided one.","if","salt","is","None",":","salt","=","_makesalt","(",")","# salt must be a string or the us-ascii subset of unicode","if","isunicode","(","salt",")",":","salt","=","salt",".","encode","(","'us-ascii'",")",".","decode","(","'us-ascii'",")","elif","isbytes","(","salt",")",":","salt","=","salt",".","decode","(","'us-ascii'",")","else",":","raise","TypeError","(","\"salt must be a string\"",")","# word must be a string or unicode (in the latter case, we convert to UTF-8)","if","isunicode","(","word",")",":","word","=","word",".","encode","(","\"UTF-8\"",")","elif","not","isbytes","(","word",")",":","raise","TypeError","(","\"word must be a string or unicode\"",")","# Try to extract the real salt and iteration count from the salt","if","salt",".","startswith","(","\"$p5k2$\"",")",":","(","iterations",",","salt",",","dummy",")","=","salt",".","split","(","\"$\"",")","[","2",":","5","]","if","iterations","==","\"\"",":","iterations","=","400","else",":","converted","=","int","(","iterations",",","16",")","if","iterations","!=","\"%x\"","%","converted",":","# lowercase hex, minimum digits","raise","ValueError","(","\"Invalid salt\"",")","iterations","=","converted","if","not","(","iterations",">=","1",")",":","raise","ValueError","(","\"Invalid salt\"",")","# Make sure the salt matches the allowed character set","allowed","=","\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.\/\"","for","ch","in","salt",":","if","ch","not","in","allowed",":","raise","ValueError","(","\"Illegal character %r in salt\"","%","(","ch",",",")",")","if","iterations","is","None","or","iterations","==","400",":","iterations","=","400","salt","=","\"$p5k2$$\"","+","salt","else",":","salt","=","\"$p5k2$%x$%s\"","%","(","iterations",",","salt",")","rawhash","=","PBKDF2","(","word",",","salt",",","iterations",")",".","read","(","24",")","return","salt","+","\"$\"","+","b64encode","(","rawhash",",","\".\/\"",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/pbkdf2.py#L229-L281"}
31
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/pbkdf2.py","language":"python","identifier":"_makesalt","parameters":"()","argument_list":"","return_statement":"return b64encode(binarysalt, \".\/\")","docstring":"Return a 48-bit pseudorandom salt for crypt().\n\n This function is not suitable for generating cryptographic secrets.","docstring_summary":"Return a 48-bit pseudorandom salt for crypt().","docstring_tokens":["Return","a","48","-","bit","pseudorandom","salt","for","crypt","()","."],"function":"def _makesalt():\n \"\"\"Return a 48-bit pseudorandom salt for crypt().\n\n This function is not suitable for generating cryptographic secrets.\n \"\"\"\n binarysalt = b(\"\").join([pack(\"@H\", randint(0, 0xffff)) for i in range(3)])\n return b64encode(binarysalt, \".\/\")","function_tokens":["def","_makesalt","(",")",":","binarysalt","=","b","(","\"\"",")",".","join","(","[","pack","(","\"@H\"",",","randint","(","0",",","0xffff",")",")","for","i","in","range","(","3",")","]",")","return","b64encode","(","binarysalt",",","\".\/\"",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/pbkdf2.py#L288-L294"}
32
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/pbkdf2.py","language":"python","identifier":"PBKDF2._pseudorandom","parameters":"(self, key, msg)","argument_list":"","return_statement":"return self.__macmodule.new(key=key, msg=msg,\n digestmod=self.__digestmodule).digest()","docstring":"Pseudorandom function. e.g. HMAC-SHA1","docstring_summary":"Pseudorandom function. e.g. HMAC-SHA1","docstring_tokens":["Pseudorandom","function",".","e",".","g",".","HMAC","-","SHA1"],"function":"def _pseudorandom(self, key, msg):\n \"\"\"Pseudorandom function. e.g. HMAC-SHA1\"\"\"\n return self.__macmodule.new(key=key, msg=msg,\n digestmod=self.__digestmodule).digest()","function_tokens":["def","_pseudorandom","(","self",",","key",",","msg",")",":","return","self",".","__macmodule",".","new","(","key","=","key",",","msg","=","msg",",","digestmod","=","self",".","__digestmodule",")",".","digest","(",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/pbkdf2.py#L142-L145"}
33
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/pbkdf2.py","language":"python","identifier":"PBKDF2.read","parameters":"(self, bytes)","argument_list":"","return_statement":"return retval","docstring":"Read the specified number of key bytes.","docstring_summary":"Read the specified number of key bytes.","docstring_tokens":["Read","the","specified","number","of","key","bytes","."],"function":"def read(self, bytes):\n \"\"\"Read the specified number of key bytes.\"\"\"\n if self.closed:\n raise ValueError(\"file-like object is closed\")\n\n size = len(self.__buf)\n blocks = [self.__buf]\n i = self.__blockNum\n while size < bytes:\n i += 1\n if i > _0xffffffffL or i < 1:\n # We could return \"\" here, but\n raise OverflowError(\"derived key too long\")\n block = self.__f(i)\n blocks.append(block)\n size += len(block)\n buf = b(\"\").join(blocks)\n retval = buf[:bytes]\n self.__buf = buf[bytes:]\n self.__blockNum = i\n return retval","function_tokens":["def","read","(","self",",","bytes",")",":","if","self",".","closed",":","raise","ValueError","(","\"file-like object is closed\"",")","size","=","len","(","self",".","__buf",")","blocks","=","[","self",".","__buf","]","i","=","self",".","__blockNum","while","size","<","bytes",":","i","+=","1","if","i",">","_0xffffffffL","or","i","<","1",":","# We could return \"\" here, but","raise","OverflowError","(","\"derived key too long\"",")","block","=","self",".","__f","(","i",")","blocks",".","append","(","block",")","size","+=","len","(","block",")","buf","=","b","(","\"\"",")",".","join","(","blocks",")","retval","=","buf","[",":","bytes","]","self",".","__buf","=","buf","[","bytes",":","]","self",".","__blockNum","=","i","return","retval"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/pbkdf2.py#L147-L167"}
34
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/pbkdf2.py","language":"python","identifier":"PBKDF2.hexread","parameters":"(self, octets)","argument_list":"","return_statement":"return b2a_hex(self.read(octets))","docstring":"Read the specified number of octets. Return them as hexadecimal.\n\n Note that len(obj.hexread(n)) == 2*n.","docstring_summary":"Read the specified number of octets. Return them as hexadecimal.","docstring_tokens":["Read","the","specified","number","of","octets",".","Return","them","as","hexadecimal","."],"function":"def hexread(self, octets):\n \"\"\"Read the specified number of octets. Return them as hexadecimal.\n\n Note that len(obj.hexread(n)) == 2*n.\n \"\"\"\n return b2a_hex(self.read(octets))","function_tokens":["def","hexread","(","self",",","octets",")",":","return","b2a_hex","(","self",".","read","(","octets",")",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/pbkdf2.py#L179-L184"}
35
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/pbkdf2.py","language":"python","identifier":"PBKDF2.close","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Close the stream.","docstring_summary":"Close the stream.","docstring_tokens":["Close","the","stream","."],"function":"def close(self):\n \"\"\"Close the stream.\"\"\"\n if not self.closed:\n del self.__passphrase\n del self.__salt\n del self.__iterations\n del self.__prf\n del self.__blockNum\n del self.__buf\n self.closed = True","function_tokens":["def","close","(","self",")",":","if","not","self",".","closed",":","del","self",".","__passphrase","del","self",".","__salt","del","self",".","__iterations","del","self",".","__prf","del","self",".","__blockNum","del","self",".","__buf","self",".","closed","=","True"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/pbkdf2.py#L218-L227"}
36
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/change_password_first_time.py","language":"python","identifier":"jsonrpc_change_password_first_time","parameters":"(auth_path)","argument_list":"","return_statement":"","docstring":"Accept a JSONRPC-style change password, with parameters like so:\n\n {\"jsonrpc\":\"2.0\",\"method\":\"setpassword\",\"params\":[\"username\",\"password\"],\"id\":1}\n\n This endpoint does not require the user to provide their existing password,\n but it can only be used when setting the administrator password for the first\n time. If a password is already set, this endpoint will return 403.\n\n This needs to be a separate endpoint from change_password because it is\n listed in auth.py as not requiring authentication cookies.","docstring_summary":"Accept a JSONRPC-style change password, with parameters like so:","docstring_tokens":["Accept","a","JSONRPC","-","style","change","password","with","parameters","like","so",":"],"function":"def jsonrpc_change_password_first_time(auth_path):\n \"\"\"Accept a JSONRPC-style change password, with parameters like so:\n\n {\"jsonrpc\":\"2.0\",\"method\":\"setpassword\",\"params\":[\"username\",\"password\"],\"id\":1}\n\n This endpoint does not require the user to provide their existing password,\n but it can only be used when setting the administrator password for the first\n time. If a password is already set, this endpoint will return 403.\n\n This needs to be a separate endpoint from change_password because it is\n listed in auth.py as not requiring authentication cookies.\n \"\"\"\n data = json.loads(sys.stdin.read())\n try:\n params = data[\"params\"]\n username = params[0]\n new_password = params[1]\n except KeyError, e:\n common.render_error(e.__str__())\n except IndexError, e:\n common.render_error(e.__str__())\n\n a = auth.Auth(auth_path)\n if a.password_exists():\n common.render_error('Administrator password has already been set.')\n else:\n if not a.save_password(new_password):\n common.render_error(\"Invalid password supplied.\")\n remote_address = os.environ.get('REMOTE_ADDR')\n tokens = a.authenticate(new_password, remote_address)\n uci.set('openwireless.setup_state', 'setup-private-net')\n uci.commit('openwireless')\n print \"Content-Type: application\/json\"\n print a.login_headers(tokens)\n print\n print \"{}\"","function_tokens":["def","jsonrpc_change_password_first_time","(","auth_path",")",":","data","=","json",".","loads","(","sys",".","stdin",".","read","(",")",")","try",":","params","=","data","[","\"params\"","]","username","=","params","[","0","]","new_password","=","params","[","1","]","except","KeyError",",","e",":","common",".","render_error","(","e",".","__str__","(",")",")","except","IndexError",",","e",":","common",".","render_error","(","e",".","__str__","(",")",")","a","=","auth",".","Auth","(","auth_path",")","if","a",".","password_exists","(",")",":","common",".","render_error","(","'Administrator password has already been set.'",")","else",":","if","not","a",".","save_password","(","new_password",")",":","common",".","render_error","(","\"Invalid password supplied.\"",")","remote_address","=","os",".","environ",".","get","(","'REMOTE_ADDR'",")","tokens","=","a",".","authenticate","(","new_password",",","remote_address",")","uci",".","set","(","'openwireless.setup_state'",",","'setup-private-net'",")","uci",".","commit","(","'openwireless'",")","print","\"Content-Type: application\/json\"","print","a",".","login_headers","(","tokens",")","print","print","\"{}\""],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/change_password_first_time.py#L10-L45"}
37
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"lib\/update\/update.py","language":"python","identifier":"Updater.valid_sig","parameters":"(self)","argument_list":"","return_statement":"return True","docstring":"Is self.purported_manifest correctly signed by a trusted key?","docstring_summary":"Is self.purported_manifest correctly signed by a trusted key?","docstring_tokens":["Is","self",".","purported_manifest","correctly","signed","by","a","trusted","key?"],"function":"def valid_sig(self):\n \"\"\"Is self.purported_manifest correctly signed by a trusted key?\"\"\"\n if not self.purported_manifest:\n return False\n in_fd, out_fd = os.pipe()\n command = [\"gpg\", \"--keyring\", keyring, \"--no-default-keyring\", \"--status-fd\", str(out_fd), \"--decrypt\"]\n p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n proc_stdout, proc_stderr = p.communicate(self.purported_manifest)\n if p.returncode != 0:\n return False\n print \"verification reported successful\"\n status = os.read(in_fd, 65536).split(\"\\n\")\n print \"status_fd output = \", status\n print \"proc_stdout = \", proc_stdout\n print \"all nonempty lines start with [GNUPG:]? \", all(bool(re.match(r\"^\\[GNUPG:\\]\", L) or not L) for L in status)\n if not all(bool(re.match(r\"^\\[GNUPG:\\]\", L) or not L) for L in status):\n return False\n if not any(re.match(r\"^\\[GNUPG:\\] GOODSIG \", L) for L in status):\n return False\n if not any(re.match(r\"^\\[GNUPG:\\] VALIDSIG \", L) for L in status):\n return False\n self.signed_manifest = proc_stdout\n return True","function_tokens":["def","valid_sig","(","self",")",":","if","not","self",".","purported_manifest",":","return","False","in_fd",",","out_fd","=","os",".","pipe","(",")","command","=","[","\"gpg\"",",","\"--keyring\"",",","keyring",",","\"--no-default-keyring\"",",","\"--status-fd\"",",","str","(","out_fd",")",",","\"--decrypt\"","]","p","=","subprocess",".","Popen","(","command",",","stdin","=","subprocess",".","PIPE",",","stdout","=","subprocess",".","PIPE",",","stderr","=","subprocess",".","PIPE",")","proc_stdout",",","proc_stderr","=","p",".","communicate","(","self",".","purported_manifest",")","if","p",".","returncode","!=","0",":","return","False","print","\"verification reported successful\"","status","=","os",".","read","(","in_fd",",","65536",")",".","split","(","\"\\n\"",")","print","\"status_fd output = \"",",","status","print","\"proc_stdout = \"",",","proc_stdout","print","\"all nonempty lines start with [GNUPG:]? \"",",","all","(","bool","(","re",".","match","(","r\"^\\[GNUPG:\\]\"",",","L",")","or","not","L",")","for","L","in","status",")","if","not","all","(","bool","(","re",".","match","(","r\"^\\[GNUPG:\\]\"",",","L",")","or","not","L",")","for","L","in","status",")",":","return","False","if","not","any","(","re",".","match","(","r\"^\\[GNUPG:\\] GOODSIG \"",",","L",")","for","L","in","status",")",":","return","False","if","not","any","(","re",".","match","(","r\"^\\[GNUPG:\\] VALIDSIG \"",",","L",")","for","L","in","status",")",":","return","False","self",".","signed_manifest","=","proc_stdout","return","True"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/lib\/update\/update.py#L51-L73"}
38
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"OWrt\/pbkdf2.py","language":"python","identifier":"crypt","parameters":"(word, salt=None, iterations=None)","argument_list":"","return_statement":"return salt + \"$\" + b64encode(rawhash, \".\/\")","docstring":"PBKDF2-based unix crypt(3) replacement.\n\n The number of iterations specified in the salt overrides the 'iterations'\n parameter.\n\n The effective hash length is 192 bits.","docstring_summary":"PBKDF2-based unix crypt(3) replacement.","docstring_tokens":["PBKDF2","-","based","unix","crypt","(","3",")","replacement","."],"function":"def crypt(word, salt=None, iterations=None):\n \"\"\"PBKDF2-based unix crypt(3) replacement.\n\n The number of iterations specified in the salt overrides the 'iterations'\n parameter.\n\n The effective hash length is 192 bits.\n \"\"\"\n\n # Generate a (pseudo-)random salt if the user hasn't provided one.\n if salt is None:\n salt = _makesalt()\n\n # salt must be a string or the us-ascii subset of unicode\n if isunicode(salt):\n salt = salt.encode('us-ascii').decode('us-ascii')\n elif isbytes(salt):\n salt = salt.decode('us-ascii')\n else:\n raise TypeError(\"salt must be a string\")\n\n # word must be a string or unicode (in the latter case, we convert to UTF-8)\n if isunicode(word):\n word = word.encode(\"UTF-8\")\n elif not isbytes(word):\n raise TypeError(\"word must be a string or unicode\")\n\n # Try to extract the real salt and iteration count from the salt\n if salt.startswith(\"$p5k2$\"):\n (iterations, salt, dummy) = salt.split(\"$\")[2:5]\n if iterations == \"\":\n iterations = 400\n else:\n converted = int(iterations, 16)\n if iterations != \"%x\" % converted: # lowercase hex, minimum digits\n raise ValueError(\"Invalid salt\")\n iterations = converted\n if not (iterations >= 1):\n raise ValueError(\"Invalid salt\")\n\n # Make sure the salt matches the allowed character set\n allowed = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.\/\"\n for ch in salt:\n if ch not in allowed:\n raise ValueError(\"Illegal character %r in salt\" % (ch,))\n\n if iterations is None or iterations == 400:\n iterations = 400\n salt = \"$p5k2$$\" + salt\n else:\n salt = \"$p5k2$%x$%s\" % (iterations, salt)\n rawhash = PBKDF2(word, salt, iterations).read(24)\n return salt + \"$\" + b64encode(rawhash, \".\/\")","function_tokens":["def","crypt","(","word",",","salt","=","None",",","iterations","=","None",")",":","# Generate a (pseudo-)random salt if the user hasn't provided one.","if","salt","is","None",":","salt","=","_makesalt","(",")","# salt must be a string or the us-ascii subset of unicode","if","isunicode","(","salt",")",":","salt","=","salt",".","encode","(","'us-ascii'",")",".","decode","(","'us-ascii'",")","elif","isbytes","(","salt",")",":","salt","=","salt",".","decode","(","'us-ascii'",")","else",":","raise","TypeError","(","\"salt must be a string\"",")","# word must be a string or unicode (in the latter case, we convert to UTF-8)","if","isunicode","(","word",")",":","word","=","word",".","encode","(","\"UTF-8\"",")","elif","not","isbytes","(","word",")",":","raise","TypeError","(","\"word must be a string or unicode\"",")","# Try to extract the real salt and iteration count from the salt","if","salt",".","startswith","(","\"$p5k2$\"",")",":","(","iterations",",","salt",",","dummy",")","=","salt",".","split","(","\"$\"",")","[","2",":","5","]","if","iterations","==","\"\"",":","iterations","=","400","else",":","converted","=","int","(","iterations",",","16",")","if","iterations","!=","\"%x\"","%","converted",":","# lowercase hex, minimum digits","raise","ValueError","(","\"Invalid salt\"",")","iterations","=","converted","if","not","(","iterations",">=","1",")",":","raise","ValueError","(","\"Invalid salt\"",")","# Make sure the salt matches the allowed character set","allowed","=","\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.\/\"","for","ch","in","salt",":","if","ch","not","in","allowed",":","raise","ValueError","(","\"Illegal character %r in salt\"","%","(","ch",",",")",")","if","iterations","is","None","or","iterations","==","400",":","iterations","=","400","salt","=","\"$p5k2$$\"","+","salt","else",":","salt","=","\"$p5k2$%x$%s\"","%","(","iterations",",","salt",")","rawhash","=","PBKDF2","(","word",",","salt",",","iterations",")",".","read","(","24",")","return","salt","+","\"$\"","+","b64encode","(","rawhash",",","\".\/\"",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/OWrt\/pbkdf2.py#L229-L281"}
39
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"OWrt\/pbkdf2.py","language":"python","identifier":"_makesalt","parameters":"()","argument_list":"","return_statement":"return b64encode(binarysalt, \".\/\")","docstring":"Return a 48-bit pseudorandom salt for crypt().\n\n This function is not suitable for generating cryptographic secrets.","docstring_summary":"Return a 48-bit pseudorandom salt for crypt().","docstring_tokens":["Return","a","48","-","bit","pseudorandom","salt","for","crypt","()","."],"function":"def _makesalt():\n \"\"\"Return a 48-bit pseudorandom salt for crypt().\n\n This function is not suitable for generating cryptographic secrets.\n \"\"\"\n binarysalt = b(\"\").join([pack(\"@H\", randint(0, 0xffff)) for i in range(3)])\n return b64encode(binarysalt, \".\/\")","function_tokens":["def","_makesalt","(",")",":","binarysalt","=","b","(","\"\"",")",".","join","(","[","pack","(","\"@H\"",",","randint","(","0",",","0xffff",")",")","for","i","in","range","(","3",")","]",")","return","b64encode","(","binarysalt",",","\".\/\"",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/OWrt\/pbkdf2.py#L288-L294"}
40
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"OWrt\/pbkdf2.py","language":"python","identifier":"PBKDF2._pseudorandom","parameters":"(self, key, msg)","argument_list":"","return_statement":"return self.__macmodule.new(key=key, msg=msg,\n digestmod=self.__digestmodule).digest()","docstring":"Pseudorandom function. e.g. HMAC-SHA1","docstring_summary":"Pseudorandom function. e.g. HMAC-SHA1","docstring_tokens":["Pseudorandom","function",".","e",".","g",".","HMAC","-","SHA1"],"function":"def _pseudorandom(self, key, msg):\n \"\"\"Pseudorandom function. e.g. HMAC-SHA1\"\"\"\n return self.__macmodule.new(key=key, msg=msg,\n digestmod=self.__digestmodule).digest()","function_tokens":["def","_pseudorandom","(","self",",","key",",","msg",")",":","return","self",".","__macmodule",".","new","(","key","=","key",",","msg","=","msg",",","digestmod","=","self",".","__digestmodule",")",".","digest","(",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/OWrt\/pbkdf2.py#L142-L145"}
41
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"OWrt\/pbkdf2.py","language":"python","identifier":"PBKDF2.read","parameters":"(self, bytes)","argument_list":"","return_statement":"return retval","docstring":"Read the specified number of key bytes.","docstring_summary":"Read the specified number of key bytes.","docstring_tokens":["Read","the","specified","number","of","key","bytes","."],"function":"def read(self, bytes):\n \"\"\"Read the specified number of key bytes.\"\"\"\n if self.closed:\n raise ValueError(\"file-like object is closed\")\n\n size = len(self.__buf)\n blocks = [self.__buf]\n i = self.__blockNum\n while size < bytes:\n i += 1\n if i > _0xffffffffL or i < 1:\n # We could return \"\" here, but\n raise OverflowError(\"derived key too long\")\n block = self.__f(i)\n blocks.append(block)\n size += len(block)\n buf = b(\"\").join(blocks)\n retval = buf[:bytes]\n self.__buf = buf[bytes:]\n self.__blockNum = i\n return retval","function_tokens":["def","read","(","self",",","bytes",")",":","if","self",".","closed",":","raise","ValueError","(","\"file-like object is closed\"",")","size","=","len","(","self",".","__buf",")","blocks","=","[","self",".","__buf","]","i","=","self",".","__blockNum","while","size","<","bytes",":","i","+=","1","if","i",">","_0xffffffffL","or","i","<","1",":","# We could return \"\" here, but","raise","OverflowError","(","\"derived key too long\"",")","block","=","self",".","__f","(","i",")","blocks",".","append","(","block",")","size","+=","len","(","block",")","buf","=","b","(","\"\"",")",".","join","(","blocks",")","retval","=","buf","[",":","bytes","]","self",".","__buf","=","buf","[","bytes",":","]","self",".","__blockNum","=","i","return","retval"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/OWrt\/pbkdf2.py#L147-L167"}
42
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"OWrt\/pbkdf2.py","language":"python","identifier":"PBKDF2.hexread","parameters":"(self, octets)","argument_list":"","return_statement":"return b2a_hex(self.read(octets))","docstring":"Read the specified number of octets. Return them as hexadecimal.\n\n Note that len(obj.hexread(n)) == 2*n.","docstring_summary":"Read the specified number of octets. Return them as hexadecimal.","docstring_tokens":["Read","the","specified","number","of","octets",".","Return","them","as","hexadecimal","."],"function":"def hexread(self, octets):\n \"\"\"Read the specified number of octets. Return them as hexadecimal.\n\n Note that len(obj.hexread(n)) == 2*n.\n \"\"\"\n return b2a_hex(self.read(octets))","function_tokens":["def","hexread","(","self",",","octets",")",":","return","b2a_hex","(","self",".","read","(","octets",")",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/OWrt\/pbkdf2.py#L179-L184"}
43
+ {"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"OWrt\/pbkdf2.py","language":"python","identifier":"PBKDF2.close","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Close the stream.","docstring_summary":"Close the stream.","docstring_tokens":["Close","the","stream","."],"function":"def close(self):\n \"\"\"Close the stream.\"\"\"\n if not self.closed:\n del self.__passphrase\n del self.__salt\n del self.__iterations\n del self.__prf\n del self.__blockNum\n del self.__buf\n self.closed = True","function_tokens":["def","close","(","self",")",":","if","not","self",".","closed",":","del","self",".","__passphrase","del","self",".","__salt","del","self",".","__iterations","del","self",".","__prf","del","self",".","__blockNum","del","self",".","__buf","self",".","closed","=","True"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/OWrt\/pbkdf2.py#L218-L227"}
EFForg__https-everywhere.jsonl ADDED
The diff for this file is too large to render. See raw diff
EinsteinsWorkshop__BlocksCAD.jsonl ADDED
The diff for this file is too large to render. See raw diff