code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def add_if_changed(self, resource): if (resource.change is not None): self.resources.append(resource) else: raise ChangeTypeError(resource.change)
module function_definition identifier parameters identifier identifier block if_statement parenthesized_expression comparison_operator attribute identifier identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list identifier else_clause block raise_statement call...
Add resource if change is not None else ChangeTypeError.
def _set_publication_info_field(self, field_name, value): self._ensure_reference_field('publication_info', {}) self.obj['reference']['publication_info'][field_name] = value
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end dictionary expression_statement assignment subscript subscript subscript attribute identifier identifier string st...
Put a value in the publication info of the reference.
def exit_statistics(hostname, start_time, count_sent, count_received, min_time, avg_time, max_time, deviation): end_time = datetime.datetime.now() duration = end_time - start_time duration_sec = float(duration.seconds * 1000) duration_ms = float(duration.microseconds / 1000) duration = duration_sec ...
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier binary_operator ide...
Print ping exit statistics
def target_to_hostname(target): if len(target) == 0 or len(target) > 255: return None if not re.match(r'^[\w.-]+$', target): return None return [target]
module function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator call identifier argument_list identifier integer comparison_operator call identifier argument_list identifier integer block return_statement none if_statement not_operator call attribute identifier identi...
Attempt to return a single hostname list from a target string.
def ip_in_subnet(ip, subnet): ipaddr = int(''.join(['%02x' % int(x) for x in ip.split('.')]), 16) netstr, bits = subnet.split('/') netaddr = int(''.join(['%02x' % int(x) for x in netstr.split('.')]), 16) mask = (0xffffffff << (32 - int(bits))) & 0xffffffff return (ipaddr & mask) == (netaddr & mask)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute string string_start string_end identifier argument_list list_comprehension binary_operator string string_start string_content string_end call identifier ar...
Does IP exists in a given subnet utility. Returns a boolean
def rm_blanks(self): _blanks = [k for k in self._dict.keys() if not self._dict[k]] for key in _blanks: del self._dict[key]
module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier call attribute attribute identifier identifier identifier argument_list if_clause not_operator subscript attribute identifier identifier identifier for_stat...
Get rid of parameters that has no value.
def check_origin(self, origin): mod_opts = self.application.mod_opts if mod_opts.get('cors_origin'): return bool(_check_cors_origin(origin, mod_opts['cors_origin'])) else: return super(AllEventsHandler, self).check_origin(origin)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement call attribute identifier identifier argument_list string string_start string_content string_end block return_statement call identifie...
If cors is enabled, check that the origin is allowed
def save_slope(self, rootpath, raw=False, as_int=False): self.save_array(self.mag, None, 'mag', rootpath, raw, as_int=as_int)
module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier false block expression_statement call attribute identifier identifier argument_list attribute identifier identifier none string string_start string_content string_end identifier identif...
Saves the magnitude of the slope to a file
def as_serializable(self): other = MeanStdFilter(self.shape) other.sync(self) return other
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
Returns non-concurrent version of current class
def getServices(self): try: conn = self.dbi.connection() result = self.serviceslist.execute(conn) return result except Exception as ex: msg = (("%s DBSServicesRegistry/getServices." + " %s\n. Exception trace: \n %s") % ...
module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list iden...
Simple method that returs list of all know DBS instances, instances known to this registry
def _fetch(self, request): client = self.client call = Call(__id__=client.newCall(request.request)) call.enqueue(request.handler) request.call = call
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list attribute identi...
Fetch using the OkHttpClient
def _reroot(self): rerooter = Rerooter() self.tree = rerooter.reroot_by_tree(self.reference_tree, self.tree)
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier
Run the re-rooting algorithm in the Rerooter class.
def DiamReq(cmd, **fields): upfields, name = getCmdParams(cmd, True, **fields) p = DiamG(**upfields) p.name = name return p
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier true dictionary_splat identifier expression_statement assignment identifier call identifier argument_list dict...
Craft Diameter request commands
def end_prov_graph(self): endTime = Literal(datetime.now()) self.prov_g.add((self.entity_d, self.prov.generatedAtTime, endTime)) self.prov_g.add((self.activity, self.prov.endedAtTime, endTime))
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list tuple attribute identifier identifier...
Finalize prov recording with end time
def _expect_vars(vs=None): if vs is None: return list() elif isinstance(vs, Variable): return [vs] else: checked = list() for v in vs: if isinstance(v, Variable): checked.append(v) else: ...
module function_definition identifier parameters default_parameter identifier none block if_statement comparison_operator identifier none block return_statement call identifier argument_list elif_clause call identifier argument_list identifier identifier block return_statement list identifier else_clause block expressi...
Verify the input type and return a list of Variables.
def end_script(self): if self.remote_bridge.status not in (BRIDGE_STATUS.RECEIVED, BRIDGE_STATUS.WAITING): return [1] self.remote_bridge.status = BRIDGE_STATUS.RECEIVED return [0]
module function_definition identifier parameters identifier block if_statement comparison_operator attribute attribute identifier identifier identifier tuple attribute identifier identifier attribute identifier identifier block return_statement list integer expression_statement assignment attribute attribute identifier...
Indicate that we have finished receiving a script.
def legal_date(year, month, day): try: assert year >= 1 assert 0 < month <= 14 assert 0 < day <= 28 if month == 14: if isleap(year + YEAR_EPOCH - 1): assert day <= 2 else: assert day == 1 except AssertionError: raise...
module function_definition identifier parameters identifier identifier identifier block try_statement block assert_statement comparison_operator identifier integer assert_statement comparison_operator integer identifier integer assert_statement comparison_operator integer identifier integer if_statement comparison_oper...
Checks if a given date is a legal positivist date
def accounts(): import yaml for path in account_files: try: c_dir = os.path.dirname(path) if not os.path.exists(c_dir): os.makedirs(c_dir) with open(path, 'rb') as f: return yaml.load(f)['accounts'] except (OSError, IOError) as ...
module function_definition identifier parameters block import_statement dotted_name identifier for_statement identifier identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement not_operator call attrib...
Load the accounts YAML file and return a dict
def patchFile(filename, replacements): patched = Utility.readFile(filename) for key in replacements: patched = patched.replace(key, replacements[key]) Utility.writeFile(filename, patched)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list id...
Applies the supplied list of replacements to a file
def _getMyFirstDatetimeTo(self): myFirstDt = self._getMyFirstDatetimeFrom() if myFirstDt is not None: daysDelta = dt.timedelta(days=self.num_days - 1) return getAwareDatetime(myFirstDt.date() + daysDelta, self.time_to, ...
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_arg...
The datetime this event first finished, or None if it never did.
def __get_value(self, field_name): value = request.values.get(field_name) if value is None: if self.json_form_data is None: value = None elif field_name in self.json_form_data: value = self.json_form_data[field_name] return value
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier none block if_statement comparison_operator attribute identifier identifi...
Get request Json value by field name
def Join(self): for _ in range(self.JOIN_TIMEOUT_DECISECONDS): if self._queue.empty() and not self.busy_threads: return time.sleep(0.1) raise ValueError("Timeout during Join() for threadpool %s." % self.name)
module function_definition identifier parameters identifier block for_statement identifier call identifier argument_list attribute identifier identifier block if_statement boolean_operator call attribute attribute identifier identifier identifier argument_list not_operator attribute identifier identifier block return_s...
Waits until all outstanding tasks are completed.
async def handle_client_ping(self, client_addr, _: Ping): await ZMQUtils.send_with_addr(self._client_socket, client_addr, Pong())
module function_definition identifier parameters identifier identifier typed_parameter identifier type identifier block expression_statement await call attribute identifier identifier argument_list attribute identifier identifier identifier call identifier argument_list
Handle an Ping message. Pong the client
def clear(self): "Removes all entries from the config map" self._pb.IntMap.clear() self._pb.StringMap.clear() self._pb.FloatMap.clear() self._pb.BoolMap.clear()
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list expression_statement call attribute attribute attribute identifier identi...
Removes all entries from the config map
def update(ctx, no_restart, no_rebuild): instance = ctx.obj['instance'] log('Pulling github updates') run_process('.', ['git', 'pull', 'origin', 'master']) run_process('./frontend', ['git', 'pull', 'origin', 'master']) if not no_rebuild: log('Rebuilding frontend') install_frontend(in...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end expr...
Update a HFOS node
def endpoint(request): s = getServer(request) query = util.normalDict(request.GET or request.POST) try: openid_request = s.decodeRequest(query) except ProtocolError, why: return direct_to_template( request, 'server/endpoint.html', {'error': str(why)}) ...
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list boolean_operator attribute identifier identifier attribute identifier identi...
Respond to low-level OpenID protocol messages.
def update_user_label(self): self._user_label = _uniqueid_to_uniquetwig(self._bundle, self.unique_label) self._set_curly_label()
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list
finds this parameter and gets the least_unique_twig from the bundle
def combine_nt_lists(lists, flds, dflt_null=""): combined_nt_list = [] lens = [len(lst) for lst in lists] assert len(set(lens)) == 1, \ "LIST LENGTHS MUST BE EQUAL: {Ls}".format(Ls=" ".join(str(l) for l in lens)) ntobj = cx.namedtuple("Nt", " ".join(flds)) for lst0_lstn in zip(*lists): ...
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_end block expression_statement assignment identifier list expression_statement assignment identifier list_comprehension call identifier argument_list identifier for_in_clause identifier identif...
Return a new list of namedtuples by zipping "lists" of namedtuples or objects.
def health(): up_time = time.time() - START_TIME response = dict(service=__service_id__, uptime='{:.2f}s'.format(up_time)) return response, HTTPStatus.OK
module function_definition identifier parameters block expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier call...
Check the health of this service.
def check_engine(handle): if handle == 'help': dump_engines() sys.exit(0) if handle not in engines.engines: print('Engine "%s" is not available.' % (handle,), file=sys.stderr) sys.exit(1)
module function_definition identifier parameters identifier block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call identifier argument_list expression_statement call attribute identifier identifier argument_list integer if_statement comparison_ope...
Check availability of requested template engine.
def list_users(self): crypt = self._decrypt_file() self.logger.info(crypt.stderr) raw_userlist = crypt.stderr.split('\n') userlist = list() for index, line in enumerate(raw_userlist): if 'gpg: encrypted' in line: m = re.search('ID (\w+)', line) ...
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment ide...
Get user list from the encrypted passdb file
def _parse_table(self): reset = self._head self._head += 2 try: self._push(contexts.TABLE_OPEN) padding = self._handle_table_style("\n") except BadRoute: self._head = reset self._emit_text("{") return style = self._pop()...
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement augmented_assignment attribute identifier identifier integer try_statement block expression_statement call attribute identifier identifier argument_list attri...
Parse a wikicode table by starting with the first line.
def calibration_cache_path(self): if self.__ifo and self.__start > 0: cal_path = self.job().get_config('calibration','path') if ( self.__LHO2k.match(self.__ifo) and (self.__start >= 729273613) and (self.__start <= 734367613) ): if self.__start < int( self.job().get_co...
module function_definition identifier parameters identifier block if_statement boolean_operator attribute identifier identifier comparison_operator attribute identifier identifier integer block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argume...
Determine the path to the correct calibration cache file to use.
def download(self, filename, format='sdf', overwrite=False, resolvers=None, **kwargs): download(self.input, filename, format, overwrite, resolvers, **kwargs)
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier false default_parameter identifier none dictionary_splat_pattern identifier block expression_statement call identifier argument_list attribute id...
Download the resolved structure as a file
def deb64_app(parser, cmd, args): parser.add_argument('value', help='the value to base64 decode, read from stdin if omitted', nargs='?') args = parser.parse_args(args) return deb64(pwnypack.main.string_value_or_stdin(args.value))
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string strin...
base64 decode a value.
def list_files(start_path): s = u'\n' for root, dirs, files in os.walk(start_path): level = root.replace(start_path, '').count(os.sep) indent = ' ' * 4 * level s += u'{}{}/\n'.format(indent, os.path.basename(root)) sub_indent = ' ' * 4 * (level + 1) for f in files: ...
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content escape_sequence string_end for_statement pattern_list identifier identifier identifier call attribute identifier identifier argument_list identifier block expression_statement ...
tree unix command replacement.
def needs_confirmation(self): if EMAIL_CONFIRMATION: self.is_active = False self.save() return True else: return False
module function_definition identifier parameters identifier block if_statement identifier block expression_statement assignment attribute identifier identifier false expression_statement call attribute identifier identifier argument_list return_statement true else_clause block return_statement false
set is_active to False if needs email confirmation
def coord_wrap(self, *args): yield from self.cell.coord.start(self) yield from self.coro(*args) yield from self.cell.coord.finish(self)
module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement yield call attribute attribute attribute identifier identifier identifier identifier argument_list identifier expression_statement yield call attribute identifier identifier argument_list list_splat iden...
Wrap the coroutine with coordination throttles.
def load_notebook(self, name): with open(self.get_path('%s.ipynb'%name)) as f: nb = nbformat.read(f, as_version=4) return nb,f
module function_definition identifier parameters identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier as_pattern_target identifier block expres...
Loads a notebook file into memory.
def node_query(self, node): if isinstance(node, ast.Call): assert node.args arg = node.args[0] if not isinstance(arg, ast.Str): return else: raise TypeError(type(node)) return arg.s
module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier attribute identifier identifier block assert_statement attribute identifier identifier expression_statement assignment identifier subscript attribute identifier identifier integer if_statem...
Return the query for the gql call node
def duplicate(self, template_fact, **modifiers): newfact = template_fact.copy() newfact.update(dict(self._get_real_modifiers(**modifiers))) return self.declare(newfact)
module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call identifier argument_list call attrib...
Create a new fact from an existing one.
def merge(self, other): for this, other in zip(self.stats, other.stats): this.merge(other)
module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier
Merge all children stats.
def read_byte(self, address): LOGGER.debug("Reading byte from device %s!", hex(address)) return self.driver.read_byte(address)
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier return_statement call attribute attribute identifier identifier identifier argument_...
Reads unadressed byte from a device.
def refs_equal(olditem, newitem): oldrefs = olditem.references newrefs = newitem.references ref_equal = lambda oldref, newref: True if (len(oldref) == len(newref)) and all( x in oldref for x in newref) else False if len(oldrefs) == len(newrefs) and all( any(re...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier lambda lambda_parameters identifier identifier con...
tests for exactly identical references
def _format_lon(self, lon): if self.ppd in [4, 16, 64, 128]: return None else: return map(lambda x: "{0:0>3}".format(int(x)), self._map_center('long', lon))
module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier list integer integer integer integer block return_statement none else_clause block return_statement call identifier argument_list lambda lambda_parameters identifier call attribu...
Returned a formated longitude format for the file
def wheel_dist_name(self): components = (safer_name(self.distribution.get_name()), safer_version(self.distribution.get_version())) if self.build_number: components += (self.build_number,) return '-'.join(components)
module function_definition identifier parameters identifier block expression_statement assignment identifier tuple call identifier argument_list call attribute attribute identifier identifier identifier argument_list call identifier argument_list call attribute attribute identifier identifier identifier argument_list i...
Return distribution full name with - replaced with _
def _render_rate_limit_page(self, exception=None): auth = request.args.get('auth') is_auth = auth == '1' if auth else bool(self.auth) return render_template('limit.html', is_authenticated=is_auth), 403
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier conditional_expr...
Renders the rate limit page.
def namedb_get_all_namespace_ids( cur ): query = "SELECT namespace_id FROM namespaces WHERE op = ?;" args = (NAMESPACE_READY,) namespace_rows = namedb_query_execute( cur, query, args ) ret = [] for namespace_row in namespace_rows: ret.append( namespace_row['namespace_id'] ) return ret
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier tuple identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier...
Get a list of all READY namespace IDs.
def evaluate_object(obj, cls=None, cache=False, **kwargs): old_obj = obj if isinstance(obj, Element): if cache: obj = obj.evaluate_cached(**kwargs) else: obj = obj.evaluate(cache=cache, **kwargs) if cls is not None and type(obj) != cls: ...
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier false dictionary_splat_pattern identifier block expression_statement assignment identifier identifier if_statement call identifier argument_list identifier identifier block if_statement identifier ...
Evaluates elements, and coerces objects to a class if needed
def filterMapAttrs(records=getIndex(), **tags): if len(tags) == 0: return records ret = [] for record in records: if matchRecordAttrs(record, tags): ret.append(record) return ret
module function_definition identifier parameters default_parameter identifier call identifier argument_list dictionary_splat_pattern identifier block if_statement comparison_operator call identifier argument_list identifier integer block return_statement identifier expression_statement assignment identifier list for_st...
matches available maps if their attributes match as specified
def artist(netease, name, id): if name: netease.download_artist_by_search(name) if id: netease.download_artist_by_id(id, 'artist'+str(id))
module function_definition identifier parameters identifier identifier identifier block if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier binary...
Download a artist's hot songs by name or id.
def _dataflash_dir(self, mpstate): if mpstate.settings.state_basedir is None: ret = 'dataflash' else: ret = os.path.join(mpstate.settings.state_basedir,'dataflash') try: os.makedirs(ret) except OSError as e: if e.errno != errno.EEXIST: ...
module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute attribute identifier identifier identifier none block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identif...
returns directory path to store DF logs in. May be relative
def groups(self): return Groups(url="%s/groups" % self.root, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port, initalize=False)
module function_definition identifier parameters identifier block return_statement call identifier argument_list keyword_argument identifier binary_operator string string_start string_content string_end attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifi...
returns the group object
def standard_program_header(self, title, length, line=32768): self.save_header(self.HEADER_TYPE_BASIC, title, length, param1=line, param2=length)
module function_definition identifier parameters identifier identifier identifier default_parameter identifier integer block expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier id...
Generates a standard header block of PROGRAM type
def vectorize(self, docs): doc_core_sems, all_concepts = self._extract_core_semantics(docs) shape = (len(docs), len(all_concepts)) vecs = np.zeros(shape) for i, core_sems in enumerate(doc_core_sems): for con, weight in core_sems: j = all_concepts.index(con) ...
module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier tuple call identifier argument_list identifier call identifier argument...
Vectorizes a list of documents using their DCS representations.
def data_slice(self, slice_ind): if self.height is None: return self.data[slice_ind] return self.data[slice_ind, ...]
module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier none block return_statement subscript attribute identifier identifier identifier return_statement subscript attribute identifier identifier identifier ellipsis
Returns a slice of datapoints
def classifyplot_from_plotfiles(plot_files, out_csv, outtype="png", title=None, size=None): dfs = [pd.read_csv(x) for x in plot_files] samples = [] for df in dfs: for sample in df["sample"].unique(): if sample not in samples: samples.append(sample) df = pd.concat(dfs)...
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier list_comprehension call attribute identifier identifier a...
Create a plot from individual summary csv files with classification metrics.
def list_npm_modules(collector, no_print=False): default = ReactServer().default_npm_deps() for _, module in sorted(collector.configuration["__active_modules__"].items()): default.update(module.npm_deps()) if not no_print: print(json.dumps(default, indent=4, sort_keys=True)) return defau...
module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier call attribute call identifier argument_list identifier argument_list for_statement pattern_list identifier identifier call identifier argument_list call attribute subscript at...
List the npm modules that get installed in a docker image for the react server
def path(self): (x, y) = self.tile return os.path.join('%u' % self.zoom, '%u' % y, '%u.img' % x)
module function_definition identifier parameters identifier block expression_statement assignment tuple_pattern identifier identifier attribute identifier identifier return_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end att...
return relative path of tile image
def build_url_base(host, port, is_https): base = "http" if is_https: base += 's' base += "://" base += host if port: base += ":" base += str(port) return base
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier string string_start string_content string_end if_statement identifier block expression_statement augmented_assignment identifier string string_start string_content string_end expression_sta...
Make base of url based on config
def save_model(self, request, obj, form, change): if 'config.menu_structure' in form.changed_data: from menus.menu_pool import menu_pool menu_pool.clear(all=True) return super(BlogConfigAdmin, self).save_model(request, obj, form, change)
module function_definition identifier parameters identifier identifier identifier identifier identifier block if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block import_from_statement dotted_name identifier identifier dotted_name identifier expression_sta...
Clear menu cache when changing menu structure
def register_trading_control(self, control): if self.initialized: raise RegisterTradingControlPostInit() self.trading_controls.append(control)
module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block raise_statement call identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier
Register a new TradingControl to be checked prior to order calls.
def glob_by_extensions(directory, extensions): directorycheck(directory) files = [] xt = files.extend for ex in extensions: xt(glob.glob('{0}/*.{1}'.format(directory, ex))) return files
module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list identifier expression_statement assignment identifier list expression_statement assignment identifier attribute identifier identifier for_statement identifier identifier block expression_state...
Returns files matched by all extensions in the extensions list
def fetch_logins(roles, repo): users = set() if 'stargazer' in roles: printmp('Fetching stargazers') users |= set(repo.stargazers()) if 'collaborator' in roles: printmp('Fetching collaborators') users |= set(repo.collaborators()) if 'issue' in roles: printmp('Fetc...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list if_statement comparison_operator string string_start string_content string_end identifier block expression_statement call identifier argument_list string string_start str...
Fetch logins for users with given roles.
def dt_to_ts(value): if not isinstance(value, datetime): return value return calendar.timegm(value.utctimetuple()) + value.microsecond / 1000000.0
module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier identifier block return_statement identifier return_statement binary_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list binary_...
If value is a datetime, convert to timestamp
def tls_session_update(self, msg_str): super(SSLv2ServerHello, self).tls_session_update(msg_str) s = self.tls_session client_cs = s.sslv2_common_cs css = [cs for cs in client_cs if cs in self.ciphers] s.sslv2_common_cs = css s.sslv2_connection_id = self.connection_id ...
module function_definition identifier parameters identifier identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier a...
XXX Something should be done about the session ID here.
def columns_dataset(self): cache = self.cache cache_key = 'columns_dataset' if cache_key not in cache: columns_dataset = super(CachedModelVectorBuilder, self ).columns_dataset cache[cache_key] = columns_dataset self.cache = ...
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier string string_start string_content string_end if_statement comparison_operator identifier identifier block expression_statement assignme...
Implement high level cache system for columns and dataset.
def sign_in(self, email, password): self.email = email self.login_password = password if self.is_element_present(*self._next_button_locator): self.wait.until(expected.visibility_of_element_located( self._next_button_locator)) self.click_next() self...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier if_statement call attribute identifier identifier argument_list list_splat attribu...
Signs in using the specified email address and password.
def apply_saved_layout(self): num_widgets = self.config.get(self.config_key + "/num_widgets", int) if num_widgets: sizes = [] for i in range(num_widgets): key = "%s/size_%d" % (self.config_key, i) size = self.config.get(key, int) si...
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list binary_operator attribute identifier identifier string string_start string_content string_end identifier if_statement identifier block expr...
Call this after adding your child widgets.
def _get_port_profile_id(self, request): port_profile_id = request.path.split("/")[-1].strip() if uuidutils.is_uuid_like(port_profile_id): LOG.debug("The instance id was found in request path.") return port_profile_id LOG.debug("Failed to get the instance id from the requ...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute subscript call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end unary_operator integer identifier argument_list if_statem...
Get the port profile ID from the request path.
def execute(self, sql, params=None): with self.engine.begin() as conn: result = conn.execute(sql, params) return result
module function_definition identifier parameters identifier identifier default_parameter identifier none block with_statement with_clause with_item as_pattern call attribute attribute identifier identifier identifier argument_list as_pattern_target identifier block expression_statement assignment identifier call attrib...
Just a pointer to engine.execute
def _sort(self): self._log.debug('Sorting responses by priority') self._responses = OrderedDict(sorted(list(self._responses.items()), reverse=True)) self.sorted = True
module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier call identifier argument_list call identifier argum...
Sort the response dictionaries priority levels for ordered iteration
def relu(inplace:bool=False, leaky:float=None): "Return a relu activation, maybe `leaky` and `inplace`." return nn.LeakyReLU(inplace=inplace, negative_slope=leaky) if leaky is not None else nn.ReLU(inplace=inplace)
module function_definition identifier parameters typed_default_parameter identifier type identifier false typed_default_parameter identifier type identifier none block expression_statement string string_start string_content string_end return_statement conditional_expression call attribute identifier identifier argument...
Return a relu activation, maybe `leaky` and `inplace`.
def configure_discover(self, ns, definition): @self.add_route(ns.singleton_path, Operation.Discover, ns) def discover(): swagger = build_swagger(self.graph, ns, self.find_matching_endpoints(ns)) g.hide_body = True return make_response(swagger)
module function_definition identifier parameters identifier identifier identifier block decorated_definition decorator call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier identifier function_definition identifier parameters block expression_statement assign...
Register a swagger endpoint for a set of operations.
def rescaleX(self): self.ratio = self.figure.get_size_inches()[0]/float(self.figure.get_size_inches()[1]) self.axes.set_xlim(-self.ratio,self.ratio) self.axes.set_ylim(-1,1)
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier binary_operator subscript call attribute attribute identifier identifier identifier argument_list integer call identifier argument_list subscript call attribute attribute identifier identifi...
Rescales the horizontal axes to make the lengthscales equal.
def yaw(self): x, y, z, w = self.x, self.y, self.z, self.w return math.asin(2*x*y + 2*z*w)
module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier identifier expression_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier return_statement call...
Calculates the Yaw of the Quaternion.
def OnGetItemText(self, item, col): try: column = self.columns[col] value = column.get(self.sorted[item]) except IndexError, err: return None else: if value is None: return u'' if column.percentPossible and self.percenta...
module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list subscript attribute id...
Retrieve text for the item and column respectively
def col(self, col_name_or_num): if isinstance(col_name_or_num, basestring): return self[col_name_or_num] elif isinstance(col_name_or_num, (int, long)): if col_name_or_num > len(self.fields): raise IndexError("Invalid column index `%s` for DataTable" % ...
module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block return_statement subscript identifier identifier elif_clause call identifier argument_list identifier tuple identifier identifier block if_statement comparison_operator ide...
Returns the col at index `colnum` or name `colnum`.
def _format_report_line(self, test, time_taken, color, status, percent): return "[{0}] {3:04.2f}% {1}: {2}".format( status, test, self._colored_time(time_taken, color), percent )
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block return_statement call attribute string string_start string_content string_end identifier argument_list identifier identifier call attribute identifier identifier argument_list identifier identifier i...
Format a single report line.
def migrate_app(sender, *args, **kwargs): from .registration import registry if 'app_config' not in kwargs: return app_config = kwargs['app_config'] app_name = app_config.label fields = [fld for fld in list(registry._field_registry.keys()) if fld.startswith(app_name)] sid = transaction.s...
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier if_statement comparison_operator string string_start string_content string_end identifier ...
Migrate all models of this app registered
def validate_bool_kwarg(value, arg_name): if not (is_bool(value) or value is None): raise ValueError('For argument "{arg}" expected type bool, received ' 'type {typ}.'.format(arg=arg_name, typ=type(value).__name__)) return value
module function_definition identifier parameters identifier identifier block if_statement not_operator parenthesized_expression boolean_operator call identifier argument_list identifier comparison_operator identifier none block raise_statement call identifier argument_list call attribute concatenated_string string stri...
Ensures that argument passed in arg_name is of type bool.
def parse_string_expr(self, string_expr_node): string_expr_node_value = string_expr_node['value'] string_expr_str = string_expr_node_value[1:-1] if string_expr_node_value[0] == "'": string_expr_str = string_expr_str.replace("''", "'") else: string_expr_str = strin...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier slice integer unary_operator integer if_statement comparison_operator...
Parse a string node content.
def text(files): sentences = convert_timestamps(files) out = [] for s in sentences: out.append(' '.join([w[0] for w in s['words']])) return '\n'.join(out)
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call att...
Returns the whole transcribed text
def _parseElfHeader(self, data): ehdr = self.__classes.EHDR.from_buffer(data) return EhdrData(header=ehdr)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier return_statement call identifier argument_list keyword_argument identifier identifier
Returns the elf header
def encode_example(self, video_or_path_or_fobj): if isinstance(video_or_path_or_fobj, six.string_types): if not os.path.isfile(video_or_path_or_fobj): _, video_temp_path = tempfile.mkstemp() try: tf.gfile.Copy(video_or_path_or_fobj, video_temp_path, overwrite=True) encoded_...
module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier attribute identifier identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment patt...
Converts the given image into a dict convertible to tf example.
def shorten_go_name_ptbl1(self, name): if self._keep_this(name): return name name = name.replace("negative", "neg.") name = name.replace("positive", "pos.") name = name.replace("response", "rsp.") name = name.replace("regulation", "reg.") name = name.replace("...
module function_definition identifier parameters identifier identifier block if_statement call attribute identifier identifier argument_list identifier block return_statement identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content strin...
Shorten GO name for tables in paper.
def printJobChildren(self): for job in self.jobsToReport: children = "CHILDREN_OF_JOB:%s " % job for level, jobList in enumerate(job.stack): for childJob in jobList: children += "\t(CHILD_JOB:%s,PRECEDENCE:%i)" % (childJob, level) print(chi...
module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier for_statement pattern_list identifier identifier call identifier argument_l...
Takes a list of jobs, and prints their successors.
def add_task(self, task, func=None, **kwargs): if not self.__tasks: raise Exception("Tasks subparsers is disabled") if 'help' not in kwargs: if func.__doc__: kwargs['help'] = func.__doc__ task_parser = self.__tasks.add_parser(task, **kwargs) if sel...
module function_definition identifier parameters identifier identifier default_parameter identifier none dictionary_splat_pattern identifier block if_statement not_operator attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement comp...
Add a task parser
def _draw_ap_score(self, score, label=None): label = label or "Avg Precision={:0.2f}".format(score) if self.ap_score: self.ax.axhline( y=score, color="r", ls="--", label=label )
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier call attribute string string_start string_content string_end identifier argument_list identifier if_statement attribute identifier identif...
Helper function to draw the AP score annotation
def index_complement(index_list, len_=None): mask1 = index_to_boolmask(index_list, len_) mask2 = not_list(mask1) index_list_bar = list_where(mask2) return index_list_bar
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifie...
Returns the other indicies in a list of length ``len_``
def getFlaskResponse(responseString, httpStatus=200): return flask.Response(responseString, status=httpStatus, mimetype=MIMETYPE)
module function_definition identifier parameters identifier default_parameter identifier integer block return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier
Returns a Flask response object for the specified data and HTTP status.
def point_stokes(self, context): stokes = np.empty(context.shape, context.dtype) stokes[:,:,0] = 1 stokes[:,:,1:4] = 0 return stokes
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment subscript identifier slice slice integer integer expr...
Return a stokes parameter array to montblanc
def make_blastdb(self): db = os.path.splitext(self.formattedprimers)[0] nhr = '{db}.nhr'.format(db=db) if not os.path.isfile(str(nhr)): command = 'makeblastdb -in {primerfile} -parse_seqids -max_file_sz 2GB -dbtype nucl -out {outfile}'\ .format(primerfile=self.formatt...
module function_definition identifier parameters identifier block expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list attribute identifier identifier integer expression_statement assignment identifier call attribute string string_start string_cont...
Create a BLAST database of the primer file
def calc_temperature_stats(self): self.temp.max_delta = melodist.get_shift_by_data(self.data.temp, self._lon, self._lat, self._timezone) self.temp.mean_course = melodist.util.calculate_mean_daily_course_by_month(self.data.temp, normalize=True)
module function_definition identifier parameters identifier block expression_statement assignment attribute attribute identifier identifier identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier attribute identifier identifier attribute identifier identifier a...
Calculates statistics in order to derive diurnal patterns of temperature
def __get_file_path(self, path, saltenv='base'): try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ...
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause as_pattern identifier as_patt...
Return either a file path or the result of a remote find_file call.
def _filter(self, criteria: Q, db): negated = criteria.negated input_db = None if criteria.connector == criteria.AND: input_db = db for child in criteria.children: if isinstance(child, Q): input_db = self._filter(child, input_db) ...
module function_definition identifier parameters identifier typed_parameter identifier type identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier none if_statement comparison_operator attribute identifier identifier attribute id...
Recursive function to filter items from dictionary
async def close_authenticator_async(self): _logger.info("Shutting down CBS session on connection: %r.", self._connection.container_id) try: self._cbs_auth.destroy() _logger.info("Auth closed, destroying session on connection: %r.", self._connection.container_id) await...
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute attribute identifier identifier identifier try_statement block expression_statement call attribute attribute identifier identi...
Close the CBS auth channel and session asynchronously.
def register_callback(self): cid = str(self.__cid) self.__cid += 1 event = queue.Queue() self.__callbacks[cid] = event return cid, event
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement augmented_assignment attribute identifier identifier integer expression_statement assignment identifier call attribute identifie...
Register callback that we will have to wait for
def process_bucket_inventory(bid, inventory_bucket, inventory_prefix): log.info("Loading bucket %s keys from inventory s3://%s/%s", bid, inventory_bucket, inventory_prefix) account, bucket = bid.split(':', 1) region = connection.hget('bucket-regions', bid) versioned = bool(int(connection.hg...
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier identifier expression_statement assignment pattern_list identifier identifier call attribute...
Load last inventory dump and feed as key source.
def make_dir(project): project_path = os.path.join(os.path.dirname(__file__), project) if os.path.exists(project_path): shutil.rmtree(project_path) os.mkdir(project_path) with open(os.path.join(project_path, '__init__.py'), 'w') as fp: fp.write('__version__ = "' + str(get_property('__ver...
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement call attribute attribute identif...
Creates the project directory for compiled modules.