File size: 80,406 Bytes
c7f4bd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{"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"}
{"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"}
{"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"}
{"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"}
{"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"}
{"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"}
{"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"}
{"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"}
{"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"}
{"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"}
{"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"}
{"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"}
{"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"}
{"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"}
{"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"}
{"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"}
{"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"}
{"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"}
{"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"}
{"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"}
{"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"}
{"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"}
{"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"}
{"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"}