query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Set suffixes if they begin with a +
def set_suffixes(args): return [arg[1:] for arg in args if arg[0] == '+']
[ "def add_suffixes(self, settingsfxs):\n for s, sfx in settingsfxs.items():\n if hasattr(self, s):\n self.__setattr__(s, getattr(self, s)[:-4] + sfx + getattr(self, s)[-4:])", "def _replace_suffix(self, word, suffix, replacement):\n ...", "def suffix_replace(original, old,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a bounding box in the form [x1,y1,x2,y2] and returns z in the form [x,y,s,r] where x,y is the centre of the box and s is the scale/area and r is the aspect ratio
def convert_bbox_to_z(bbox): w = bbox[2] - bbox[0] h = bbox[3] - bbox[1] x = bbox[0] + w / 2. y = bbox[1] + h / 2. s = w * h # scale is just area r = w / float(h) return np.array([x, y, s, r]).reshape((4, 1))
[ "def convert_bbox_to_z(bbox):\n w = bbox[2] - bbox[0]\n h = bbox[3] - bbox[1]\n x = bbox[0] + w/2.\n y = bbox[1] + h/2.\n s = w * h #scale is just area\n r = w / float(h)\n return np.array([x, y, s, r]).reshape((4, 1))", "def bound_box(points):\n min_x = np.amin(points[:, 0])\n min_y = np.amin(poi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator for exposing a method as an RPC call with the given signature.
def expose_rpc(permission, return_type, *arg_types): def decorator(func): if not hasattr(func, '_xmlrpc_signatures'): func._xmlrpc_signatures = [] func._xml_rpc_permission = permission func._xmlrpc_signatures.append((return_type,) + tuple(arg_types)) return func r...
[ "def rpcmethod(func):\n func.rpcmethod = True\n return func", "def rpcmethod(func):\n func.rpcmethod = True\n return func", "def xmlrpc_method(returns='string', args=None, name=None):\r\n # Args should be a list\r\n if args is None:\r\n args = []\r\n\r\n def _xmlrpc_func(func...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Serialize the result of the RPC call and send it back to the client.
def send_rpc_result(req, result):
[ "def _post_exec(self, result):\n result_dict = zeep.helpers.serialize_object(result, target_cls=dict)\n return result_dict", "def send_result(result, encode=None):\n # encode result if requested\n if encode == 'json':\n result = json.dumps(result)\n elif not encode is...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Provide the namespace in which a set of methods lives. This can be overridden if the 'name' element is provided by xmlrpc_methods().
def xmlrpc_namespace():
[ "def Namespace(self) -> str:", "def namespaceList(self):\n \n pass", "def Namespaces(self) -> CodeNamespaceCollection:", "def createNamespace(self):\r\n raise NotImplementedError('Endpoint can not be used directly.')", "def XmlNamespace(self) -> str:", "def all_namespaces(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method takes one parameter, the name of a method implemented by the RPC server. It returns a documentation string describing the use of that method. If no such string is available, an empty string is returned. The documentation string may contain HTML markup.
def methodHelp(self, req, method): p = self.get_method(method) return '\n'.join((p.signature, '', p.description))
[ "def __system_methodHelp(method_name, **kwargs):\n entry_point = kwargs.get(ENTRY_POINT_KEY)\n protocol = kwargs.get(PROTOCOL_KEY)\n\n method = registry.get_method(method_name, entry_point, protocol)\n if method is None:\n raise RPCInvalidParams('Unknown method {}. Unable to retrieve its document...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract all phrases from word alignment.
def extract_phrase(self, src_text, tgt_text, alignment, max_phrase_len=0): def extract_from_range(tgt_start, tgt_end, src_start, src_end, max_phrase_len): """Extract a set of possible phrase given the source, language ranges. """ # print("rages", tgt_start, tgt_end, src_star...
[ "def extract_phrases(data,model):\n phrases = []\n alignment = model.alignment_idx\n for i in range(len(data)):\n sent_phrases = phrase_extraction(data[i][\"fr\"],data[i][\"en\"],alignment[i])\n phrases.append(sent_phrases)\n return phrases", "def lemmatized_phrases(self):\n phras...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract a set of possible phrase given the source, language ranges.
def extract_from_range(tgt_start, tgt_end, src_start, src_end, max_phrase_len): # print("rages", tgt_start, tgt_end, src_start, src_end) if tgt_end < 0: return # If `src_align_idx` out of the `src_start` and `src_target`. for src_align_idx, tgt_align_idx ...
[ "def extract_phrase(self, src_text, tgt_text, alignment, max_phrase_len=0):\n def extract_from_range(tgt_start, tgt_end, src_start, src_end, max_phrase_len):\n \"\"\"Extract a set of possible phrase given the source, language ranges.\n\n \"\"\"\n # print(\"rages\", tgt_start,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract phrase from list of the parallel sentences.
def extract_phrase_from_parallel_sentences(self, src_lst, tgt_lst, word_alignment, max_phrase_len=0, save_phrase_table=None): ...
[ "def extract_phrases(data,model):\n phrases = []\n alignment = model.alignment_idx\n for i in range(len(data)):\n sent_phrases = phrase_extraction(data[i][\"fr\"],data[i][\"en\"],alignment[i])\n phrases.append(sent_phrases)\n return phrases", "def sentence_parse(list_of_posts): \n fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute log probability of sorucetarget phrase pairs. Note that we compute log p(f|e) due to the noise channel assumption.
def compute_log_probs(self, phrases, save_to_file=None): # Co-ocurrence for source and target phrase tgt_src_cnt = defaultdict(lambda: defaultdict(int)) # ocurrence for target (English) tgt_cnt = defaultdict(int) # Compute frequency and co-occurence for phrase_p...
[ "def log_prob(self):", "def log_prob(self, sents):\n log_prob = 0\n for sent in sents:\n log_prob += self.sent_log_prob(sent)\n return log_prob", "def log_prob(self, sents):\n prob = 0\n for sent in sents:\n prob += self.sent_log_prob(sent)\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Flatten nested list into a list of sorucetarget phrase pairs.
def flatten_phrase_collect(phrase_collect): flatten_phrse_collect = list() for phrase_lst in phrase_collect: pass return flatten_phrse_collect
[ "def flatten(nested_list):\r\n return list(chain.from_iterable(nested_list))", "def _flatten(phrases):\n return [' '.join(phrase) for phrase in phrases]", "def flatten(nested_list):\n t_l = []\n for i in nested_list:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Summary Split data into nq blocks.
def split_data(data, nq, flag=1): if flag == 1: quantiles = np.linspace(data.min(), data.max(), nq + 1) elif flag == 2: segs = np.linspace(0, 100, nq + 1) quantiles = np.percentile(data, segs) quantiles[0] = quantiles[0] - 1e-15 quantiles[-1] = quantiles[-1] + 1e-15 grp_names...
[ "def test_chunk_size_priority_over_n_splits(self):\n with self.subTest(input='list', chunk_size=1, n_splits=6):\n self.assertEqual(get_n_chunks(self.test_data, iterable_len=None, chunk_size=1, n_splits=6, n_jobs=None), 13)\n with self.subTest(input='numpy', chunk_size=1, n_splits=6):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
online maxminscale normalization using key basic statistics.
def update_maxminscale(stats_on_target, lastest_minmax): target_xss, target_xs, target_xct = stats_on_target xmn, xmx = lastest_minmax zss = (target_xss - 2 * xmn * target_xs + target_xct * xmn**2) / (xmx - xmn)**2 zs = (target_xs - target_xct * xmn) / (xmx - xmn) zct = target_xct return zss, ...
[ "def min_max_normalization_univariate(data) :\r\n\r\n scaled_data = [] #The data obtained afte scaling the given data\r\n\r\n min_val = min(data) #The min value of the feature \r\n max_val = max(data) #The max value of the feature\r\n\r\n #Calculating the scaled features\r\n for a in range(0, len(dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct the flow graph by connecting this node to another node or a command. The predicate is a function that tells the flow executor if the flow can enter the step without the user intervention (automatically).
def connect(self, node_or_command: Union['FlowNode', str], predicate: Predicate = lambda _: False, hints: bool = True): node_to_connect_to = node_or_command if isinstance(node_or_command, FlowNode) else FlowNode(node_or_command, ...
[ "def add_true_edge(source, sink):\n assert isinstance(source, Branch)\n source.add_outgoing_edge(sink, \"T\")\n source.true_edge = sink\n sink.add_incoming_edge(source, \"T\")", "def build_connection(self, src, tgt) -> NoReturn:\n # If src and tgt are the same node, src not in node_collection o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets the predicate function for the specified child node.
def predicate_for_node(self, node: 'FlowNode'): for predicate, possible_node in self.children: if node == possible_node: return predicate return None
[ "def _get_predicate_function(cls):\n return lambda *args: False # This predicate will always fail and shouldn't be used.", "def get_predicate(self):\n return self._predicate", "def predicate(self):\n return self._predicate", "def predicate(f):\n wrapper = Predicate(f)\n update_wrap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all the possible next steps after this one (predicates statisfied or not).
def next_steps(self) -> List[FlowNode]: return [node for predicate, node in self._current_step.children]
[ "def _get_all_steps(self):\n steps = [\n self.provide_facets(),\n self.provide_garment_filters(),\n self.provide_query_filters(),\n self.provide_weights()\n ]\n return list(chain.from_iterable(steps))", "def next_step(self):\n self.proceed()\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The original flowroot of this flow.
def root(self) -> FlowRoot: return self._root
[ "def original(self):\n return self._original", "def clone_as_root(self) :\n clone = deepcopy(self)\n clone.parent = None\n clone.path_length = 0\n clone.previous_action = None\n return clone", "def original_variable(self):\n return self._original_variable", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register a flow with this executor.
def add_flow(self, flow: FlowRoot): with self._lock: self.flow_roots[flow.name] = flow
[ "def register_flow(self, state, flow_id):\n self._flows[state] = flow_id\n _LOGGER.debug(\"Register state %s for flow_id %s\", state, flow_id)", "def flow(self, flow):\n\n self._flow = flow", "def add_flow_controller(cls, name, controller):\n cls.registered_controllers[name] = contro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Trigger workflows that may have command cmd as a auto_trigger or an in flight flow waiting for command. This assume cmd has been correctly executed.
def trigger(self, cmd: str, requestor: Identifier, extra_context=None) -> Optional[Flow]: flow, next_step = self.check_inflight_flow_triggered(cmd, requestor) if not flow: flow, next_step = self._check_if_new_flow_is_triggered(cmd, requestor) if not flow: return None ...
[ "def _check_if_new_flow_is_triggered(self, cmd: str, user: Identifier) -> Tuple[Optional[Flow], Optional[FlowNode]]:\n log.debug(\"Test if the command %s is an auto-trigger for any flow ...\", cmd)\n with self._lock:\n for name, flow_root in self.flow_roots.items():\n if cmd ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if user is already running a flow.
def check_inflight_already_running(self, user: Identifier) -> bool: with self._lock: for flow in self.in_flight: if flow.requestor == user: return True return False
[ "def _check_if_new_flow_is_triggered(self, cmd: str, user: Identifier) -> Tuple[Optional[Flow], Optional[FlowNode]]:\n log.debug(\"Test if the command %s is an auto-trigger for any flow ...\", cmd)\n with self._lock:\n for name, flow_root in self.flow_roots.items():\n if cmd ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Trigger workflows that may have command cmd as a auto_trigger.. This assume cmd has been correctly executed.
def _check_if_new_flow_is_triggered(self, cmd: str, user: Identifier) -> Tuple[Optional[Flow], Optional[FlowNode]]: log.debug("Test if the command %s is an auto-trigger for any flow ...", cmd) with self._lock: for name, flow_root in self.flow_roots.items(): if cmd in flow_roo...
[ "def trigger(self):\n for _, t in self.triggers.items():\n # This cause an error. But I'll deal with that later.\n t.trigger(None)", "def checkTriggers():\n # TODO this\n pass", "def trigger(self, cmd: str, requestor: Identifier, extra_context=None) -> Optional[Flow]:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stops a specific flow. It is a no op if the flow doesn't exist. Returns the stopped flow if found.
def stop_flow(self, name: str, requestor: Identifier) -> Optional[Flow]: with self._lock: for flow in self.in_flight: if flow.name == name and flow.check_identifier(requestor): log.debug(f'Removing flow {str(flow)}.') self.in_flight.remove(flow...
[ "def stopTraffic(self):\n self.ixnObj.logInfo('\\nstopTraffic: %s' % self.ixnObj.sessionUrl+'/traffic/operations/stop')\n self.ixnObj.post(self.ixnObj.sessionUrl+'/traffic/operations/stop', data={'arg1': self.ixnObj.sessionUrl+'/traffic'})\n self.checkTrafficState(expectedState=['stopped', 'sto...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert byte data for a Point to a GeoJSON `dict`.
def __load_point(big_endian, type_bytes, data_bytes): endian_token = '>' if big_endian else '<' if type_bytes == WKB_2D['Point']: coords = struct.unpack('%sdd' % endian_token, data_bytes) elif type_bytes == WKB_Z['Point']: coords = struct.unpack('%sddd' % endian_token, data_bytes) elif ...
[ "def geojson(self, file_handle):\n return self.bytes(file_handle, \"application/vnd.geo+json\")", "def parse_point(line):\n return json.loads(line)", "def preprocess_point(point):\n # TODO: Replace IDs with actual information available at the\n # reference schema\n \n return {\n 'uu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cluster prey sequences according to mapped RefSeq
def refseq_based_clustering(self): self.refseq_based = NonRedSetDict() for prey in self.ivv_info.Prey_info().preys(): refseqid = self.get_refseq(prey) if refseqid: self.refseq_based.append_Dict(refseqid, prey)
[ "def refseq_based_clustering(self):\n self.refseq_based = NonRedSetDict()\n for prey in self.ivv_to_refseq.keys():\n refseqid = self.get_refseq(prey)\n if refseqid:\n self.refseq_based.append_Dict(refseqid, prey)\n\n self.refseq_based_map = {}\n for r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all RefSeqs. refseq_based_clustering() must be precalled.
def get_all_refseq(self): return self.refseq_based.keys()
[ "def references(self) -> \"IterableList[Reference]\":\n return Reference.list_items(self)", "def references(self):\r\n return Reference.list_items(self)", "def getReferencesFrom(self) -> List[ghidra.program.model.symbol.Reference]:\n ...", "def get_ref_array(self):\n s = [] # refe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This creates the symbols out of a stylegallery
def create_symbols(self, style_gallery, style_gallery_name, class_to_export): try: symbols_element = self.xml_document.getElementsByTagName("symbols")[0] except IndexError: symbols_element = self.xml_document.createElement("symbols") root_element = self.xml_document.getE...
[ "def draw_symbols():\n svgs = {\n \"coin\": draw_single_symbol(\"coin\"),\n \"red_cross\": draw_single_symbol(\"red_cross\"),\n \"radioactive\": draw_single_symbol(\"radioactive\"),\n \"food\": draw_single_symbol(\"food\"),\n \"water\": draw_single_symbol(\"water\"),\n \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if given args are new
def __is_args_new(self, *args, **kwargs): # if input size is different if len(args) != len(self.__cached_args) or len(kwargs) != len(self.__cached_kwargs): return True # check args and kwargs for a, ca in zip(args, self.__cached_args): if a != (ca() if isinstance(...
[ "def is_arg_changed(self):\n # type: () -> bool\n current_args = [arg['name'] for arg in self.current_file.get('args', [])]\n old_args = [arg['name'] for arg in self.old_file.get('args', [])]\n\n if not self._is_sub_set(current_args, old_args):\n print_error(Errors.breaking_ba...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the two base images needed to create a lighthouse animation. base_img is either A full/relative path from the run context The name of a directory under lighthouses here
def load_base_images(base_img): if base_img is not None: if not os.path.exists(base_img): base_img = os.path.join(LIGHTHOUSES_DIR, base_img) return ( Image.open(os.path.join(base_img, 'on.gif')).convert('RGBA'), Image.open(os.path.join(base_img, 'off.gif')) ...
[ "def get_random_base():\n\n n_base = count_raw_img('base')\n img = \"{}.jpg\".format(random.randint(1, n_base + 1))\n return Image.open(RAW_DIR_PATH['base'] + img)", "def get_base_filename_for_images():\n base_filename = str(datetime.datetime.now()).split('.')[0]\n base_filename = base_filename.rep...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a light characteristic, return a list of 2tuples representing the state of light at any given time. A fixed light is the given colour, permanently >>> characteristic_to_light_states('F. R') [('R', 1)]
def characteristic_to_light_states(description): fragments = description.split() pattern_type, groups = parse_pattern(fragments.pop(0)) colour, fragments = get_colour_code(fragments) try: period = parse_period(fragments) except IndexError: if must_have_period(pattern_type, groups): ...
[ "def get_states(crime):\n statelist = []\n for i in range(len(crime)-1):\n statelist.append(crime[i][0])\n return statelist", "def lights(self):\n data = self.make_request('lights')\n\n found_lights = []\n for device_id, light_data in data.items():\n light_type = LI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the split up characteristic, return the period in milliseconds The period is specified in seconds >>> parse_period(['2']) 2000 The letter 's' to mark the units may be present >>> parse_period(['3s']) 3000 It may be separated from the number by a space >>> parse_period(['4','s']) 4000 A Quick flash can only have a...
def parse_period(fragments): period_spec = fragments[-1] # The last term is the cycle period, # it may or may not have 's' for seconds # The 's' may or may not be attached to the number if period_spec == 's': period_spec = fragments[-2] if period_spec[-1] == 's': period_spec = pe...
[ "def parse_period(period):\n parts = PIPELINE_FREQUENCY_RE.match(period)\n if not parts:\n raise ValueError(\"'{0}' cannot be parsed as a period\".format(period))\n parts = parts.groupdict()\n kwargs = {parts['unit']: int(parts['number'])}\n return timedelta(**kwargs)", "def parseperiod(text...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Crack a pattern definition into its type and any grouping. A pattern consists of the pattern type (e.g. flashing, occulting) and optionally a group designation in parentheses. The pattern definition could just be the type >>> parse_pattern('Fl') ('fl', [1]) It could have optional dots marking the abbreviation, these ca...
def parse_pattern(pattern): pattern_type, _, group_spec = pattern.partition('(') # Groups are separated by '+' in a composite pattern. groups = [ int(group) for group in group_spec[:-1].split('+') ] if group_spec else [1] # Some light lists use dots, some don't, just throw them away ret...
[ "def _parsePattern(self, pattern):\n pattern.name = self._tokenizer.token()[6:]\n pattern.line = self._tokenizer.line()\n pattern.reporter = self._reporter\n self._tokenizer.nextToken()\n\n # Parse the parameter list\n if not self._expect('('):\n return\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a list of light states, collapse any adjacent entries that have the same state. If there are no adjacent matching states, there is no change to the output >>> collapse_states([('R',1), ('Y', 1), ('R', 1)]) [('R', 1), ('Y', 1), ('R', 1)] Adjacent states are collapsed, summing their durations >>> collapse_states([(...
def collapse_states(states): new_states = states[:1] for state in states[1:]: last_state = new_states[-1] if state[0] == last_state[0]: new_states[-1] = (state[0], last_state[1] + state[1]) else: new_states.append(state) return new_states
[ "def removeStatesWithoutOutgoingTransitions(self):\n assert len(self.rejecting)==len(self.transitions)\n assert len(self.rejecting)==len(self.stateNames)\n emptyStates = [len(self.transitions[i])==0 for i in range(0,len(self.transitions))]\n stateMapper = {}\n self.labelToStateAnd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Fixed pattern is simply an alwayson light in the given colour. groups and period are irrelevant.
def fixed(_groups, colour, _period): return [(colour, 1)]
[ "def flash(groups, colour, period):\n\n if groups == [1]:\n if period <= 2000:\n raise ValueError(\n \"The cycle period for a flash must be longer than 2 seconds\"\n )\n\n return [\n (colour, 1000),\n ('Off', period-1000)\n ]\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A flash is a single colour displayed for a short period, followed by a longer period of darkness A single flash of a given colour is a 1 second flash >>> flash([1], 'R', 5000) [('R', 1000), ('Off', 4000)] Grouped flashes have a shorter duration >>> flash([3], 'R', 10000) [('R', 500), ('Off', 1000), ('R', 500), ('Off', ...
def flash(groups, colour, period): if groups == [1]: if period <= 2000: raise ValueError( "The cycle period for a flash must be longer than 2 seconds" ) return [ (colour, 1000), ('Off', period-1000) ] return light_sequenc...
[ "def quick(groups, colour, period):\n # The cycle period cannot be longer than 1.2s (60/50)\n # or shorter than 0.5s\n if groups == [1]:\n if period is not None:\n raise ValueError(\n \"Quick Flash cycle periods must be longer than 0.5 seconds\"\n )\n\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
isophase is a pattern with equal dark and light. There are no groups.
def isophase(_groups, colour, period): # Whole numbers are required, so odd numbers are dealt with by loading # the spare into the off period. # As this is in milliseconds, this will be imperceptible. # It is also unlikely, as the top-level input is in seconds # and has been multiplied up to millise...
[ "def is_monochromatic(self):\n return equal(s.color for s in self.iter_states())", "def IsByColor(self) -> bool:", "def find_dark_states(excited_state, ground_states):", "def is_dark(self):\n\n return self.red() < 125 and self.green() < 125 and self.blue() < 125", "def _present_pattern(self, p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A Quick flash is more than 50 per minute.
def quick(groups, colour, period): # The cycle period cannot be longer than 1.2s (60/50) # or shorter than 0.5s if groups == [1]: if period is not None: raise ValueError( "Quick Flash cycle periods must be longer than 0.5 seconds" ) return [ ...
[ "def start_flash_timer(self):\r\n self.flashMillisecs = 1000\r\n self.flashTimer.start(50)", "def update_flash_time(self, delta):\n self.flash_time += delta", "def flash_power_on(self):\n time_end = time.time() + 1.5\n while time.time() < time_end:\n for i in range(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write out binary VTK file with a single vector field. Can specify time index or output time.
def writeVTK(self,fname,itime=None,output_time=None): if output_time: itime = int(output_time / self.dt) if not itime: print 'Need to specify itime or output_time' return print 'Writing out time step',itime,': t=',self.t[itime] u = np.zeros((self.NY,1,...
[ "def saveVelocityAndPressureVTK_binary(pressure,u,v,w,x,y,z,filename,dims):\n numEl_size = u.size; numEl = np.prod(numEl_size);\n # open the file and write the ASCII header:\n file = open(filename,'w')\n file.write('# vtk DataFile Version 3.0\\n')\n file.write('VTK file for data post-processed with P...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call writeVTK for a range of times
def writeVTKSeries(self,prefix=None,step=1): if not prefix: prefix = self.prefix for i in range(0,self.N,step): fname = prefix + '_' + str(i) + '.vtk' self.writeVTK(fname,itime=i)
[ "def writeVTK(self,fname,itime=None,output_time=None):\n if output_time:\n itime = int(output_time / self.dt)\n if not itime:\n print 'Need to specify itime or output_time'\n return\n print 'Writing out time step',itime,': t=',self.t[itime]\n u = np.zeros...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a minimal configuration for the user.
def create_default_user_config(server, port, user, api_key, whitelist_tags=[], ignore_proxy=True, verify_ssl=False): config = {} config_path = DEFAULT_CONFIG_PATH config['default'] = {'server': server, 'port': port, 'user': user, 'ap...
[ "def create_config(self) -> None:\n pass", "def create_empty_config_file():\n config = {\n \"config\": [\n {\n \"site\": {\n \"username\": \"\",\n \"name\": \"\",\n \"ip_address\": \"\",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
rebuilds elements of flat_li to match list structure of original_li (or tuple if given as args)
def deflatten(flat_li, *original_li): if len(original_li) == 1: original_li = original_li[0] deflatten_li = [] i = 0 for el in original_li: if isinstance(el, Sequence): deflatten_li.append(flat_li[i:i+len(el)]) i += len(el) else: deflatten_li.a...
[ "def _Restructure(l, structure):\n result = []\n current_index = 0\n for element in structure:\n if element is None:\n result.append(l[current_index])\n current_index += 1\n else:\n result.append(l[current_index:current_index+element])\n current_index += element\n\n if len(result) == 1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find all indices from list ``l`` where entries match specific object ``o``
def findall(l, o): return [i for i, u in enumerate(l) if u==o]
[ "def locate_all_occurrence(l, e):\n return [i for i, x in enumerate(l) if x == e]", "def linear_search(v, l):\n i = 0\n for value in l:\n if value == v:\n return i\n i += 1\n return len(l)", "def linsearch(l, x):\n\n for i in range(len(l)):\n if x == l[i]:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get all entries of list ``l`` at positions ``idx``
def getall(l, idx): return [l[i] for i in idx]
[ "def getValues(l, index):\n return [l[i] for i in index]", "def listElems(list0, idx):\n\n list = [list0[id] for id in idx]\n return list", "def get_list(self, index):\n if isinstance(index, slice):\n # XXX needs support for slices\n raise NotImplementedError\n index...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Model function for CIFAR10.
def cifar10_model_fn(features, labels, mode, params): features = tf.reshape(features, [-1, _IMAGE_SIZE, _IMAGE_SIZE, _NUM_CHANNELS]) learning_rate_fn = resnet_run_loop.learning_rate_with_decay( batch_size=params['batch_size'], batch_denom=128, num_images=_NUM_IMAGES['train'], boundary_epochs=[10, 20, 3...
[ "def load_cifar10():\n \n # import cifar10 data, split into train and test\n (train_images, train_labels), (test_images, test_labels) = cifar10.load_data()\n # normalise\n train_images, test_images = train_images / 255.0, test_images / 255.0\n # print general info\n print()\n print(\"Suc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is the main prediction adding function. It starts by grabbing a file to open from standard in, which contains one message board page. It processes each message contained in the page.
def main(): # db_user = raw_input('DB username: ') db_user = 'oraclech' pw = getpass.getpass() odb = oracle_db.OracleDb(db_user, pw, database='oraclech_new') contest_id = raw_input('Current Contest ID? ') round_num = raw_input('Current Round Number? ') round_nums = round_num.split(',') topic_num = ra...
[ "def load_poems(self):\n file = open(self.name, \"r\")\n content = file.readlines()\n for i in content:\n self.add_msg_and_index(i.strip())", "def main(fin, fout):\n h = HTMLParser.HTMLParser()\n wiki_page = []\n page_flag = 0\n\n for line in fin:\n line = line.strip()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function parses the predictions in one individual message. If the message contains predictions, they will be inserted into the oracle database.
def ParsePredictions(odb, message, contest, round_nums): duel = 0 if contest['CompetitorsPerMatch'] == 2: duel = 1 user_id = odb.GetUserId(message['User']) if user_id is None: user_id = GetUserId(odb, message['User'], add_alt=1) # This enables admins to enter predictions for other users. # TODO: M...
[ "def parse_prediction(self, predictions):\n\t\tusers = list()\n\t\tprint(predictions)\n\t\tfor prediction in predictions:\n\t\t\tfor email in prediction:\n\t\t\t\tusers.append(email)\n\t\t\t\t\n\t\treturn users", "def process(self, message, **kwargs):\n if self.classifier is None:\n self.train()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompt for user input to figure out who predictions are for. This function is written so that the Oracle host can post predictions in the topic for other users.
def PromptForId(odb, message, orig_id=1): print 'Is this prediction for someone other than the poster?\n\n%s\n\n' % \ (message['Text']) diff_user = raw_input('(y/n): ') if diff_user == 'n': return orig_id user_name = raw_input('Username this prediction is for? ') user_id = odb.GetUserId(user_...
[ "def prompt_user():\n \n Q1= input(\"What type of plot output? (Enter #)\"+\"\\n\"+\"\\n\"+\"1.Countplot\"+\"\\n\"+\"2.Scatterplot\"+\"\\n\"+\"3.Boxplot\"+\"\\n\"+\"4.Simple Linear Regression Model\"+\"\\n\"+\"5.Multiple Linear Regression Model\"+\"\\n\")\n question(data,Xtrain,Xtest,ytrain,ytest, Q1)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tokenized_sentence = ["tu", "que", "tal"] all_words = ["tu", "yo", "soy", "que", "tal"] bag = [ 1, 0, 0, 1, 1]
def bag_of_words(tokenized_sentence, all_words): tokenized_sentence = [stem(w) for w in tokenized_sentence] #print(tokenized_sentence) bag = np.zeros_like(all_words, dtype=np.float32) for idx, w in enumerate(all_words): if w in tokenized_sentence: bag[idx] = 1.0 return bag
[ "def bag_of_words(tokenized_sentence,all_words):\r\n tokenized_sentence = [stem(w) for w in tokenized_sentence]\r\n bag = np.zeros(len(all_words), dtype=np.float32) # her cümle için ilk olarak sıfır veriyoru<\r\n for idx,w in enumerate(all_words): # yenilenen cümlelerin ve indexlerin sayısını tutmamızı ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
|coro| Calls the internal callback that the command holds.
async def __call__(self, *args, **kwargs): if self.cog is not None: # manually pass the cog class to the coro instead of calling it as a method return await self.callback(self.cog, *args, **kwargs) else: return await self.callback(*args, **kwargs)
[ "def callback_command_(self, cmd, visit_args, cbdata):\n self.callback_command(cmd, visit_args, cbdata)\n return", "async def _call_callbacks(self, command: str, arg: dict[str, Any]) -> None:\n callbacks = self._callbacks.get(command, self._default_callback)\n for callback in callbacks...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A decorator that registers a coroutine as a preinvoke hook. A preinvoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required.
def before_invoke(self, coro): if not asyncio.iscoroutinefunction(coro): raise TypeError('The pre-invoke hook must be a coroutine.') self._before_invoke = coro return coro
[ "def before_invoke(coro) -> Callable[[T], T]:\n def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:\n if isinstance(func, Command):\n func.before_invoke(coro)\n else:\n func.__before_invoke__ = coro\n return func\n return decorator # type: ign...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A decorator that registers a coroutine as a postinvoke hook. A postinvoke hook is called directly after the command is called. This makes it a useful function to cleanup database connections or any type of clean up required.
def after_invoke(self, coro): if not asyncio.iscoroutinefunction(coro): raise TypeError('The post-invoke hook must be a coroutine.') self._after_invoke = coro return coro
[ "def after_invoke(coro) -> Callable[[T], T]:\n def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:\n if isinstance(func, Command):\n func.after_invoke(coro)\n else:\n func.__after_invoke__ = coro\n return func\n return decorator # type: ignore...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
An iterator that recursively walks through all commands and subcommands. Yields
def walk_commands(self) -> typing.Generator[Command, None, None]: for command in self.commands: yield command if isinstance(command, Group): yield from command.walk_commands()
[ "def _allSubCommands(self) -> \"Command\":\n\n for subCommand in self._subCommands:\n # First yield the sub-command itself\n yield subCommand\n\n # Next yield all of the sub-command's sub-commands\n for subSubCommand in subCommand._allSubCommands:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A decorator that registers a coroutine as a preinvoke hook. This allows you to refer to one before invoke hook for several commands that do not have to be within the same cog. Example
def before_invoke(coro) -> Callable[[T], T]: def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: if isinstance(func, Command): func.before_invoke(coro) else: func.__before_invoke__ = coro return func return decorator # type: ignore
[ "def before_invoke(self, coro):\n if not asyncio.iscoroutinefunction(coro):\n raise TypeError('The pre-invoke hook must be a coroutine.')\n\n self._before_invoke = coro\n return coro", "async def cog_before_invoke(self, ctx):\n ...", "def _execute_pre_hook(self, context, f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A decorator that registers a coroutine as a postinvoke hook. This allows you to refer to one after invoke hook for several commands that do not have to be within the same cog.
def after_invoke(coro) -> Callable[[T], T]: def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: if isinstance(func, Command): func.after_invoke(coro) else: func.__after_invoke__ = coro return func return decorator # type: ignore
[ "def after_invoke(self, coro):\n if not asyncio.iscoroutinefunction(coro):\n raise TypeError('The post-invoke hook must be a coroutine.')\n\n self._after_invoke = coro\n return coro", "async def cog_after_invoke(self, ctx):\n ...", "def _execute_post_hook(self, context, fu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes a storage merge reader.
def __init__(self, session, storage_writer, task_storage_reader): super(StorageMergeReader, self).__init__() self._active_container_type = None self._active_generator = None self._container_types = [] self._event_data_identifier_mappings = {} self._event_data_parser_mappings = {} self._event...
[ "def _storage_init(self):\n if not self._storage.initialized:\n self._storage.init(self._module._py3_wrapper)", "def __init__(self):\n self.read_repository = {}", "def init_import(self):\n self.state = DxfReaderState.BEGINNING\n self.entity_type = DrawingEntityType.UNKNOWN...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle page head and create dict with different content
def handle_page_head(self, head_content): return_dict = {} return_dict['title'] = self.find_in_content(r'title:.+', head_content) return_dict['permalink'] = self.find_in_content(r'permalink:.+', head_content) return return_dict
[ "def _generate_head(self) -> NoReturn:\n\t\thead = HtmlTag('head')\n\t\t# Add meta tags.\n\t\thead.add(VoidHtmlTag('meta', attributes={'content': 'text/html', 'charset': 'utf-8'}))\n\t\thead.add(VoidHtmlTag('meta', attributes={'name': 'author', 'content': 'MD2HTML'}))\n\t\thead.add(\n\t\t\tVoidHtmlTag('meta', attri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle page body and create page dict
def handle_page_body(self, body_content): return_dict = {} return_dict['content'] = self.markdown_to_html(body_content) return return_dict
[ "def _create_page(self, body: Body):", "def create_full_page_dict(self) -> dict:\r\n page_dict = {\"page_name\": self.page_title,\r\n \"page_hyperlink\": self.target_page}\r\n\r\n for header in self.headers:\r\n\r\n basic_text = self.pull_word_list(header)\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read pages and save the instance into database
def read_pages(self): for file in os.listdir(self.repo_path): if file.endswith('.md'): if str(file) is not ('README.md' or '404.md'): with open(self.repo_path + file, 'r') as page_file: file_data = page_file.read() c...
[ "def save(self):\n database = Database()\n check_query = \"\"\"SELECT id FROM page WHERE img_url=%s\"\"\"\n insert_query = \"\"\"INSERT INTO page VALUES (NULL, %s, %s, %s)\"\"\"\n for page in self.pages:\n result = database.execute(check_query, [page])\n if result i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
read all files that we want at any time. we have to pass the extension and exception_list. exception_list will contain the list of all the files that should'nt be scanned. repo is the Repo db instance
def read_pages(self, repo, extension, exception_list): for file in os.listdir(self.repo_path): if file.endswith('.'.join(['', extension])): if file not in exception_list: file_handler = FileHandler(self.repo_path, file) content = file_handler.r...
[ "def get_files_with_extension(self, extension=sys.argv[1]) -> list:\n if extension == \"\":\n raise EnvironmentError(\"No extension provided!\")\n\n result = []\n for idx, file in enumerate(self.file_list):\n if re.search(extension + \"$\", file):\n result.a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update status to database
def _update_status(self): self._db_update({'status': self.status})
[ "def update_status(status):", "def update_status(self, status):\n pass", "def updateStatus(self, status):\n pass", "def UpdateStatus(self, status):\r\n self.status.update(status)", "def update_status(self, context):\n LOG.debug(\"Update status called.\")\n self.status.update()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to generate distributed training scripts.
def generate_disttrain_scipts(self): train_py = "/home/haihuam/Projects/RepPoints/mmdetection/tools/train.py" py = self.global_setting.get('python', sys.executable) ex_options = self.global_setting.get('train_options', str()) if not os.access(py, os.X_OK): py = "/home/haihua...
[ "def script_generator(self):\n\n self._get_free_tcp_port()\n\n train_py = \"/home/haihuam/Projects/RepPoints/mmdetection/tools/train.py\"\n py = self.global_setting.get('python', sys.executable)\n ex_options = self.global_setting.get('train_options', str())\n\n if not os.access(py...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to generate the scripts to analyze the log.
def script_generator(self): analyze_tool = "/home/haihuam/Projects/RepPoints/mmdetection/tools/analyze_logs.py" ex_options = self.global_setting.get('analyze_options', str()) py = self.global_setting.get('python', sys.executable) if os.access(py, os.X_OK): content = "set -e \...
[ "def log_analyzer():\n build_script_log_path = log_time_path()\n print(\"--- Build Script Analyzer ---\", file=sys.stderr)\n build_events = []\n total_duration = 0\n if os.path.exists(build_script_log_path):\n print(\"Build Script Log: {}\".format(build_script_log_path), file=sys.stderr)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to generate distributed training scripts.
def script_generator(self): self._get_free_tcp_port() train_py = "/home/haihuam/Projects/RepPoints/mmdetection/tools/train.py" py = self.global_setting.get('python', sys.executable) ex_options = self.global_setting.get('train_options', str()) if not os.access(py, os.X_OK): ...
[ "def generate_disttrain_scipts(self):\n train_py = \"/home/haihuam/Projects/RepPoints/mmdetection/tools/train.py\"\n py = self.global_setting.get('python', sys.executable)\n ex_options = self.global_setting.get('train_options', str())\n\n if not os.access(py, os.X_OK):\n py = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validates and modifies the dictionary Checks tube number against given radii, max tube lengths, and given q_dof. Checks that the lengths are all divisible by delta_x and raises an error if not.
def config_validation(configuration): tube_num = configuration.get('tube_number') q_dof = configuration.get('q_dof') radius = configuration.get('tube_radius') delta_x = configuration.get('delta_x') tube_lengths = configuration.get('tube_lengths') if isinstance(q_dof, int): configuration...
[ "def check(self):\n # check for nonsense or missing mandatory parameters\n mdp = self.parameters.get( \"md\", [] )\n fp = self.parameters.get( \"files\", [] )\n ip = self.parameters.get( \"intervals\", [] )\n\n for keyword in (\"temperature\", \"steps\", \"stepsize\"):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes an object and returns a list of names of all the methods in that class
def classmethods(class_object): fn_tuple_list = inspect.getmembers(class_object, predicate=inspect.ismethod) fn_names = [ f_name for (f_name, method) in fn_tuple_list if not f_name.startswith("_") ] return fn_names
[ "def all_methods( self, obj ):\n temp = []\n for name in dir( obj ):\n func = getattr( obj, name )\n if hasattr( func, '__call__' ):\n temp.append( name )\n return temp", "def methods_of(obj):\r\n result = []\r\n for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Akaike information criterion (AIC) is a measure of the relative goodness of fit of a statistical model. Akaike, Hirotugu (1974). "A new look at the statistical model
def calculate_AIC(self): hmm_ll_calculator = LikelihoodInfEngineHMM( dbn=self.model.dbn, hidden_node_index=0, check_dbn=False) ll_full = hmm_ll_calculator.calc_ll(self.seq_list, self.mismask_list) return 2 * ll_full - 2 * self._get_parameter_count()
[ "def test_aic_ms(distribution):\n print(\"TESTING: AIC model selection for %s distribution\" % distribution.upper())\n params = dist.DISTRIBUTIONS[distribution][dist.KEY_TEST_PARAMS]\n print(\" creating sample\")\n test_sample = dist.samples(distribution, params)\n print(\" calculating AIC for all ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Bayesian information criterion (BIC) is a criterion for model selection among a finite set of models. Schwarz, Gideon E. (1978). "Estimating the dimension of a model". Annals
def calculate_BIC(self): hmm_ll_calculator = LikelihoodInfEngineHMM( dbn=self.model.dbn, hidden_node_index=0, check_dbn=False) ll_full = hmm_ll_calculator.calc_ll(self.seq_list, self.mismask_list) return 2 * ll_full - self._get_parameter_count() * math.log( ...
[ "def calculate_bayesian_information_criterion(self):\n n = len(self.xx) # No. data points\n k = 2 + 2 * self.n_breakpoints # No. model parameters\n rss = self.residual_sum_squares\n self.bic = n * np.log(rss / n) + k * np.log(n)", "def BIC(self):\n return np.array([model.model...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create sequence and mismask (mask that identifies values as hidden, observed or missing) from a training set.
def _create_sequence_and_mismask(self, training_set, missing_residues): seq_list = [] mismask_list = [] if not self.show_warnings: warning_list = warnings.filters[:] warnings.filterwarnings('ignore', category=TorusDBNWarning) training_set_cou...
[ "def masking(X_train, X_test, y_train, y_test):\n # create mask to exclude NaN-values from train data\n mask_train = np.zeros(X_train.shape[0], dtype=np.bool)\n\n for i, subfeat in enumerate(X_train):\n if True in np.isnan(subfeat):\n mask_train[i] = True\n else:\n mask_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Optimization method to find the best size for the hidden node according to a training set.
def find_optimal_model( self, training_set, use_aic=False, min_node=10, max_node=90, start_size=20, end_size=5, node_samples=4, check_decreasing_ll=False, missing_residues=None): if not self.show_warnings: warning_list = warnings.filters[:] warnings....
[ "def train_size(self):", "def getMinNumHiddenNodes(numTrainingSamples, inputDimension, desiredApproxError):\n return numTrainingSamples * desiredApproxError / inputDimension", "def calculate_train_cluster_sizes():\n return calculate_cluster_sizes(os.path.expanduser(\"resources/legal_filter_train\"))", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print a message to the standard output, in case show_info is enabled.
def info(self, message): if self.show_info: print(message)
[ "def _info(message):\n print('_info >' + message)", "def info(self, message):\n if not self.args.quiet:\n print(message)", "def info(msg):\n if script.verbosity_level >= script.VERBOSITY_DEFAULT:\n print msg", "def print_info(message: str):\n global verbose\n if verbose:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Does the url contain a downloadable resource
def is_downloadable(url): h = requests.head(url, allow_redirects=True) header = h.headers content_type = header.get('content-type') if 'text' in content_type.lower(): return False if 'html' in content_type.lower(): return False return True
[ "def is_downloadable(url):\n print(url)\n try:\n h = requests.head(url, allow_redirects=True)\n print('lo hace')\n header = h.headers\n content_type = header.get('content-type')\n if 'text' in content_type.lower():\n return False\n if 'html' in content_type...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Go to the given workspace number.
def go_to(i3: i3ipc.Connection, workspace: int): i3.command(f"workspace number {workspace}")
[ "def change_workspace(num):\n LOGGER.debug('change_workspace: requested workspace {}'.format(num))\n output = get_focused_output()\n prefix = get_workspace_prefix(output)\n ws_num = get_workspace_num(prefix, num)\n workspace = get_workspace(ws_num, prefix, num)\n result = switch_workspace(f'{works...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move the focused container to the given workspace.
def move_to(i3: i3ipc.Connection, workspace: int): i3.command(f"move container to workspace number {workspace}")
[ "def move_container(i3, name, monitor, container_id=None):\n i3.command(f'move container to workspace {name}')\n i3.command(f'workspace {name}, move workspace to output {monitor}')\n if container_id:\n i3.command(f'[con_id=\"{container_id}\"] focus')", "def i3wm_move_workspace_to_other_output():\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the workspace to switch to. If the current workspace is a target, go to the next target. If the current workspace isn't a target, go to the first open target.
def get_target_workspace(current_workspace, open_workspaces, target_workspaces): logger.debug('get_target_workspace(current: %s, open: %s, targets: %s)', current_workspace, open_workspaces, target_workspaces) if len(target_workspaces) <= 0: logger.debug('No workspaces given - defaultin...
[ "def workspace_go(wm, win, state, motion): # pylint: disable=W0613\n target = wm.get_workspace(None, motion)\n if not target:\n return # It's either pinned, on no workspaces, or there is no match\n target.activate(int(time.time()))", "def go_to(i3: i3ipc.Connection, workspace: int):\n i3.comm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the number of the current workspace.
def get_current_workspace_num(i3: i3ipc.Connection): return i3.get_tree().find_focused().workspace().num
[ "def workspace_id(self) -> str:\n return pulumi.get(self, \"workspace_id\")", "def workspace_id(self):\n return self._workspace_id", "def CurrentWorkspace():\n return _C.CurrentWorkspace()", "def get_current_window():\n\n try:\n return vim.current.window.number - 1\n except Attri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the numbers of open workspaces.
def get_open_workspaces(i3: i3ipc.Connection): return [ws.num for ws in i3.get_tree().workspaces()]
[ "def get_opened_windows_list():\n\n global opened_windows_names\n EnumWindows(EnumWindowsProc(foreach_window), 0)\n return opened_windows_names", "def get_open_disk_space(self):\n count = 0\n for i in range(self.size):\n if self.disk_mem[i]==\".\":\n count += 1\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Provides an ndimensional parallel iterator that generates index tuples for each iteration point. Sequentially, pndindex is identical to np.ndindex.
def pndindex(*args): return np.ndindex(*args)
[ "def indicesIter(self):\n \n pass", "def pndindex(*args):\n return np.ndindex(*args)", "def multiindex_iterator (multiindex_shape):\n return itertools.product(*tuple(range(dim) for dim in multiindex_shape))", "def ndindex(ix):\n\n if len(ix)==2:\n for i in range(ix[0]):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the name for the handler called from ``__init__`` if a name is not given.
def _create_name(self) -> str: return self.stream.__class__.__name__
[ "def _init_name(self, name):\n if name is None:\n if self.__name__ is not None:\n return\n if type(self) is not Operator:\n name = type(self).__name__\n elif self.direct is not None and self.direct.__name__ not in (\n '<lambda>',\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attempts to cache `objdoc` for module `modname`.
def __setitem__(self, modname: str, objdoc: Objdoc): spec = importlib.util.find_spec(modname) if spec.origin is None: raise CannotCache(f"not a module file; can't cache: {modname}") path = self.__get_path(spec) path = path.parent / (path.name + ".json.gz") check = _g...
[ "def __put_module_in_sys_cache(module_name, module_obj):\n #try:\n #if hasattr(sys, 'stypy_module_cache'):\n sys.stypy_module_cache[module_name] = module_obj\n # else:\n # __preload_sys_module_cache()\n # sys.stypy_module_cache[module_name] = module_obj\n # except:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
True if `path` is a subpath of `other`.
def is_subpath(path: Path, other: Path): try: Path(path).relative_to(other) except ValueError: return False else: return True
[ "def is_sub(parent, path):\n parent = canonical_path(parent, resolve_link=False)\n path = canonical_path(path, resolve_link=False)\n return os.path.commonprefix([parent, path]) == parent", "def _issubpath(self, a, b):\n p1 = a.rstrip(os.sep).split(os.sep)\n p2 = b.rstrip(os.sep).split(os.se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the path to the objdoc cache for a module.
def _get_pycache_path(spec: ModuleSpec) -> Path: # Refuse to do __pycache__ caching for anything in PREFIX. # FIXME: Not sure if this is the right policy. if is_subpath(spec.origin, sys.prefix): raise CannotCache(spec.name) # Find out where the module cache file goes. mod_cache_path = impor...
[ "def get_cache_path(self):", "def apidoc_cache_file(self):\n # type: () -> str\n\n return os.path.join(self.apidoc_cache_dir, '{0}{1}'.format(self.apidoc_cache_name, self.cache_extension))", "def _get_module_path(module):\n return pathlib.Path(os.path.dirname(os.path.abspath(inspect.getfile(mod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the path to the supdoc cache directory.
def get_cache_dir() -> Path: try: cache_dir = Path(os.environ["SUPDOC_CACHE_DIR"]) except KeyError: try: cache_dir = Path(os.environ["XDG_CACHE_DIR"]) except KeyError: if sys.platform == "linux": cache_dir = Path.home() / ".cache" elif ...
[ "def write_cache_path(self):\n\n return self.__user_cache_dir or \\\n os.path.join(self.imgdir, IMG_PUB_DIR)", "def get_cache_path(self):", "def _get_cache_dir(self):\n return self.data['info']['root_cache_dir']", "def host_cache_dir(self):\n cache_dir = SpaCyMo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a cache that stores files in a separate directory.
def DirCache(dir: Path) -> Cache: dir = Path(dir) return Cache(lambda spec: dir / spec.name)
[ "def cache_directory(fs):\n # type: (_T) -> WrapCachedDir[_T]\n return WrapCachedDir(fs)", "def get_new_cache() -> Cache:\n\n return Cache(tempfile.mkdtemp())", "def set_cache(new_path=None):\n\n global CACHE_DIR, API_CACHE, SPRITE_CACHE\n\n if new_path is None:\n new_path = get_default_ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Caches modules in `modnames` and their submodules.
def cache_modules(*modnames) -> None: inspector = Inspector() modnames = { n for m in modnames for n in find_submodules(m) } for modname in modnames: logging.debug(f"inspecting: {modname}") objdoc = inspector.inspect_module(modname) logging.debug(f"writing cache: {modname}") ...
[ "def generate_modules_cache(self, modules, underlined=None,\r\n task_handle=taskhandle.NullTaskHandle()):\r\n job_set = task_handle.create_jobset(\r\n 'Generatig autoimport cache for modules', len(modules))\r\n for modname in modules:\r\n job_set.sta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a driver to the specified appium server & return driver,touch objects.
def create_driver(self, app_server): config = self.config[app_server] cmd = config['CMD'] server_name = config['NAME'] log_file_name = config['LOG_FILE_NAME'] full_log_path = os.path.join(os.environ['basedir'], 'logs', 'appium', log_file_name) url = config['URL'] ...
[ "def create_driver(self, app_server):", "def appium_init(self):\n desired_cups = {}\n desired_cups['platformName'] = 'Android'\n desired_cups['platformVersion'] = android_version\n desired_cups['deviceName'] = device_name\n desired_cups['appPackage'] = pkg_name\n desired_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Close the application, quits the drivers.
def close_driver(self): package_dict = self.config['PACKAGE'] try: self.driver.terminate_app(package_dict[self.app_name]) # Kill app self.driver.quit() # Kill drivers except WebDriverException: pass finally: LOGGER.info("Closed {apl} on {...
[ "def program_close():\n\n print(\"\\n\")\n sys.exit(0)", "def quit_driver(self,):\n\n self.driver.quit()", "def close_application(self):\n if mb.askyesno(translate(QUIT_TITLE), message=translate(QUIT_DIALOG),\n icon=\"question\"):\n self.main_frame.destroy()"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read mobile window size & sets the scroll length for a mobile.
def set_scroll_length(self): size = self.driver.get_window_size() self.x_cord = int(size['width'] / 2) self.start_y = int(size['height'] * 0.9) self.end_y = int(size['height'] * 0.1)
[ "def set_scroll_length(self):", "def get_window_size(self):\n if not self._window_size:\n is_mobile_web = self.driver_wrapper.is_android_web_test() or self.driver_wrapper.is_ios_web_test()\n if is_mobile_web and self.driver_wrapper.driver.current_context != 'NATIVE_APP':\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform tap for requested element or coordinates.
def tap_screen(self, element=None, config=None, x_cord=None, y_cord=None): if element and config: self.touch.tap(x=config[element]['x'], y=config[element]['y']).perform() elif x_cord: self.touch.tap(x=x_cord, y=y_cord).perform() else: ...
[ "def tap_on(driver, element):\n loc_type, loc_value = element\n actions = TouchAction(driver)\n actions.tap(driver.find_element(loc_type, loc_value)).perform()", "def tap(self, elem=None, x=0, y=0, count=1):\n self.switch_to_app()\n if elem:\n action = MobileTouchActi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Swipe the screen to scroll down.
def swipe_up(self): self.driver.swipe(start_x=self.x_cord, start_y=self.start_y, end_x=self.x_cord, end_y=self.end_y, duration=1000)
[ "def swipe_down(self):\n self.swipe_sub(SWIPE_MATRIX[1])", "def swipe_element_to_bottom_of_screen(self):\n window_size_y = self.driver.get_window_size()[\"height\"]\n self.swipe(30, window_size_y - 80, 30, window_size_y - 500)", "def swipeDown (self) :\n rotated = Grid(np.rot90(np.rot90(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Swipe the screen to move right.
def swipe_right(self, config): self.driver.swipe(start_x=config['SWIPE_RIGHT']['x'], start_y=config['SWIPE_RIGHT']['y'], end_x=(config['SWIPE_RIGHT']['x'] - 400), end_y=config['SWIPE_RIGHT']['y'], duration=1000)
[ "def swipe_right(self):\n self.swipe_sub(SWIPE_MATRIX[3])", "def swipe_right(self, config):", "def swipeRight (self) :\n rotated = Grid(np.rot90(self.grid))\n self.grid = np.rot90(np.rot90(np.rot90(rotated.swipeBase())))", "def move_right(self):\n self.tape.move_right()", "def move_r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to perform long press of element or a coordinate and slide.
def press_long_and_slide(self, element, x_cord, y_cord, hold_time): if element: self.touch.long_press(el=element, duration=hold_time).move_to( x=x_cord, y=y_cord).release().perform() else: LOGGER.error('Element and co-ordinates must be given for long press!')
[ "def press_long_and_slide(self, element, x_cord, y_cord, hold_time):", "def do_longpress(self, str_arg):\n arg = validateString(str_arg)\n # if arg.startswith(r'('):\n # raise ValueError('Bad argument, You may want to use longpress2 with coordinates as auguments.')\n x = 0\n y =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Press back button on mobile for 'num' times.
def press_back(self, num=1): for _11 in range(0, num): # _11 as dummy variable self.driver.back()
[ "def press_back(self, num=1):", "def press_back_button(self):\n self.driver.back()", "def go_back(self):", "def __select_back_btn(self):\n for _ in range(2):\n self.fc.select_back()\n if self.printers.verify_printers_screen(raise_e=False):\n return True\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return element according to element type given.
def return_element(self, el_type, text, bounds=False): if el_type == 'access': element = self.driver.find_element_by_accessibility_id(text) elif el_type == 'id': element = self.driver.find_element_by_id(text) elif el_type == 'xpath' and bounds: element = self....
[ "def element_type(self) -> global___Type:", "def _from_element(self, ele: ET.Element, py_type: Optional[str] = None) -> Any:\n # pylint: disable=too-many-branches\n py_type = py_type or ele.attrib.get(\"type\")\n text = ele.text or \"\"\n value = None # type: Any\n if py_type =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return list of elements of class 'android.widget.TextView'.
def return_textview_elements(self): return self.driver.find_elements_by_class_name('android.widget.TextView')
[ "def get_all_text_view_text(self, textview):\n\t\ttextbuffer = textview.get_buffer()\n\t\tstartiter, enditer = textbuffer.get_bounds()\n\t\ttext = startiter.get_slice(enditer)\n\t\treturn text", "def get_text(self) -> List[str]:\n return self.__texts", "def get_texts(self) -> List[str]:\n return s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return element according to 'text' or 'search text' and clicks it.
def click_using_class(self, text, search_text=None, delay=3, is_button=False): if search_text: class_name = 'android.widget.EditText' button = self.return_button(search_text, class_name) elif is_button: class_name = 'android.widget.Button' button = self.re...
[ "def click_by_text(self, text):\n self.locate_element('p,' + text).click()", "def click_using_class(self, text, search_text, delay=3, is_button=False):", "def try_click_text_part(self, text):\r\n try:\r\n self.driver.find_element_by_xpath(\r\n '//*[contains(text(), \"%s\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for delete_opening_balance_journals_key
def test_delete_opening_balance_journals_key(self): pass
[ "def test_get_opening_balance_journals_key(self):\n pass", "def test_delete_business_exchange_rates_key(self):\n pass", "def test_get_opening_balance_journals(self):\n pass", "def test_post_opening_balance_journals(self):\n pass", "def test_fundinginformations_id_delete(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for get_opening_balance_journals
def test_get_opening_balance_journals(self): pass
[ "def test_get_opening_balance_journals_key(self):\n pass", "def test_post_opening_balance_journals(self):\n pass", "def test_delete_opening_balance_journals_key(self):\n pass", "def testgetDeals():\n ans = app.getDeals(splitMonths = True)\n assert(len(ans[0]) == 12 and ans[1] > 0) \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for get_opening_balance_journals_key
def test_get_opening_balance_journals_key(self): pass
[ "def test_get_opening_balance_journals(self):\n pass", "def test_delete_opening_balance_journals_key(self):\n pass", "def test_post_opening_balance_journals(self):\n pass", "def test_get_business_exchange_rates_key(self):\n pass", "def _check_open_orders(self, **kargs):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for post_opening_balance_journals
def test_post_opening_balance_journals(self): pass
[ "def test_get_opening_balance_journals(self):\n pass", "def test_get_opening_balance_journals_key(self):\n pass", "def test_delete_opening_balance_journals_key(self):\n pass", "def test_finalize_and_open_period(self):\n employee_payments_qty = EmployeePayment.objects.filter(employe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Go to the page 'url', find the next link to got, then extract the JSON query result, find the wanted train, and display the results.
def main(url, MY_OUTWARD_TIME_MINI, MY_OUTWARD_TIME_MAXI="23:59"): MY_OUTWARD_TIME_MINI = MY_OUTWARD_TIME_MINI.replace("h", ":") MY_OUTWARD_TIME_MAXI = MY_OUTWARD_TIME_MAXI.replace("h", ":") # Create the web browser object b = RB(history=True, allow_redirects=True) # Open the page b.open(url) ...
[ "def _pull_page_rec(self, url):\n print \"Pulling\", url\n res = self.session.open(url)\n pyq = pyquery.PyQuery(res.get_data())\n lev = lambda s: re.search('\\\\((\\\\d)\\\\)', s).group(1)\n for entry_element in pyq('div.entry'):\n enq = pyquery.PyQuery(entry_element)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generate the hashes for the passwords
def gen_hash(self, data): password_gen = crypt.encrypt(data) return password_gen
[ "def _get_pwd_hash(self):\n data_to_hash = (self.realm + self.email_addr + self.pwd).encode()\n data_hash = hashlib.sha256(data_to_hash)\n for _ in range(4096):\n data_hash = hashlib.sha256(data_hash.digest())\n return data_hash.hexdigest()", "def gen_password_hash(password)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }