query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
parse a variable decl
def variable_decl(): @generate def persistent_global_scope(): yield keyword("persistent") yield normalspaces() yield keyword("global") return s.Construct(s.PERSISTENTGLOBAL) @generate def global_scope(): yield keyword("global") return s.Construct(s.GLOBAL...
[ "def declvars(self, name: str):", "def _parse_variable(variable_ast: dict) -> \"VariableNode\":\n return VariableNode(\n name=_parse_name(variable_ast[\"name\"]),\n location=_parse_location(variable_ast[\"loc\"]),\n )", "def _parse_var(lexer: shlex.shlex) -> Tuple[str, Optional[Any]]:\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a while loop
def while_loop(): yield keyword("while") yield normalspaces() whileexpr = yield expression yield normalspaces() yield keyword("do") yield normalspaces() bodyexpr = yield expression return s.Construct(s.WHILE_LOOP, whileexpr, bodyexpr)
[ "def _while(self, node):\n write_code('label while') \n self._eval_token(node.children[0])\n write_code('if-goto while_end')\n map(lambda x: self._eval_token(x), node.children[1:])\n write_code('goto while')\n return", "def parse_while_statement(self):\n location...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a do loop
def do_loop(): yield keyword("do") yield normalspaces() bodyexpr = yield expression yield normalspaces() yield keyword("while") yield normalspaces() whileexpr = yield expression return s.Construct(s.DO_LOOP, bodyexpr, whileexpr)
[ "def test_do_while_stmt2(self):\r\n input = \"\"\"int main () {\r\n /* local variable definition */\r\n int a;\r\n a = 0;\r\n /* do loop execution */\r\n do {\r\n printf(\"value of a: \", a);\r\n a = a + 1;\r\n }while( a < 20 );\r\n return 0;\r\n}\r\n\"\"\"\r\n expec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a loop exit
def loop_exit(): @generate def with_expr(): yield normalspaces() yield keyword("with") yield normalspaces() value = yield operand return value yield keyword("exit") value = yield optional(with_expr) return s.Construct(s.LOOP_EXIT, value)
[ "def end_game_parse(line):\n tokens = line.split()\n while tokens:\n token = tokens.pop(0)\n \"*** YOUR CODE HERE ***\"\n return None", "def end_while_true(self):\n seen_close = 0\n while ((self.program[self.pc] != '[' or seen_close > 0) and \\\n self.pc >= 0):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a try expr
def try_expr(): yield keyword("try") yield normalspaces() tryexpr = yield expression yield normalspaces() yield keyword("catch") yield normalspaces() catchexpr = yield expression return s.Construct(s.TRY_EXPR, tryexpr, catchexpr)
[ "def testTryExceptElseFinally(self):\n token = self.parser.parse(filename='evo/TryExceptElseFinally.evo')\n trytoken = token.content[0]\n res = trytoken.siblings()\n self.assertEqual(len(res['exc']), 1)\n self.assertTrue(res['else'])\n self.assertTrue(res['finally'])", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a factor in a case
def case_factor(): @generate def unary_minus(): yield string("-") yield normalspaces() expr = yield expression return s.Construct(s.UNARY_MINUS, expr) @generate def unary_not(): yield keyword("not") yield normalspaces() expr = yield expression ...
[ "def parse_case_field(page):\n case_pattern = re.compile(\n r'''\n Case: # The name of the field we are looking for.\n .* # Any character.\n (\\d{2}-\\d{6,7}) # The case the number we are looking for.\n ''',\n re.VERBOSE,\n )\n return match_p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a case expr
def case_expr(): # pylint: disable=useless-return @generate def default(): yield keyword("default") return None @generate def case_item(): case = yield default ^ case_factor yield normalspaces() yield string(":") yield normalspaces() expr = yi...
[ "def visitCaseFunctionCall(self, ctx: MySqlParser.CaseFunctionCallContext) -> SQLToken:\n branches = []\n for func_alternative in ctx.caseFuncAlternative():\n branches.append(self.visit(func_alternative))\n if ctx.ELSE():\n branches.append((None, self.visit(ctx.functionArg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse the with context expr
def with_context(): # pylint: disable=line-too-long yield optional(keyword("with")) yield normalspaces() kw = yield keyword("(animate|undo|redraw|quiet|printAllElements|defaultAction|MXSCallstackCaptureEnabled|dontRepeatMessages|macroRecorderEmitterEnabled)") yield normalspaces() v = yield opera...
[ "def context_expr():\n contexts = yield sepBy1(\n about_context ^\n incoordsys_context ^\n innode_context ^\n at_context ^\n with_context, listsep())\n yield normalspaces()\n expr = yield expression\n return s.Construct(s.CONTEXT_EXPR, contexts, exp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse the at context expr
def at_context(): yield keyword("at") yield normalspaces() kw = yield keyword("level|time") yield normalspaces() v = yield operand return s.Construct(s.CONTEXT_AT, kw, v)
[ "def context_expr():\n contexts = yield sepBy1(\n about_context ^\n incoordsys_context ^\n innode_context ^\n at_context ^\n with_context, listsep())\n yield normalspaces()\n expr = yield expression\n return s.Construct(s.CONTEXT_EXPR, contexts, exp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse the in coordsys context expr
def incoordsys_context(): @generate def special_name(): name = yield keyword("world|local|parent|grid|screen") return s.Construct(s.NAME, name) yield optional(keyword("in")) yield normalspaces() yield keyword("coordsys") yield normalspaces() v = yield special_name | operand ...
[ "def context_expr():\n contexts = yield sepBy1(\n about_context ^\n incoordsys_context ^\n innode_context ^\n at_context ^\n with_context, listsep())\n yield normalspaces()\n expr = yield expression\n return s.Construct(s.CONTEXT_EXPR, contexts, exp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a context expr
def context_expr(): contexts = yield sepBy1( about_context ^ incoordsys_context ^ innode_context ^ at_context ^ with_context, listsep()) yield normalspaces() expr = yield expression return s.Construct(s.CONTEXT_EXPR, contexts, expr)
[ "def parse_expression(expr):\n child_expressions = []\n for child_expr in expr:\n if isinstance(child_expr, pyparsing.ParseResults):\n child_expressions.append(parse_expression(child_expr))\n else:\n child_expressions.append(child_expr)\n while len(child_expressions) > 2...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a set context
def set_context(): yield keyword("set") yield normalspaces() cxt = yield about_context ^ incoordsys_context ^ innode_context ^ at_context ^ with_context return s.Construct(s.SET_CONTEXT, cxt)
[ "def parse_set_list(self,tokiter,scopes):\n peek=tokiter.peek()\n while peek.token_type=='varname':\n yield peek.token_value\n lvaltoken=peek\n tokiter.next() # discard varname\n peek=tokiter.peek()\n while peek.token_type==end_of_line_type:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a global decl
def global_decl(): yield keyword("global") yield normalspaces() decls = yield sepBy1(decl, listsep()) return s.Construct(s.GLOBAL_DECL, decls)
[ "def get_decl():\n s=r'''\nvoid a(){\n float ret;\n int *aa;\n}\n'''\n parser = c_parser.CParser()\n a_ast = parser.parse(s)\n a_decl=a_ast.ext[0].body.block_items\n return a_decl", "def variable_decl():\n @generate\n def persistent_global_scope():\n yield keyword(\"persistent\")...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a rollout item
def rollout_item(): # pylint: disable=line-too-long kw = yield keyword("dotnetcontrol|hyperlink|subrollout|multilistbox|imgtag|curvecontrol|angle|label|button|edittext|combobox|dropdownList|listbox|spinner|slider|pickbutton|radiobuttons|checkbox|checkbutton|colorPicker|mapbutton|materialbutton|progressbar|timer...
[ "def parse_item(self):\n msg(\"parsing u.item\")\n lines = file('/'.join((self.datadir,\"u.item\"))).read().split(\"\\n\")\n infos = [line.replace('||','|').split('|') for line in lines if line]\n for info in infos:\n movie_id = int(info[0])\n if len(info[1].rstrip(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse an item group
def item_group(): yield keyword("group") yield normalspaces() qstring = yield quoted yield normalspaces() yield string("(") yield normalspaces() group = yield sepBy(rollout_item, normalspaces()) yield normalspaces() yield string(")") return s.Construct(s.ROLLOUT_GROUP, qstring, g...
[ "def Item(self) -> Group:", "def parse_item(self):\n msg(\"parsing u.item\")\n lines = file('/'.join((self.datadir,\"u.item\"))).read().split(\"\\n\")\n infos = [line.replace('||','|').split('|') for line in lines if line]\n for info in infos:\n movie_id = int(info[0])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a rollout handler
def rollout_handler(): yield keyword("on") yield normalspaces() handlername = yield var_name() yield normalspaces() varn = yield var_name() yield normalspaces() varn2 = yield optional(var_name()) yield normalspaces() varn3 = yield optional(var_name()) yield normalspaces() yie...
[ "def parse_event(self, event):", "def _parse(self):\n\t\t\n\t\tself.reply_msg = MessageHandler.fire_handlers(self)", "def handle_raw_endpoint_event(self, msg):\n classname = msg.data.keys()[0]\n attr = msg.data[classname]\n parsed_msg = msg.wf.ept_epm_parser.parse(classname, attr, attr[\"_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a rollout clause
def rollout_clause(): clause = yield (local_decl ^ global_decl ^ function_def ^ struct_def ^ mousetool_def ^ item_group ^ rollout_item ^ rollout_handler) # this is weird, why this clause? # (in the macroscript thing we use it as a bundle of things... ...
[ "def rollout_def():\n yield keyword(\"rollout\")\n yield normalspaces()\n vname = yield var_name()\n yield normalspaces()\n qstring = yield quoted\n yield normalspaces()\n vnop = yield sepBy(named_argument, normalspaces())\n yield normalspaces()\n yield string(\"(\")\n yield normalspac...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a rollout def
def rollout_def(): yield keyword("rollout") yield normalspaces() vname = yield var_name() yield normalspaces() qstring = yield quoted yield normalspaces() vnop = yield sepBy(named_argument, normalspaces()) yield normalspaces() yield string("(") yield normalspaces() clauses = ...
[ "def parse_move(s):", "def rollout_handler():\n yield keyword(\"on\")\n yield normalspaces()\n handlername = yield var_name()\n yield normalspaces()\n varn = yield var_name()\n yield normalspaces()\n varn2 = yield optional(var_name())\n yield normalspaces()\n varn3 = yield optional(var_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a rcmenu item
def rcmenu_item(): yield keyword("menuitem|separator|submenu") yield normalspaces() varname = yield var_name() yield normalspaces() label = yield quoted yield normalspaces() vnarg = yield sepBy(named_argument, singlelinespaces()) return s.Construct(s.RCMENU_ITEM, varname, label, vnarg)
[ "def rcmenu_def():\n yield keyword(\"rcmenu\")\n yield normalspaces()\n vname = yield var_name()\n yield normalspaces()\n yield string(\"(\")\n yield normalspaces()\n clauses = yield sepBy(rcmenu_clause, end_of_statement)\n yield normalspaces()\n yield string(\")\")\n return s.Construc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a rcmenu handler
def rcmenu_handler(): yield keyword("on") yield normalspaces() varname = yield var_name() yield normalspaces() vn2 = yield var_name() yield normalspaces() yield keyword("do") yield normalspaces() expr = yield expression return s.Construct(s.RCMENU_HANDLER, varname, vn2, expr)
[ "def rcmenu_def():\n yield keyword(\"rcmenu\")\n yield normalspaces()\n vname = yield var_name()\n yield normalspaces()\n yield string(\"(\")\n yield normalspaces()\n clauses = yield sepBy(rcmenu_clause, end_of_statement)\n yield normalspaces()\n yield string(\")\")\n return s.Construc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a rcmenu clause
def rcmenu_clause(): clause = yield ( rcmenu_handler ^ local_decl ^ function_def ^ struct_def ^ rcmenu_item) return clause
[ "def rcmenu_def():\n yield keyword(\"rcmenu\")\n yield normalspaces()\n vname = yield var_name()\n yield normalspaces()\n yield string(\"(\")\n yield normalspaces()\n clauses = yield sepBy(rcmenu_clause, end_of_statement)\n yield normalspaces()\n yield string(\")\")\n return s.Construc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse an rc menu def
def rcmenu_def(): yield keyword("rcmenu") yield normalspaces() vname = yield var_name() yield normalspaces() yield string("(") yield normalspaces() clauses = yield sepBy(rcmenu_clause, end_of_statement) yield normalspaces() yield string(")") return s.Construct(s.RCMENU_DEF, vname...
[ "def rcmenu_handler():\n yield keyword(\"on\")\n yield normalspaces()\n varname = yield var_name()\n yield normalspaces()\n vn2 = yield var_name()\n yield normalspaces()\n yield keyword(\"do\")\n yield normalspaces()\n expr = yield expression\n return s.Construct(s.RCMENU_HANDLER, varn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a on do handler
def on_do_handler(): @generate def do_exprseq(): yield keyword("do") yield normalspaces() handler = yield expression # expr_seq return handler yield keyword("on") yield normalspaces() event = yield var_name() yield normalspaces() handler = yield function_retu...
[ "def _parse(self):\n\t\t\n\t\tself.reply_msg = MessageHandler.fire_handlers(self)", "def on_map_do_handler():\n @generate\n def do_exprseq():\n yield keyword(\"do\")\n yield normalspaces()\n handler = yield expression # expr_seq\n return handler\n\n yield keyword(\"on\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a on map do handler
def on_map_do_handler(): @generate def do_exprseq(): yield keyword("do") yield normalspaces() handler = yield expression # expr_seq return handler yield keyword("on") yield normalspaces() yield keyword("map") yield normalspaces() event = yield var_name() ...
[ "def after_map(self, map):", "def before_map(self, map):", "def parse_event(self, event):", "def serve_map(self, foo):\n if(self.phase == 1):\n rospy.loginfo(\"Requesting the map for map converter\")\n rospy.wait_for_service('dynamic_map')\n try:\n map_se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a on clone do handler
def on_clone_do_handler(): @generate def do_exprseq(): yield keyword("do") yield normalspaces() handler = yield expression # expr_seq return handler yield keyword("on") yield normalspaces() yield keyword("clone") yield normalspaces() thing = yield var_name() ...
[ "def on_handler_clone(self,\n nfa_name: str,\n run_id: str,\n state_name: str,\n event: BoboEvent):", "def clone(self, data):", "def _clone(context, obj, clone_id):\n return context.manage_clone(obj, clone_id)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a macroscript clause
def macroscript_clause(): @generate def handler_block_item(): ret = yield on_do_handler ^ local_decl ^ function_def return ret yield lparen yield normalspaces() handlers = yield sepBy1(handler_block_item, normalspaces()) yield normalspaces() yield rparen return s.Construc...
[ "def macroscript_def():\n yield keyword(\"macroscript\")\n yield normalspaces()\n vname = yield var_name()\n yield normalspaces()\n vnop = yield sepBy(named_argument, normalspaces())\n yield normalspaces()\n handlers = yield expr_seq ^ macroscript_clause\n\n return s.Construct(s.MACROSCRIPT_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a macroscript def
def macroscript_def(): yield keyword("macroscript") yield normalspaces() vname = yield var_name() yield normalspaces() vnop = yield sepBy(named_argument, normalspaces()) yield normalspaces() handlers = yield expr_seq ^ macroscript_clause return s.Construct(s.MACROSCRIPT_DEF, vname, vnop...
[ "def macroscript_clause():\n @generate\n def handler_block_item():\n ret = yield on_do_handler ^ local_decl ^ function_def\n return ret\n yield lparen\n yield normalspaces()\n handlers = yield sepBy1(handler_block_item, normalspaces())\n yield normalspaces()\n yield rparen\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a tool clause
def tool_clause(): yield (local_decl ^ function_def ^ struct_def ^ tool_handler)
[ "def parse( self, root ):\n # Get the (user visible) name of the tool\n self.name = root.get( \"name\" )\n if not self.name: \n raise Exception, \"Missing tool 'name'\"\n # Get the UNIQUE id for the tool \n # TODO: can this be generated automatically?\n self.id =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a tool handler
def tool_handler(): yield keyword("on") yield normalspaces() yield var_name() yield normalspaces() yield optional(var_name()) yield normalspaces() yield keyword("do") yield normalspaces() expr = yield expression return expr
[ "def parse( self, root ):\n # Get the (user visible) name of the tool\n self.name = root.get( \"name\" )\n if not self.name: \n raise Exception, \"Missing tool 'name'\"\n # Get the UNIQUE id for the tool \n # TODO: can this be generated automatically?\n self.id =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a mousetool def
def mousetool_def(): yield keyword("tool") yield normalspaces() vname = yield var_name() yield normalspaces() vnop = yield sepBy(named_argument, normalspaces()) yield normalspaces() yield string("(") yield normalspaces() toolclauses = yield sepBy(tool_clause, normalspaces()) yiel...
[ "def get_cmd_parser(buf):\n buf = buf.strip('\\n')\n try:\n value = json.loads(buf)\n return value\n except ValueError:\n # Handles in the following.\n pass\n\n value = buf # Default value\n if is_valid_uuid(buf):\n # UUID type\n pass # Uses the default\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a param handler
def param_handler(): yield keyword("on") yield normalspaces() hname = yield var_name() yield normalspaces() action = yield keyword("set|get|preset|postset") yield normalspaces() other = yield var_name() yield normalspaces() yield keyword("do") yield normalspaces() expr = yiel...
[ "def _handleInput(self, paramInput):\n pass", "def parse_param_elem( self, input_elem, enctypes, context ):\n param = ToolParameter.build( self, input_elem )\n param_enctype = param.get_required_enctype()\n if param_enctype:\n enctypes.add( param_enctype )\n # If paramete...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a plugin clause
def plugin_clause(): clause = yield (local_decl ^ function_def ^ struct_def ^ parameters_def ^ mousetool_def ^ rollout_def ^ on_map_do_handler ^ on_clone_do_handler ^ on_do_handler) return clause
[ "def plugin_def():\n yield keyword(\"plugin\")\n yield normalspaces()\n vname = yield var_name()\n yield normalspaces()\n vname = yield var_name()\n yield normalspaces()\n vnop = yield sepBy(named_argument, normalspaces())\n yield normalspaces()\n yield string(\"(\")\n yield normalspac...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a plugin def
def plugin_def(): yield keyword("plugin") yield normalspaces() vname = yield var_name() yield normalspaces() vname = yield var_name() yield normalspaces() vnop = yield sepBy(named_argument, normalspaces()) yield normalspaces() yield string("(") yield normalspaces() pluginclau...
[ "def parse(name):\n\n pass", "def parseManagerText(self, text):\n\n # Regular expressions for scanning the file\n find_active = re.compile(r\"^\\s*?(\\w+)\\.py\", re.MULTILINE)\n find_inactive = re.compile(r\"^\\s*?#\\s*(\\w+)\\.py\", re.MULTILINE)\n find_manager = re.compile(r\"^\\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse a when handler
def when_handler(): @generate def when_attribute(): # pylint: disable=line-too-long yield keyword("when") yield normalspaces() kw = yield keyword("topology|geometry|names?|transform|select|parameters|subAnimStructure|controller|children|any") yield normalspaces() ...
[ "def parse_event(self, event):", "def _parse(self):\n\t\t\n\t\tself.reply_msg = MessageHandler.fire_handlers(self)", "def handle(self, handler: Handler):\n pass", "def sched_switch_parser(event, text):\n if text.count('=') == 2: # old format\n regex = re.compile(\n r'(?P<prev_comm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the setup string (pacman setup os setup script) for the copy command used by the mover
def getSetup(self): _setup_str = "" self._setup = self._setup.strip() tolog("self setup: %s" % self._setup) if self._setup and self._setup != "" and self._setup.strip() != "": if not self._setup.endswith(";"): self._setup += ";" if not "alias" in ...
[ "def _setup_body(setup_conf: SETUP_CONFIG) -> str:\n return os.linesep.join([\n 'import sys',\n 'from setuptools import setup',\n '',\n \"args = ' '.join(sys.argv).strip()\",\n 'if not any(args.endswith(suffix) for suffix in [{allowed_suffixes}]):',\n ' raise {error}'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return exit code (0 if OK), file size and checksum of a local file, as well as as date string if requested
def getLocalFileInfo(self, fileName, checksumType="default", date=None): # note that date is mutable statusRet = 0 outputRet = {} outputRet["errorLog"] = "" outputRet["report"] = {} outputRet["report"]["clientState"] = None outputRet["size"] = 0 outputRet...
[ "def process_file(filename):\n\n try:\n checksum_errors = verify_checksums(filename)\n if OPTIONS.compliance:\n compliance_errors = verify_compliance(filename)\n else:\n compliance_errors = 0\n if OPTIONS.write_file and checksum_errors == 0 or OPTIONS.force:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get checksum with xrdadler32 command
def getRemoteFileChecksum(self, full_surl, checksumType): remote_checksum = None output = None cmd = "%s xrdadler32 %s" % (self._setup, full_surl) tolog("Executing command: %s" % (cmd)) try: ec, output = commands.getstatusoutput(cmd) except Exception, e: ...
[ "def calculate_checksum(self):\n return binascii.crc32(self.unpack_binary(0, 0x78)) & 0xFFFFFFFF", "def bin_checksum(s):\n return bin_sha256(bin_sha256(s))[:4]", "def getRemoteFileChecksumFromOutput(self, output):\n remote_checksum = None\n # get remote checksum from the command output\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get checksum from xrdcp chksum command output
def getRemoteFileChecksumFromOutput(self, output): remote_checksum = None # get remote checksum from the command output if "xrootd" in output or "XRootD" in output: status = False # define the search patterns if "md5:" in output: checksum_pstr ...
[ "def get_checksum(input_file):\n _, _, stderr = run_cmd(['ffprobe', input_file])\n checksum = re.findall('checksum == (.*)', stderr)[0]\n return checksum", "def find_checksum(chksum): \n for record in capture_metadata2:\n if record[1]==chksum:\n return 1\n return 0", "def get_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the global file paths using to_native_lfn() [dsname needed] or Rucio naming convension [surl needed to extract the scope]
def getGlobalFilePaths(self, surl, dsname, computingSite, sourceSite, jobId=None): # this method will in fact only ever return a single path, but keep 'paths' as a list for consistency with getGlobalFilePathsDQ2() paths = [] # get the global redirectors (several, since the lib file might not b...
[ "def findGlobalFilePath(self, surl, dsname, computingSite, sourceSite, jobId=None):\n\n global_path = \"\"\n filename = os.path.basename(surl)\n\n # should dq2-list-files be used? If not, use to_native_lfn() directly to guess the path\n useDQ2 = False\n\n if useDQ2:\n #...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Correct the redirector in case the protocol and/or trailing slash are missing
def updateRedirector(self, redirector): if not redirector.startswith("root://"): redirector = "root://" + redirector tolog("Updated redirector for missing protocol: %s" % (redirector)) if not redirector.endswith("/"): redirector = redirector + "/" tolog("...
[ "def test_subdomain_redirect(self):\n self.init('/', 'japan.personfinder.appspot.com')\n legacy_redirect.redirect(self.handler)\n self.assertEquals(301, self.handler.response.status_int)\n self.assertEquals('http://google.org/personfinder/japan/',\n self.handler....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the global file paths using dq2listfiles
def getGlobalFilePathsDQ2(self, dsname): paths = [] if dsname == "": tolog("!!WARNING!!3333!! Dataset not defined") return paths filename = self.getGlobalPathsFileName(dsname) if os.path.exists(filename): try: f = open(filename, 'r')...
[ "def llist(self):\n\n filenames = os.listdir(self.SHARED_FOLDER)\n\n print('Local filepaths:')\n for filename in filenames:\n print(f'\\t{filename}')", "def define_files():\n paths = []\n files = os.listdir(PATH_TO_INPUT_DIR)\n for file in files:\n path = os.path.jo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify a global path (make sure the path begins with the root file protocol)
def verifyGlobalPath(self, path, verbose=True): # NOTE: per file check status = False protocol = 'root://' if path != "": if len(path) > len(protocol): if path[:len(protocol)] == protocol: # path verified status = True...
[ "def check_path():\n root = os.path.abspath(os.path.curdir)\n assert os.path.basename(root) == \"treelite\", \"Must be run on project root.\"", "def check_path(path, curr_dir):\n if not os.path.isabs(path):\n path = os.path.join(curr_dir, path)\n\n return path", "def is_root(path):\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify the global paths (make sure the output begins with the root file protocol)
def verifyGlobalPaths(self, output): # NOTE: this is not a per file check but an integration check to make sure the output is not garbish # individual files will be verified as they are needed return self.verifyGlobalPath(output, verbose=False)
[ "def testPaths():\n for path in config.main.paths:\n assert(os.path.exists(config.main.paths[path]))", "def check_path():\n root = os.path.abspath(os.path.curdir)\n assert os.path.basename(root) == \"treelite\", \"Must be run on project root.\"", "def __checkBase():\n if FIRED_BASE_FOLDER is ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the FAX redirectors via curl or JSON
def _getFAXRedirectors(self, computingSite, sourceSite, pandaID, url='http://waniotest.appspot.com/SiteToFaxEndpointTranslator'): fax_redirectors_dictionary = {} file_name = "fax_redirectors.json" if os.path.exists(file_name): # Read back the FAX redirectors from file ...
[ "def follow_redirect(self, response):\n new_response = response\n while new_response.status_code in (301, 302, 303, 307):\n scheme, netloc, path, query, fragment = urlparse.urlsplit(new_response['location'])\n new_response = self.client.get(path, QueryDict(query))\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the FAX redirectors primarily from the google server, fall back to schedconfig.faxredirector value
def getFAXRedirectors(self, computingSite, sourceSite, jobId): fax_redirectors_dictionary = {} # Is the sourceSite set? if sourceSite and sourceSite.lower() != 'null': # Get the FAX redirectors (if the method returns an empty dictionary, the keys and values will be set below) ...
[ "def _getFAXRedirectors(self, computingSite, sourceSite, pandaID, url='http://waniotest.appspot.com/SiteToFaxEndpointTranslator'):\n\n fax_redirectors_dictionary = {}\n file_name = \"fax_redirectors.json\" \n if os.path.exists(file_name):\n # Read back the FAX redirectors from fil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the global path for the given file
def findGlobalFilePath(self, surl, dsname, computingSite, sourceSite, jobId=None): global_path = "" filename = os.path.basename(surl) # should dq2-list-files be used? If not, use to_native_lfn() directly to guess the path useDQ2 = False if useDQ2: # get the global ...
[ "def _find_global_config_file():\n # Check test-imposed environment var P4GF_LOG_CONFIG_FILE.\n if p4gf_const.P4GF_TEST_LOG_CONFIG_PATH in os.environ:\n path = os.environ[p4gf_const.P4GF_TEST_LOG_CONFIG_PATH]\n if os.path.exists(path):\n return path\n\n # Check /etc/git-fusion.log....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parsing storage specific write concern Optional, use Monty WriteConcern by default. Recive MontyClient kwargs, should parse kwargs and return a instance of `montydb.base.WriteConcern` class.
def wconcern_parser(self, client_kwargs): pass
[ "def set_write_disposition(write_disposition):\n if write_disposition == 'WRITE_APPEND':\n return bigquery.WriteDisposition.WRITE_APPEND\n elif write_disposition == 'WRITE_EMPTY':\n return bigquery.WriteDisposition.WRITE_EMPTY\n elif write_disposition == 'WRITE_TRUNCATE':\n return bigq...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Trains a tokenizer from a dataframe and saves to disk. Uses minimal alphabet of ascii lowercase plus up to 30 characters.
def train_tokenizer_from_df( df, directory, filename, vocab_size, min_frequency, max_caption_length, special_tokens, use_bert_wordpiece=True, ): if use_bert_wordpiece: tokenizer = BertWordPieceTokenizer(lowercase=True) tokenizer.enable_padding(length=max_caption_lengt...
[ "def _tokenize_df(df, target=\"sentence\"):\n tqdm.pandas()\n assert type(target) is str, \"target must be a string\"\n assert target in df.columns, \"dataframe must have a {} column (user specified) to tokenize\".format(target)\n df[\"tokenized_text\"] = df[target].progress_apply(Review...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add the start and end tokens to the strings in columns 1 > end of a pandas dataframe. Returns a copy of the dataframe and a list of the special tokens.
def add_special_tokens(df, pad=PAD, start=BOS, end=EOS, unk=UNK): for col in df.iloc[:, 1:].columns: if not df.loc[0, col].startswith(start): df[col] = start + " " + df[col] + " " + end return df, [pad, start, end, unk]
[ "def avail(df):\r\n avail = DataFrame({\r\n 'start' : df.apply(lambda col: col.first_valid_index()),\r\n 'end' : df.apply(lambda col: col.last_valid_index())\r\n })\r\n return avail[['start', 'end']]", "def add_tokenized_column(self, df, column_name_to_tokenize):\n C...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a single captions or group of captions from a rank1 or rank2 tensor of ids using a tokenizer.
def ids_to_captions(ids_tensor, tokenizer, skip_special_tokens=False): if ids_tensor.dim() == 1: ids_tensor = ids_tensor.reshape(1, -1) ids_tensor = ids_tensor.cpu() strings = tokenizer.decode_batch(ids_tensor.tolist(), skip_special_tokens=False) if skip_special_tokens: strings = list(ma...
[ "def get_random_caption_tokens(idx):\n \n # Initialize an empty list for the results.\n result = []\n\n # For each of the indices.\n for i in idx:\n # The index i points to an image in the training-set.\n # Each image in the training-set has at least 5 captions\n # which have bee...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns possibly weighted average of 1, 2, 3, and 4gram corpus BLEU scores for a batch of predictions and ground truths. The tokenizer is used to strip special characters and padding and (if relevant) reconstruct words from subwords.
def corpus_bleu_score( preds: torch.Tensor, gt: torch.Tensor, tokenizer, weights=(0.25, 0.25, 0.25, 0.25) ): preds = [s.strip().split(" ") for s in ids_to_captions(preds, tokenizer, True)] gt = [ [s.strip().split(" ") for s in ids_to_captions(lst, tokenizer, True)] for lst in gt ] re...
[ "def get_bleu_score_mean(dataset,sentence_bleu,weights,smoothing_function):\n data_set_bleu_score = 0 #bleu score of all dataset\n\n for k,v in dataset.items():\n reference = [k.lower().split(\" \")]\n utterance_bleu_score = 0 # current utterance bleu_Score = average_paraphrase_bleu_score\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sample a minibatch and show the images and captions.
def sample_minibatch(minibatch, tokenizer, remove_special_tokens=True): inv_normalize = NormalizeInverse() sample_images = inv_normalize(minibatch["image"]) sample_captions = minibatch["captions"] for i in range(sample_images.shape[0]): plt.imshow(sample_images[i].permute(1, 2, 0).clip(0, 1).cpu...
[ "def display_samples(folders):\n if not do_plotting:\n return\n for folder in folders:\n print(folder)\n image_files = os.listdir(folder)\n image = random.choice(image_files)\n image_file = os.path.join(folder, image)\n i = Image(filename=image_file)\n display(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Similar to `check_value()`, but accepts many candidate shapes and checks each of them before raising an error.
def _check_value_any(a, *shapes, **kwargs): if len(shapes) == 0: raise ValueError("At least one shape is required") name = kwargs.get("name") for shape in shapes: try: return check_value(a, shape, name=name) except ValueError: pass if name is None: ...
[ "def is_valid_shape(value):\n if is_int_positive(value):\n return True, value\n elif isinstance(value, tuple) or isinstance(value, list):\n for v in value:\n if not is_int_positive(v):\n return False, value\n return True, value\n else:\n return False, v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start to listen for messages untill one comes or the timeout is reached. Use 'limit' for tests when you want to run the worker a given number of loops before it stop without having to tell him to. Limit should be an integer representing the number of loops. This is mainly used for testing purpose and is default to 1, w...
def main_loop(self, timeout=1, limit=-1): self.run = True self.on_main_loop() try: while self.run and limit != 0: try: self.connection.drain_events(timeout=timeout) except socket.timeout: # this happens when ...
[ "def start(self, timeout=1, limit=-1, force_purge=False):\n\n self.on_worker_starts()\n\n self.connect()\n\n self.logger.info('%s is starting' % self.name)\n\n if force_purge:\n self.purge()\n\n self.main_loop(timeout, limit)\n\n self.on_worker_stopped()\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connect the worker to th message broker, purge queues if required then starts the main loop to listen and react for messages. Provide callbacks to perform action before and after the main loop starts. Use 'limit' for tests when you want to run the worker a given number of loops before it stop without having to tell him...
def start(self, timeout=1, limit=-1, force_purge=False): self.on_worker_starts() self.connect() self.logger.info('%s is starting' % self.name) if force_purge: self.purge() self.main_loop(timeout, limit) self.on_worker_stopped() self.logger.info(...
[ "def main_loop(self, timeout=1, limit=-1):\n\n self.run = True\n\n self.on_main_loop()\n\n try:\n while self.run and limit != 0:\n try:\n self.connection.drain_events(timeout=timeout)\n except socket.timeout: \n # th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Override this if you want to perform an action when the worker start
def on_worker_starts(self): pass
[ "def start_worker(self):\n self._thread_worker = _start_thread(self._start)", "def on_start(self, event):\n pass", "def launch(self):\n Worker.time += 1", "def start_processing(self):\n pass", "def __call__(self, *args, **kwargs):\n self.start(*args, **kwargs)", "def on_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Override this if you want to perform an action when the worker has stoped
def on_worker_stopped(self): pass
[ "def at_stop(self):\r\n pass", "def callback_stopping(self, myrun):\n pass # pragma: no cover", "def _worker_emu_stop(self):\n self._worker_queue.put(UnicornWorkerUpdateStateMessage(TargetStates.STOPPED))\n self.uc.emu_stop()", "def request_stop(self):\n self._stop_requested = T...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Override this if you want to perform an action when the worker has connected to the messag broker
def on_worker_connected(self): pass
[ "def on_connected(self):\n log.debug('on_connected called.')", "def kasaya_connection_started(self, addr):\n LOG.debug(\"Connected to %s\", addr)\n self.SYNC.notify_worker_live(self.status)", "def on_message_handled(self, event):\n self.accept(event.delivery)\n print('job acce...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Override this to return the exchanges you are going to use for you worker. It should return a mapping of exchange names and exchanges object.
def get_exchanges(self): pass
[ "def list_exchanges(self):\n endpoint = self.build_url(\"/exchanges\")\n return self.request('get', endpoint)", "def bind_exchanges(self):\n\n for name, exchange in self.exchanges.items():\n self.exchanges[name] = exchange(self.channel)", "def createexchanges(self):\r\n ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loop on all exchanges in the self.exchanges dictionary and bind them to the current channel. Called in self.connect() right after the connection with the message broker has been established. Assume there is only one channel and one connection.
def bind_exchanges(self): for name, exchange in self.exchanges.items(): self.exchanges[name] = exchange(self.channel)
[ "async def ensure_exchanges(self, channel):\n\n # TODO: Perhaps instead make self.exchanges a property to better guard\n # against its use before ensure_exchanges has been called\n if self.exchanges is not None:\n return\n\n self.exchanges = {}\n\n for exchange_name in ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Override this to return the queues you are going to use for you worker. It should return a mapping of exchange names and exchanges object.
def get_queues(self): pass
[ "def get_spider_queues(config):\n queues = {}\n for project in get_project_list(config):\n table = 'scrapy_%s_queue' % project\n queues[project] = PgQueue(config, table=table)\n return queues", "def get_queues():\n queues = []\n for name, display_name in tasks.TASK_QUEUE_DISPLAY_NAMES.items():\n que...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loop on all queues in the self.queues dictionary and bind them to the current channel. Called in self.connect() right after the connection with the message broker has been established. Assume there is only one channel and one connection.
def bind_queues(self): for name, queue in self.queues.items(): self.queues[name] = queue(self.channel) self.queues[name].declare()
[ "def on_bindok(self, frame):\n logger.debug('Queue bound')\n self.start_consuming()", "def start_handling_messages(self):\n for amqp_consumer in self._amqp_consumers:\n amqp_consumer.start_handling_messages()", "def bind(self, queue, routing_key=None, arguments=None, nowait=False...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Override this to return the consumers you are going to use for you worker. It should return a mapping of exchange names and exchanges object. There are no 'bind_consumers' method as kombu forces you to instanciate producers already bounded
def get_consumers(self): pass
[ "def get_all_consumers(self):\n return self.consumers", "def get_queues(self):\n pass", "def get_producers(self):\n return {'psms': Producer(self.channel, exchange=self.exchanges['psms'])}", "def list_consumers(self):\n endpoint = self.build_url(\"/consumers\")\n return self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Override this to return the producers you are going to use for you worker. It should return a mapping of exchange names and exchanges object. There are no 'bind_producers' method as kombu forces you to instanciate producers already bounded
def get_producers(self): pass
[ "def get_producers(self):\n return {'psms': Producer(self.channel, exchange=self.exchanges['psms'])}", "def get_producers(self):\n # generators, ofc how could I forget!\n if not self._producers:\n return None\n\n for producer in self._producers:\n yield producer_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
One producer only for all messages, since we have only one exchange.
def get_producers(self): return {'psms': Producer(self.channel, exchange=self.exchanges['psms'])}
[ "def worker(self, producer):\r\n while self.redis.get_status('producer') == 'run':\r\n for table in self.producer_table:\r\n logger.info(f'start processing : {table}')\r\n producer.send(table)", "async def producer():\n MQStatus.mqp_connected = False\n while T...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a dictionary with all countries
def get_countries(self): if self.db_connected: data = {} countries = self.cur.execute("SELECT id, key, name FROM countries ORDER BY name") for country in countries.fetchall(): data[country[0]] = { "iso_id" : country[1], "name" : country[2] } r...
[ "def allCountries():", "def getCountriesInfos():\n countries = getCountries()\n return [(country['code'], country['name'], country['resource_uri'])\n for country in countries]", "def get_countries(self):\n return self._make_transferto_request(action=\"pricelist\", info_type=\"countries\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a dictionary with all info for one country
def get_country_information(self,country): if self.db_connected: data = {} infos = self.cur.execute("""SELECT format.key, format.value, format.id FROM format INNER JOIN countries ON countries.id=format.country_id WHERE countries.key = :isoid AND format.parent_id IS NULL UNION ...
[ "def get_countries(self):\n if self.db_connected:\n data = {}\n countries = self.cur.execute(\"SELECT id, key, name FROM countries ORDER BY name\")\n for country in countries.fetchall():\n data[country[0]] = {\n \"iso_id\" : country[1],\n \"name\" : country[2]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes the country entry from the country list
def delete_country_entry(self,country_keys): if self.db_connected: self.delete_country_data(country_keys) for country in country_keys: self.cur.execute("DELETE FROM countries WHERE key = :key", {"key":country})
[ "def remove_country():\n\n name=request.get_data().decode().split('=')[1]\n result = json.loads(dumps(db.getInstance().delete_country_by_name(name)))\n return result", "def delete(self, country_id):\n le_country = get_a_country(country_id)\n if not le_country:\n return {'success...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
From BO optimization extract X giving the best seen Y and best expt for X already visited
def get_bests_from_BO(bo): y_seen = np.min(bo.Y) x_seen = bo.X[np.argmin(bo.Y)] Y_pred = bo.model.predict(bo.X) y_exp = np.min(Y_pred[0]) x_exp = bo.X[np.argmin(Y_pred[0])] return (x_seen, y_seen), (x_exp, y_exp)
[ "def best_neighborhood_improvement (self, x):\n\n best = []\n best_avg = self.avg_f_neighborhood(x)\n for i in range(self.n):\n for j in range(i+1, self.n):\n if x[i] != x[j]:\n if self.num_evals >= self.max_evals:\n break\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Distribute the test kits to the counties for this agent
def distribute_test_kits(self): raise NotImplementedError("Subclass must implement abstract method")
[ "def create_installers_bunch(installer, train, test, coverages, xgrid, ygrid):\n\n \n bunch = Bunch(name=installer)\n\n points = dict(test=test, train=train)\n\n\n\n for label, pts in points.iteritems():\n\n\n # choose points associated with the desired species\n pts = pts[pts['installer'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plots sorted coefficient values of the model
def plotCoef(model,train_x): coefs = pd.DataFrame(model.coef_, train_x.columns) coefs.columns = ["coef"] coefs["abs"] = coefs.coef.apply(np.abs) coefs = coefs.sort_values(by="abs", ascending=False).drop(["abs"], axis=1) plt.figure(figsize=(15, 7)) coefs.coef.plot(kind='bar') plt.gr...
[ "def vis_coef(estimator, feature_names, topn = 10):\n fig = plt.figure()\n n_classes = estimator.coef_.shape[0]\n feature_names = np.asarray(feature_names)\n for idx, coefs in enumerate(estimator.coef_, 1):\n sorted_coefs = np.argsort(coefs)\n positive_coefs = sorted_coefs[-topn:]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if your prediction is in str type or not. If not, then raise error.
def _check_datatype_to_string(prediction): if isinstance(prediction, str): return True raise TypeError('Prediction is not in string type.')
[ "def input_type_check(data: object) -> None:\n if not isinstance(data, str):\n raise TypeError(\"Input data must be a 'str' object.\")", "def test_response_column_not_str_error(self):\n\n with pytest.raises(TypeError, match=\"response_column must be a str\"):\n\n NearestMeanResponseImp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
MainVision class's constructor. Initializes, notably, the various ROS callbacks and starts the puck detection
def __init__(self): rospy.init_node(ROS_VISION_NODE_NAME) rospy.on_shutdown(self.stopCurrentPuckDetector) self.puckDetector = None self.MODE = PuckDetectorBuilder.ROS self.m_reconfigureSubscriber = rospy.Subscriber(ROS_SUBSCRIBER_CONFIG_START_TOPIC_NAME, Bool, self.reconfigureCa...
[ "def __init__(self):\n self.bridge = CvBridge()\n rospy.init_node('occlusion_renderer')\n\n # Instantiate OcclusionRenderer object\n self.pkg_path = rospkg.RosPack().get_path('occlusion_render')\n sawyer_dae = '%s/models/sawyer.dae' % self.pkg_path\n self.renderer = Occlusi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called to stop the puck detection done by the current PuckDetector
def stopCurrentPuckDetector(self): if self.puckDetector != None: self.puckDetector.userWantsToQuit() self.puckDetector.stopIncommingCameraFeed() self.puckDetector = None
[ "def kill(self):\n\n self.running = False\n\n try:\n # teardown robot\n self.strategy.teardown()\n except Exception:\n # method not implemented by strategy\n pass", "def stopMotor(self) -> None:\n ...", "def stop(self):\n\n self.tank...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called to start a new PuckDetector
def startPuckDetector(self, i_reconfigure): builder = PuckDetectorBuilder(self.MODE, 30, i_reconfigure) self.stopCurrentPuckDetector() self.puckDetector = builder.build() self.puckDetector.findPuck()
[ "def __init__(self):\n rospy.init_node(ROS_VISION_NODE_NAME)\n rospy.on_shutdown(self.stopCurrentPuckDetector)\n\n self.puckDetector = None\n self.MODE = PuckDetectorBuilder.ROS\n self.m_reconfigureSubscriber = rospy.Subscriber(ROS_SUBSCRIBER_CONFIG_START_TOPIC_NAME, Bool, self.re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wrapper for callable to cache arguments and return values.
def wrapper(*args, **kwargs): key = wrapper.__cache_key__(*args, **kwargs) result = g.cache.get(key, ENOVAL) if result is ENOVAL: result = func(*args, **kwargs) g.cache[key] = result return result
[ "def memoize(func, cache, num_args):\n def wrapper(*args):\n mem_args = args[:num_args]\n if mem_args in cache:\n return cache[mem_args]\n result = func(*args)\n cache[mem_args] = result\n return result\n return wraps(func)(wrapper)", "def memoized(*args, **kwar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make key for cache given function arguments.
def __cache_key__(*args, **kwargs): return args_to_key(base, args, kwargs, False)
[ "def _build_cache_key(self, *args):\n return self.key if not self.key_mod else self.key % tuple(args)", "def cachekey(func, *args, **kwargs):\n args2 = arguments(func, *args, **kwargs)\n\n # ignoring `instance`\n instance_index = getattr(func, '_instance_index', False)\n if instance_index is no...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A method used for computing composition descriptors. AAProperty is a dict form containing classifciation of amino acids such as _Polarizability. AAPName is a string used for indicating a AAP name. result is a dict form containing composition descriptors based on the given property.
def CalculateComposition(ProteinSequence,AAProperty,AAPName): TProteinSequence=StringtoNum(ProteinSequence,AAProperty) Result={} Num=len(TProteinSequence) Result[AAPName+'C'+'1']=round(float(TProteinSequence.count('1'))/Num,3) Result[AAPName+'C'+'2']=round(float(TProteinSequence.count('2'))/Num,3) Result[AA...
[ "def convertAAToProperties(self, sequence, properties=None):\n properties = properties or ['composition', 'iep', 'polarity']\n result = []\n\n for aa in sequence:\n if aa in PROPERTY_DETAILS:\n aaProperties = sum(PROPERTY_DETAILS[aa][prop] for prop in\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A method used for computing transition descriptors AAProperty is a dict form containing classifciation of amino acids such as _Polarizability. AAPName is a string used for indicating a AAP name.
def CalculateTransition(ProteinSequence,AAProperty,AAPName): TProteinSequence=StringtoNum(ProteinSequence,AAProperty) Result={} Num=len(TProteinSequence) CTD=TProteinSequence Result[AAPName+'T'+'12']=round(float(CTD.count('12')+CTD.count('21'))/(Num-1),3) Result[AAPName+'T'+'13']=round(float(CTD.count('1...
[ "def CalculateComposition(ProteinSequence,AAProperty,AAPName):\r\n\tTProteinSequence=StringtoNum(ProteinSequence,AAProperty)\r\n\tResult={}\r\n\tNum=len(TProteinSequence)\r\n\tResult[AAPName+'C'+'1']=round(float(TProteinSequence.count('1'))/Num,3)\r\n\tResult[AAPName+'C'+'2']=round(float(TProteinSequence.count('2')...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A method used for calculating composition descriptors based on Hydrophobicity of AADs.
def CalculateCompositionHydrophobicity(ProteinSequence): result=CalculateComposition(ProteinSequence,_Hydrophobicity,'_Hydrophobicity') return result
[ "def compute_compositionality(self):\n #pdb.set_trace()\n compositionality = 0\n comparisons = 0\n meanings = self.meaning_space.meanings()\n for meaning1,meaning2 in itertools.combinations(meanings, 2):\n mdist = self.meaning_space.hamming(meaning1,meaning2)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A method used for calculating composition descriptors based on SecondaryStr of AADs.
def CalculateCompositionSecondaryStr(ProteinSequence): result=CalculateComposition(ProteinSequence,_SecondaryStr,'_SecondaryStr') return result
[ "def load_stereo_chemical_props() -> Tuple[Mapping[str, List[Bond]],\n Mapping[str, List[Bond]],\n Mapping[str, List[BondAngle]]]:\n # stereo_chemical_props_path = (\n # 'alphafold/common/stereo_chemical_props.txt')\n # with op...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A method used for calculating composition descriptors based on SolventAccessibility of AADs.
def CalculateCompositionSolventAccessibility(ProteinSequence): result=CalculateComposition(ProteinSequence,_SolventAccessibility,'_SolventAccessibility') return result
[ "def get_pymatgen_descriptor(composition, property_name):\n eldata = []\n # what are these named tuples for? not used or returned! -KM\n eldata_tup_lst = []\n eldata_tup = collections.namedtuple('eldata_tup', 'element propname propvalue propunit amt')\n\n oxidation_states = {}\n if isinstance(comp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A method used for calculating Transition descriptors based on Hydrophobicity ofAADs.
def CalculateTransitionHydrophobicity(ProteinSequence): result=CalculateTransition(ProteinSequence,_Hydrophobicity,'_Hydrophobicity') return result
[ "def _cal_hoag(self) -> AbstractHOAG:\n # 读入梯度信息\n with open(self.our_work, \"r\") as fp:\n lines = fp.readlines()\n # 计算loss的值\n loss = [float(line.strip().split()[0]) for line in lines]\n gradient = []\n for i in range(1, len(loss)):\n gradient.appen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A method used for calculating Transition descriptors based on Charge of AADs.
def CalculateTransitionCharge(ProteinSequence): result=CalculateTransition(ProteinSequence,_Charge,'_Charge') return result
[ "def pd_create(cd):\n\n # check that 'c' or 'd' is passed\n #assert cd == (\n # 'c' or 'd'), 'This must be charge (c) or discharge (d) data'\n\n # number of descriptors it generates\n n_desc = 19\n\n # determines prefix string based on need for a charge or\n # dis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A method used for calculating Transition descriptors based on SecondaryStr of AADs.
def CalculateTransitionSecondaryStr(ProteinSequence): result=CalculateTransition(ProteinSequence,_SecondaryStr,'_SecondaryStr') return result
[ "def _compute_durations_on_diff_addrs(self, stud_address, stud_alternate_1,\n stud_alternate_2, has_car):\n main_duration = self._fetch_travel_duration(stud_address,\n has_car)\n self.durations['main_duration' +...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A method used for calculating Transition descriptors based on SolventAccessibility of AADs.
def CalculateTransitionSolventAccessibility(ProteinSequence): result=CalculateTransition(ProteinSequence,_SolventAccessibility,'_SolventAccessibility') return result
[ "def describe(self, access, element):\n self._prepare(access)\n # Accumulate the descriptor sets from each ability, then turn into a string.\n tags = set()\n for c in self.abilities:\n tags |= c.describe(access, element)\n return ' '.join(list(tags)).lower()", "def ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A method used for calculating Distribution descriptors based on Hydrophobicity of AADs.
def CalculateDistributionHydrophobicity(ProteinSequence): result=CalculateDistribution(ProteinSequence,_Hydrophobicity,'_Hydrophobicity') return result
[ "def _HAC_model():\n\n\tclf = AgglomerativeClustering()\n\treturn clf", "def pd_create(cd):\n\n # check that 'c' or 'd' is passed\n #assert cd == (\n # 'c' or 'd'), 'This must be charge (c) or discharge (d) data'\n\n # number of descriptors it generates\n n_desc = 19\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A method used for calculating Distribution descriptors based on NormalizedVDWV of AADs.
def CalculateDistributionNormalizedVDWV(ProteinSequence): result=CalculateDistribution(ProteinSequence,_NormalizedVDWV,'_NormalizedVDWV') return result
[ "def _compute_det_variance(self):", "def detAcceptanceRateValues(self):\n if(not(self.weight)):\n for nodej in self.g.nodes():\n WeightedSum = len(self.g.in_edges(nodej))\n for edge in self.g.in_edges(nodej):\n self.A[edge[0] + \"-\"+edge[1]] = (1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A method used for calculating Distribution descriptors based on Charge of ADDs.
def CalculateDistributionCharge(ProteinSequence): result=CalculateDistribution(ProteinSequence,_Charge,'_Charge') return result
[ "def pd_create(cd):\n\n # check that 'c' or 'd' is passed\n #assert cd == (\n # 'c' or 'd'), 'This must be charge (c) or discharge (d) data'\n\n # number of descriptors it generates\n n_desc = 19\n\n # determines prefix string based on need for a charge or\n # dis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A method used for calculating Distribution descriptors based on SecondaryStr of AADs.
def CalculateDistributionSecondaryStr(ProteinSequence): result=CalculateDistribution(ProteinSequence,_SecondaryStr,'_SecondaryStr') return result
[ "def calculate_agreement_directness(annotations_1, annotations_2):\n directness_1 = []\n directness_2 = []\n # Search for pairs annotated by both\n for pair in annotations_1:\n if pair in annotations_2:\n # Only take those into account that were annotated as \"affixal\" by both annotat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A method used for calculating Distribution descriptors based on SolventAccessibility of AADs.
def CalculateDistributionSolventAccessibility(ProteinSequence): result=CalculateDistribution(ProteinSequence,_SolventAccessibility,'_SolventAccessibility') return result
[ "def usage_distribution_across_agencies(dframe=dframe): \n \n funding_colors = ['#6baed6','#3182bd','#08519c','#bdd7e7']\n placement_colors = ['#67001f','#b2182b','#d6604d','#f4a582',\n '#fddbc7','#f7f7f7','#d1e5f0','#92c5de',\n '#4393c3','#2166ac','#053061']\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find all of the tags this post is associated with
def tags(self): return [t['tag'] for t in database.execute( 'SELECT tag FROM tags WHERE post_id = ?', [self['id']])]
[ "def get_tags(self):\n return self.tags.order_by(article_tag_mapping.c.created_at.asc()).all()", "def tags(self) -> List:", "def get_all_tags():\n return Tag.query.all()", "def get_tags(self, language=None):\n\n # get tagged post\n entries = self\n if language:\n entr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decode the photos associated with this post (if any)
def photos(self): return json.loads(self['photos']) or []
[ "def photos(self):\n try:\n return self._photos\n except AttributeError:\n photo_uuids = [\n uuid\n for uuid, photo in self._db._dbphotos.items()\n if photo[\"momentID\"] == self._pk\n ]\n\n self._photos = self._d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new Lock instance named ``name`` using the Redis client supplied by ``redis``. ``timeout`` indicates a maximum life for the lock. By default, it will remain locked until release() is called. ``timeout`` can be specified as a float or integer, both representing the number of seconds to wait. ``sleep`` indicates...
def __init__(self, redis, name, timeout=None, sleep=0.1, blocking=True, blocking_timeout=None, thread_local=True): self.redis = redis self.name = name self.timeout = timeout self.sleep = sleep self.blocking = blocking self.blocking_timeout = blocking_time...
[ "async def acquire(self, blocking=None, blocking_timeout=None):\n sleep = self.sleep\n token = b(uuid.uuid1().hex)\n if blocking is None:\n blocking = self.blocking\n if blocking_timeout is None:\n blocking_timeout = self.blocking_timeout\n blocking_timeout =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds more time to an already acquired lock. ``additional_time`` can be specified as an integer or a float, both representing the number of seconds to add.
async def extend(self, additional_time): if self.local.token is None: raise LockError("Cannot extend an unlocked lock") if self.timeout is None: raise LockError("Cannot extend a lock with no timeout") return await self.do_extend(additional_time)
[ "def extend(self, additional_time=0.0):\n\t\tself._last_time += additional_time", "def add_time(self, amount):\n self._time += amount", "def add_integration_time(self, time):\n self.integration_time += time", "def add_time(self, user_info, time_to_add):\n user_info['time_collected'] = tim...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use Redis to hold a shared, distributed lock named ``name``. Returns True once the lock is acquired. If ``blocking`` is False, always return immediately. If the lock was acquired, return True, otherwise return False. ``blocking_timeout`` specifies the maximum number of seconds to wait trying to acquire the lock. It sho...
async def acquire(self, blocking=None, blocking_timeout=None): sleep = self.sleep token = b(uuid.uuid1().hex) if blocking is None: blocking = self.blocking if blocking_timeout is None: blocking_timeout = self.blocking_timeout blocking_timeout = blocking_ti...
[ "def Shared(self, blocking=False, timeout=None):\n self._flock(fcntl.LOCK_SH, blocking, timeout,\n \"Failed to lock %s in shared mode\" % self.filename)", "def Exclusive(self, blocking=False, timeout=None):\n self._flock(fcntl.LOCK_EX, blocking, timeout,\n \"Failed to lock %s i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set current time display.
def set_current_time(self, time: str) -> None: self._logger.debug("running") self._current_time_val.setText(time) self._logger.debug("done")
[ "def setTime(self):\n self.btnStart.setEnabled(True)\n self.btnReset.setEnabled(True)\n \n t = self.time.time()\n\n self.hours = t.hour()\n self.minutes = t.minute()\n self.seconds = t.second()\n \n self.tick = self.hours*3600 + self.minutes*60 + self.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set exp start time display.
def set_exp_start_time(self, time: str) -> None: self._logger.debug("running") self._start_time_val.setText(time) self._logger.debug("done")
[ "def start_time(self, start_time):\n self.__start = start_time", "def start_time(self, start_time: str):\n\n self._start_time = start_time", "def set_start_time(self):\n self.solve_start = time.time()", "def setTime(self):\n self.btnStart.setEnabled(True)\n self.btnReset.set...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set block number display.
def set_block_num(self, num: str) -> None: self._logger.debug("running") self._block_num_val.setText(num) self._logger.debug("done")
[ "def setBlockNumber(self, blockNo: int):\n self.__blockNumber = blockNo", "def setDisplayBlockOffset(self, offset):\n self.getHandle().setDisplayBlockOffset(offset)", "def setDisplayBlock(self, material):\n if material != None:\n block = CraftMagicNumbers.getBlock(material.getIte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set block start time display.
def set_block_start_time(self, time: str) -> None: self._logger.debug("running") self._block_start_time_val.setText(time) self._logger.debug("done")
[ "def start_time(self, start_time):\n self.__start = start_time", "def setStartTime(self, startTime):\n self.startTime = startTime", "def start_time(self, start_time: str):\n\n self._start_time = start_time", "def set_start( self, value ):\n\t\tend = self.get_end( )\n\t\tself.set_time( val...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }