code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def create_shn (archive, compression, cmd, verbosity, interactive, filenames): if len(filenames) > 1: raise util.PatoolError("multiple filenames for shorten not supported") cmdlist = [util.shell_quote(cmd)] cmdlist.extend(['-', util.shell_quote(archive), '<', util.shell_quote(filenames[0])])...
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block if_statement comparison_operator call identifier argument_list identifier integer block raise_statement call attribute identifier identifier argument_list string string_start string_content string_en...
Compress a WAV file to a SHN archive.
def shutdown(self, service_thread_map): with self._services.lifecycle_lock: for service, service_thread in service_thread_map.items(): self._logger.info('terminating pantsd service: {}'.format(service)) service.terminate() service_thread.join(self.JOIN_TIMEOUT_SECONDS) self._logg...
module function_definition identifier parameters identifier identifier block with_statement with_clause with_item attribute attribute identifier identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement call attribute attri...
Gracefully terminate all services and kill the main PantsDaemon loop.
def rename_key(pki_dir, id_, new_id): oldkey = os.path.join(pki_dir, 'minions', id_) newkey = os.path.join(pki_dir, 'minions', new_id) if os.path.isfile(oldkey): os.rename(oldkey, newkey)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end identifier expression_statement assignment identifier call a...
Rename a key, when an instance has also been renamed
def search_people_by_bio(query, limit_results=DEFAULT_LIMIT, index=['onename_people_index']): from pyes import QueryStringQuery, ES conn = ES() q = QueryStringQuery(query, search_fields=['username', 'profile_bio'], default_operator='...
module function_definition identifier parameters identifier default_parameter identifier identifier default_parameter identifier list string string_start string_content string_end block import_from_statement dotted_name identifier dotted_name identifier dotted_name identifier expression_statement assignment identifier ...
queries lucene index to find a nearest match, output is profile username
def mount(self, url, app): "Mount a sub-app at the url of current app." app.url = url self.mounts.append(app)
module function_definition identifier parameters identifier identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_li...
Mount a sub-app at the url of current app.
def create_topic(self, topic_name, topic_config): topic_subs = [] t = self.template if "Subscription" in topic_config: topic_subs = topic_config["Subscription"] t.add_resource( sns.Topic.from_dict( topic_name, topic_config ...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier list expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_st...
Creates the SNS topic, along with any subscriptions requested.
def global_get(self, key): key = self.pack(key) r = self.sql('global_get', key).fetchone() if r is None: raise KeyError("Not set") return self.unpack(r[0])
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_co...
Return the value for the given key in the ``globals`` table.
def encode_token(self, token): key = current_app.secret_key if key is None: raise RuntimeError( "please set app.secret_key before generate token") return jwt.encode(token, key, algorithm=self.config["algorithm"])
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block raise_statement call identifier argument_list string string_start string_content string_end return_statement call...
Encode Authorization token, return bytes token
def directory(self): if self._directory is None: self._directory = self.api._load_directory(self.cid) return self._directory
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier return_sta...
Directory that holds this file
def format_vk(vk): for ext in get_extensions_filtered(vk): req = ext['require'] if not isinstance(req, list): ext['require'] = [req]
module function_definition identifier parameters identifier block for_statement identifier call identifier argument_list identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement not_operator call identifier argument_list identifier ident...
Format vk before using it
def deploy(remote, assets_to_s3): header("Deploying...") if assets_to_s3: for mod in get_deploy_assets2s3_list(CWD): _assets2s3(mod) remote_name = remote or "ALL" print("Pushing application's content to remote: %s " % remote_name) hosts = get_deploy_hosts_list(CWD, remote or None...
module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end if_statement identifier block for_statement identifier call identifier argument_list identifier block expression_statement call identifier argumen...
To DEPLOY your application
def align(self,inputwords, outputwords): alignment = [] cursor = 0 for inputword in inputwords: if len(outputwords) > cursor and outputwords[cursor] == inputword: alignment.append(cursor) cursor += 1 elif len(outputwords) > cursor+1 and out...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier list expression_statement assignment identifier integer for_statement identifier identifier block if_statement boolean_operator comparison_operator call identifier argument_list identifier ...
For each inputword, provides the index of the outputword
def _persisted_last_epoch(self) -> int: epoch_number = 0 self._make_sure_dir_exists() for x in os.listdir(self.model_config.checkpoint_dir()): match = re.match('checkpoint_(\\d+)\\.data', x) if match: idx = int(match[1]) if idx > epoch_numb...
module function_definition identifier parameters identifier type identifier block expression_statement assignment identifier integer expression_statement call attribute identifier identifier argument_list for_statement identifier call attribute identifier identifier argument_list call attribute attribute identifier ide...
Return number of last epoch already calculated
def setup(app): app.connect("builder-inited", build_configuration_parameters) app.connect("autodoc-skip-member", skip_slots) app.add_stylesheet("css/custom.css")
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identif...
Map methods to states of the documentation build.
def save_hdf(self, filename, path='', overwrite=False): if os.path.exists(filename) and overwrite: os.remove(filename) for pop in self.poplist: name = pop.modelshort pop.save_hdf(filename, path='{}/{}'.format(path,name), append=True)
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_end default_parameter identifier false block if_statement boolean_operator call attribute attribute identifier identifier identifier argument_list identifier identifier block expression_stateme...
Saves PopulationSet to HDF file.
def render_flatpage(request, f): if f.registration_required and not request.user.is_authenticated(): from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) if f.template_name: t = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else...
module function_definition identifier parameters identifier identifier block if_statement boolean_operator attribute identifier identifier not_operator call attribute attribute identifier identifier identifier argument_list block import_from_statement dotted_name identifier identifier identifier identifier dotted_name ...
Internal interface to the flat page view.
def addAnnotationsSearchOptions(parser): addAnnotationSetIdArgument(parser) addReferenceNameArgument(parser) addReferenceIdArgument(parser) addStartArgument(parser) addEndArgument(parser) addEffectsArgument(parser) addPageSizeArgument(parser)
module function_definition identifier parameters identifier block expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier expres...
Adds common options to a annotation searches command line parser.
def step_an_empty_file_named_filename(context, filename): assert not os.path.isabs(filename) command_util.ensure_workdir_exists(context) filename2 = os.path.join(context.workdir, filename) pathutil.create_textfile_with_contents(filename2, "")
module function_definition identifier parameters identifier identifier block assert_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call...
Creates an empty file.
def open_dataset(self, service): if not self.dataset: path = os.path.join(SERVICE_DATA_ROOT, service.data_path) self.dataset = netCDF4.Dataset(path, 'r') return self.dataset
module function_definition identifier parameters identifier identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier expression_statement ...
Opens and returns the NetCDF dataset associated with a service, or returns a previously-opened dataset
def create_exclude_rules(args): global _cached_exclude_rules if _cached_exclude_rules is not None: return _cached_exclude_rules rules = [] for excl_path in args.exclude: abspath = os.path.abspath(os.path.join(args.root, excl_path)) rules.append((abspath, True)) for incl_path ...
module function_definition identifier parameters identifier block global_statement identifier if_statement comparison_operator identifier none block return_statement identifier expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_statement assignment ...
Creates the exlude rules
def getTextTitle(self): request_id = self.getRequestID() if not request_id: return "" analysis = self.getAnalysis() if not analysis: return request_id return "%s - %s" % (request_id, analysis.Title())
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator identifier block return_statement string string_start string_end expression_statement assignment identifier call attribute identifier ...
Return a title for texts and listings
def draw_variables(self): z = self.q[0].draw_variable_local(self.sims) for i in range(1,len(self.q)): z = np.vstack((z,self.q[i].draw_variable_local(self.sims))) return z
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute subscript attribute identifier identifier integer identifier argument_list attribute identifier identifier for_statement identifier call identifier argument_list integer call identifier argument_l...
Draw parameters from the approximating distributions
def ReadAllFlowRequestsAndResponses(self, client_id, flow_id): flow_key = (client_id, flow_id) try: self.flows[flow_key] except KeyError: return [] request_dict = self.flow_requests.get(flow_key, {}) response_dict = self.flow_responses.get(flow_key, {}) res = [] for request_id in...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier tuple identifier identifier try_statement block expression_statement subscript attribute identifier identifier identifier except_clause identifier block return_statement list expression_sta...
Reads all requests and responses for a given flow from the database.
def repo(name: str, owner: str) -> snug.Query[dict]: request = snug.GET(f'https://api.github.com/repos/{owner}/{name}') response = yield request return json.loads(response.content)
module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type subscript attribute identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_...
a repo lookup by owner and name
def save_sequence_rule(self, sequence_rule_form, *args, **kwargs): if sequence_rule_form.is_for_update(): return self.update_sequence_rule(sequence_rule_form, *args, **kwargs) else: return self.create_sequence_rule(sequence_rule_form, *args, **kwargs)
module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement call attribute identifier identifier argument_list block return_statement call attribute identifier identifier argument_list identifier list_splat identifier dictio...
Pass through to provider SequenceRuleAdminSession.update_sequence_rule
def _event(self, event): result = dict( pid=event.device_id, tid=event.resource_id, name=event.name, ts=event.timestamp_ps / 1000000.0) if event.duration_ps: result['ph'] = _TYPE_COMPLETE result['dur'] = event.duration_ps / 1000000.0 else: result['ph'] = _TY...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier i...
Converts a TraceEvent proto into a catapult trace event python value.
def cfnumber_to_number(cfnumber): numeric_type = cf.CFNumberGetType(cfnumber) cfnum_to_ctype = {kCFNumberSInt8Type: c_int8, kCFNumberSInt16Type: c_int16, kCFNumberSInt32Type: c_int32, kCFNumberSInt64Type: c_int64, kCFNumberFloat32Type: c_float, ...
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier dictionary pair identifier identifier pair identifier identifier pair identifier identifier pair identifie...
Convert CFNumber to python int or float.
def run(self): self.info_log("The test batch is ready.") self.executed_tests = [] for test in self.tests: localhost_instance = LocalhostInstance( runner=self, browser_config=self.browser_config, test_name=test.Test.name ) ...
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier list for_statement identifier attribute identifier identifier block expr...
Run the test batch
def returns_json(func): def decorator(*args, **kwargs): instance = args[0] request = getattr(instance, 'request', None) request.response.setHeader("Content-Type", "application/json") result = func(*args, **kwargs) return json.dumps(result) return decorator
module function_definition identifier parameters identifier block function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier call identifier argument_...
Decorator for functions which return JSON
def _reset_i(self, i): self.count[i].value=0 log.debug("reset counter %s", i) self.lock[i].acquire() for x in range(self.q[i].qsize()): self.q[i].get() self.lock[i].release() self.start_time[i].value = time.time()
module function_definition identifier parameters identifier identifier block expression_statement assignment attribute subscript attribute identifier identifier identifier identifier integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier ...
reset i-th progress information
def collect_github_config(): github_config = {} for field in ["user", "token"]: try: github_config[field] = subprocess.check_output(["git", "config", "github.{}".format(field)]).decode('utf-8').strip() except (OSError, subprocess.CalledProcessError): pass return github_config
module function_definition identifier parameters block expression_statement assignment identifier dictionary for_statement identifier list string string_start string_content string_end string string_start string_content string_end block try_statement block expression_statement assignment subscript identifier identifier...
Try load Github configuration such as usernames from the local or global git config
def create_groups(orientations, *groups, **kwargs): grouped = [] if kwargs.pop('copy', True): orientations = [copy(o) for o in orientations] for o in orientations: o.member_of = None try: grouped += o.members for a in o.members: a.member_of = o...
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier list if_statement call attribute identifier identifier argument_list string string_start string_content string_end true block expression_statemen...
Create groups of an orientation measurement dataset
def _no_mute_on_stop_playback(self): if self.ctrl_c_pressed: return if self.isPlaying(): if self.actual_volume == -1: self._get_volume() while self.actual_volume == -1: pass if self.actual_volume == 0: ...
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement if_statement call attribute identifier identifier argument_list block if_statement comparison_operator attribute identifier identifier unary_operator integer block expression_statement c...
make sure vlc does not stop muted
def _convert_listlike(arg, unit='ns', box=True, errors='raise', name=None): if isinstance(arg, (list, tuple)) or not hasattr(arg, 'dtype'): arg = np.array(list(arg), dtype=object) try: value = sequence_to_td64ns(arg, unit=unit, errors=errors, copy=False)[0] ...
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier true default_parameter identifier string string_start string_content string_end default_parameter identifier none block if_statement boolean_operator call i...
Convert a list of objects to a timedelta index object.
def _get_subparser_cell_args(self, subparser_prog): subparsers = self._get_subparsers() for subparser in subparsers: if subparser_prog == subparser.prog: return subparser._cell_args return None
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block return_statement attribut...
Get cell args of a specified subparser by its prog.
def __connect(): global redis_instance if use_tcp_socket: redis_instance = redis.StrictRedis(host=hostname, port=port) else: redis_instance = redis.StrictRedis(unix_socket_path=unix_socket)
module function_definition identifier parameters block global_statement identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier else_clause block expression_statem...
Connect to a redis instance.
def generate_seed(seed): if seed is None: random.seed() seed = random.randint(0, sys.maxsize) random.seed(a=seed) return seed
module function_definition identifier parameters identifier block if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list integer attribute identifier iden...
Generate seed for random number generator
def _stop_cpulimit(self): if self._cpulimit_process and self._cpulimit_process.returncode is None: self._cpulimit_process.kill() try: self._process.wait(3) except subprocess.TimeoutExpired: log.error("Could not kill cpulimit process {}".format(...
module function_definition identifier parameters identifier block if_statement boolean_operator attribute identifier identifier comparison_operator attribute attribute identifier identifier identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list try_statement b...
Stops the cpulimit process.
def fail(p_queue, host=None): if host is not None: return _path(_c.FSQ_FAIL, root=_path(host, root=hosts(p_queue))) return _path(p_queue, _c.FSQ_FAIL)
module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block return_statement call identifier argument_list attribute identifier identifier keyword_argument identifier call identifier argument_list identifier keyword_argument ...
Construct a path to the fail dir for a queue
def internal2external(xi, bounds): xe = np.empty_like(xi) for i, (v, bound) in enumerate(zip(xi, bounds)): a = bound[0] b = bound[1] if a == None and b == None: xe[i] = v elif b == None: xe[i] = a - 1. + np.sqrt(v ** 2. + 1.) elif a == None: ...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement pattern_list identifier tuple_pattern identifier identifier call identifier argument_list call identifier argument_list iden...
Convert a series of internal variables to external variables
def log_request(self, code="-", size="-"): self._service.log(logging.DEBUG, '"%s" %s', self.requestline, code)
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list attribute i...
Logs a request to the server
def _results(self, connection, msgid): try: kind, results = connection.result(msgid) if kind != ldap.RES_SEARCH_RESULT: results = [] except ldap.LDAPError as e: results = [] logger.error(u"result(%d) raised %s" % (msgid, pprint.pformat(e)))...
module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier attribute identifier identifier block e...
Returns the result of a previous asynchronous query.
def load(self): try: merged_configfile = self.get_merged_config() self.yamldocs = yaml.load(merged_configfile, Loader=Loader) self.yamldocs = [x for x in self.yamldocs if x] self.logdebug('parsed_rules:\n%s\n' % pretty(self.yamldocs)) except (yaml.scanner....
module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier keyword_argume...
Load our config, log and raise on error.
def makeicons(source): im = Image.open(source) for name, (_, w, h, func) in icon_sizes.iteritems(): print('Making icon %s...' % name) tn = func(im, (w, h)) bg = Image.new('RGBA', (w, h), (255, 255, 255)) x = (w / 2) - (tn.size[0] / 2) y = (h / 2) - (tn.size[1] / 2) ...
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement pattern_list identifier tuple_pattern identifier identifier identifier identifier call attribute identifier identifier argument_list bl...
Create all the neccessary icons from source image
def _format_lat(self, lat): if self.ppd in [4, 16, 64, 128]: return None else: if lat < 0: return map(lambda x: "{0:0>2}" .format(int(np.abs(x))) + 'S', self._map_center('lat', lat)) else: return map(lambda x:...
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 if_statement comparison_operator identifier integer block return_statement call identifier argu...
Returned a formated latitude format for the file
async def _cancel_payloads(self): for task in self._tasks: task.cancel() await asyncio.sleep(0) for task in self._tasks: while not task.done(): await asyncio.sleep(0.1) task.cancel()
module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement await call attribute identifier identifier argument_list integer for_statement identifier attribut...
Cancel all remaining payloads
def format(self, record): data = record.__dict__.copy() data['data_id'] = DATA['id'] data['data_location_id'] = DATA_LOCATION['id'] data['hostname'] = socket.gethostname() data['pathname'] = os.path.relpath(data['pathname'], os.path.dirname(__file__)) data['exc_info'] = N...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string s...
Dump the record to JSON.
def clear(self): self.command(c.LCD_CLEARDISPLAY) self._cursor_pos = (0, 0) self._content = [[0x20] * self.lcd.cols for _ in range(self.lcd.rows)] c.msleep(2)
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier tuple integer integer expression_statement assignment attribute identifier identifier ...
Overwrite display with blank characters and reset cursor position.
def _merge_list_fastqs(files, out_file, config): if not all(map(fastq.is_fastq, files)): raise ValueError("Not all of the files to merge are fastq files: %s " % (files)) assert all(map(utils.file_exists, files)), ("Not all of the files to merge " "exist: %...
module function_definition identifier parameters identifier identifier identifier block if_statement not_operator call identifier argument_list call identifier argument_list attribute identifier identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content ...
merge list of fastq files into one
def _log_request(request): logger.debug("Inbound email received") for k, v in list(request.POST.items()): logger.debug("- POST['%s']='%s'" % (k, v)) for n, f in list(request.FILES.items()): logger.debug("- FILES['%s']: '%s', %sB", n, f.content_type, f.size)
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end for_statement pattern_list identifier identifier call identifier argument_list call attribute attribute identifier identifier identifier...
Helper function to dump out debug info.
def merge(self, n): if os.path.isfile(n[:-4]): old = Utils().read_file(n[:-4]).splitlines() if os.path.isfile(n): new = Utils().read_file(n).splitlines() with open(n[:-4], "w") as out: for l1, l2 in itertools.izip_longest(old, new): if l1 is No...
module function_definition identifier parameters identifier identifier block if_statement call attribute attribute identifier identifier identifier argument_list subscript identifier slice unary_operator integer block expression_statement assignment identifier call attribute call attribute call identifier argument_list...
Merge new file into old
def wrtxt_hier(self, fout_txt): with open(fout_txt, 'wb') as prt: self.prt_hier(prt) print(" WROTE: {TXT}".format(TXT=fout_txt))
module function_definition identifier parameters identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list i...
Write hierarchy below specfied GO IDs to an ASCII file.
def log_prior(self): for p, b in zip(self.parameter_vector, self.parameter_bounds): if b[0] is not None and p < b[0]: return -np.inf if b[1] is not None and p > b[1]: return -np.inf return 0.0
module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier attribute identifier identifier block if_statement boolean_operator comparison_operator subscript identifier integer none comparison_operator i...
Compute the log prior probability of the current parameters
def element(self): element = self.keywords["VRHFIN"].split(":")[0].strip() try: return Element(element).symbol except ValueError: if element == "X": return "Xe" return Element(self.symbol.split("_")[0]).symbol
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute subscript call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end integer iden...
Attempt to return the atomic symbol based on the VRHFIN keyword.
def register_plugin_module(mod): for k, v in load_plugins_from_module(mod).items(): if k: if isinstance(k, (list, tuple)): k = k[0] global_registry[k] = v
module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call attribute call identifier argument_list identifier identifier argument_list block if_statement identifier block if_statement call identifier argument_list identifier tuple identifier identifier block ...
Find plugins in given module
def center_origin(self): self.set_origin(Vector2(self.image.get_width() / 2.0, self.image.get_height() / 2.0))
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list binary_operator call attribute attribute identifier identifier identifier argument_list float binary_operator call attribute attribute identifier identi...
Sets the origin to the center of the image.
def assign_tip_labels_and_colors(self): "assign tip labels based on user provided kwargs" if self.style.tip_labels_colors: if self.ttree._fixed_order: if isinstance(self.style.tip_labels_colors, (list, np.ndarray)): col...
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement attribute attribute identifier identifier identifier block if_statement attribute attribute identifier identifier identifier block if_statement call identifier argument_list ...
assign tip labels based on user provided kwargs
def update_firewall_rule(self, firewall_rule, body=None): return self.put(self.firewall_rule_path % (firewall_rule), body=body)
module function_definition identifier parameters identifier identifier default_parameter identifier none block return_statement call attribute identifier identifier argument_list binary_operator attribute identifier identifier parenthesized_expression identifier keyword_argument identifier identifier
Updates a firewall rule.
def register(self): group = cfg.OptGroup( self.group_name, title="HNV (Hyper-V Network Virtualization) Options") self._config.register_group(group) self._config.register_opts(self._options, group=group)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement call attribute attribute identifi...
Register the current options to the global ConfigOpts object.
def combine_keys(pks: Iterable[Ed25519PublicPoint]) -> Ed25519PublicPoint: P = [_ed25519.decodepoint(pk) for pk in pks] combine = reduce(_ed25519.edwards_add, P) return Ed25519PublicPoint(_ed25519.encodepoint(combine))
module function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier block expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier identifier ex...
Combine a list of Ed25519 points into a "global" CoSi key.
def _expand_data(self, old_data, new_data, group): for file in old_data: if file: extension = file.split(".")[-1].lower() if extension in self.file_types.keys(): new_data['groups'][group].append(self._expand_one_file(normpath(file), ...
module function_definition identifier parameters identifier identifier identifier identifier block for_statement identifier identifier block if_statement identifier block expression_statement assignment identifier call attribute subscript call attribute identifier identifier argument_list string string_start string_con...
data expansion - uvision needs filename and path separately.
def var(self): if self._var is None: self._var = symbol.var(self.name, shape=self.shape, dtype=self.dtype, lr_mult=self.lr_mult, wd_mult=self.wd_mult, init=self.init, stype=self._stype) return self._var
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier att...
Returns a symbol representing this parameter.
def geom_wh(geom): e = geom.GetEnvelope() h = e[1] - e[0] w = e[3] - e[2] return w, h
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator subscript identifier integer subscript identifier integer expression_statement assignment identifier ...
Compute width and height of geometry in projected units
def search_mosaics(name, bbox, rbox, limit, pretty): bbox = bbox or rbox cl = clientv1() mosaic, = cl.get_mosaic_by_name(name).items_iter(1) response = call_and_wrap(cl.get_quads, mosaic, bbox) echo_json_response(response, pretty, limit)
module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier boolean_operator identifier identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment pattern_list identifier...
Get quad IDs and information for a mosaic
def _create_fw(self, tenant_id, data): LOG.debug("In creating Native FW data is %s", data) ret, in_sub, out_sub = self.attach_intf_router(tenant_id, data.get('tenant_name'), data.get('router_id'...
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 expression_statement assignment pattern_list identifier identifier identifier call attribute identifier...
Internal routine that gets called when a FW is created.
def update_rating(self, postid): post_data = self.get_post_data() rating = float(post_data['rating']) postinfo = MPost.get_by_uid(postid) if postinfo and self.userinfo: MRating.update(postinfo.uid, self.userinfo.uid, rating=rating) self.update_post(postid) ...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list subscript identifier string string_start string_content string_end expressio...
only the used who logged in would voting.
def inner(self, isolated=False): if isolated: return Frame(self.eval_ctx, level=self.symbols.level + 1) return Frame(self.eval_ctx, self)
module function_definition identifier parameters identifier default_parameter identifier false block if_statement identifier block return_statement call identifier argument_list attribute identifier identifier keyword_argument identifier binary_operator attribute attribute identifier identifier identifier integer retur...
Return an inner frame.
def client_list(self, *args): if len(self._clients) == 0: self.log('No clients connected') else: self.log(self._clients, pretty=True)
module function_definition identifier parameters identifier list_splat_pattern identifier block if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement call attribute identifier identifier argument_list string string_start string_content string_e...
Display a list of connected clients
def _maybe_dt_array(array): if not isinstance(array, DataTable) or array is None: return array if array.shape[1] > 1: raise ValueError('DataTable for label or weight cannot have multiple columns') array = array.to_numpy()[:, 0].astype('float') return array
module function_definition identifier parameters identifier block if_statement boolean_operator not_operator call identifier argument_list identifier identifier comparison_operator identifier none block return_statement identifier if_statement comparison_operator subscript attribute identifier identifier integer intege...
Extract numpy array from single column data table
def route_request(self, request_json, metadata=None): request = Request(request_json) request.metadata = metadata handler_fn = self._handlers[self._default] if not request.is_intent() and (request.request_type() in self._handlers): handler_fn = self._handlers[request.request_...
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment identifier subscri...
Route the request object to the right handler function
def tensor_size_guidance_from_flags(flags): tensor_size_guidance = dict(DEFAULT_TENSOR_SIZE_GUIDANCE) if not flags or not flags.samples_per_plugin: return tensor_size_guidance for token in flags.samples_per_plugin.split(','): k, v = token.strip().split('=') tensor_size_guidance[k] = int(v) return te...
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement boolean_operator not_operator identifier not_operator attribute identifier identifier block return_statement identifier for_statement identifier call attribu...
Apply user per-summary size guidance overrides.
def sdk_version(self): if self.__sdk == 0: try: self.__sdk = int(self.adb.cmd("shell", "getprop", "ro.build.version.sdk").communicate()[0].decode("utf-8").strip()) except: pass return self.__sdk
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier integer block try_statement block expression_statement assignment attribute identifier identifier call identifier argument_list call attribute call attribute subscript call attribute call a...
sdk version of connected device.
def split_bel_stmt(stmt: str, line_num) -> tuple: m = re.match(f"^(.*?\))\s+([a-zA-Z=\->\|:]+)\s+([\w(]+.*?)$", stmt, flags=0) if m: return (m.group(1), m.group(2), m.group(3)) else: log.info( f"Could not parse bel statement into components at line number: {line_num} assertion: {...
module function_definition identifier parameters typed_parameter identifier type identifier identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier keyword_argument identifier integer if_state...
Split bel statement into subject, relation, object tuple
def render(self): context = self.context if 'app' not in context: context['app'] = self.application.name temp_dir = self.temp_dir templates_root = self.blueprint.templates_directory for root, dirs, files in os.walk(templates_root): for directory in dirs: ...
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_con...
Render the blueprint into a temp directory using the context.
def list_corpus_files(dotted_path): corpus_path = get_file_path(dotted_path, extension=CORPUS_EXTENSION) paths = [] if os.path.isdir(corpus_path): paths = glob.glob(corpus_path + '/**/*.' + CORPUS_EXTENSION, recursive=True) else: paths.append(corpus_path) paths.sort() return path...
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier list if_statement call attribute attribute identifier identifier identifier argument_lis...
Return a list of file paths to each data file in the specified corpus.
def hilbert(ts): output = signal.hilbert(signal.detrend(ts, axis=0), axis=0) return Timeseries(output, ts.tspan, labels=ts.labels)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier integer keyword_argument identifier integer return_statement call iden...
Analytic signal, using the Hilbert transform
def compare_md5(self): if self.direction == "put": remote_md5 = self.remote_md5() return self.source_md5 == remote_md5 elif self.direction == "get": local_md5 = self.file_md5(self.dest_file) return self.source_md5 == local_md5
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement comparison_operator attrib...
Compare md5 of file on network device to md5 of local file.
def find_all(self, prefix): prefix = ip_network(prefix) if not self.prefix.overlaps(prefix) \ or self.prefix[0] > prefix[0] \ or self.prefix[-1] < prefix[-1]: raise NotAuthoritativeError('This node is not authoritative for %r' % prefix)...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement boolean_operator boolean_operator not_operator call attribute attribute identifier identifier identifier argument_list identifier line_continuatio...
Find everything in the given prefix
def list_items(queue): itemstuple = _list_items(queue) items = [item[0] for item in itemstuple] return items
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier list_comprehension subscript identifier integer for_in_clause identifier identifier return_statement identifier
List contents of a queue
def validate(options): try: if options.backends.index('modelinstance') > options.backends.index('model'): raise Exception("Metadata backend 'modelinstance' must come before 'model' backend") except ValueError: raise Exception("Metadata backend 'modelinstance' must...
module function_definition identifier parameters identifier block try_statement block if_statement comparison_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string stri...
Validates the application of this backend to a given metadata
def create(self, data, **kwargs): self.client.post(self.url, data=data)
module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier
Create classifitions for specific entity
def baseclass(self): for cls in _BASE_CLASSES: if isinstance(self, cls): return cls raise ValueError("Cannot determine the base class of %s" % self.__class__.__name__)
module function_definition identifier parameters identifier block for_statement identifier identifier block if_statement call identifier argument_list identifier identifier block return_statement identifier raise_statement call identifier argument_list binary_operator string string_start string_content string_end attri...
The baseclass of self.
def _find_vm(name, data, quiet=False): for hv_ in data: if not isinstance(data[hv_], dict): continue if name in data[hv_].get('vm_info', {}): ret = {hv_: {name: data[hv_]['vm_info'][name]}} if not quiet: __jid_event__.fire_event({'data': ret, 'outp...
module function_definition identifier parameters identifier identifier default_parameter identifier false block for_statement identifier identifier block if_statement not_operator call identifier argument_list subscript identifier identifier identifier block continue_statement if_statement comparison_operator identifie...
Scan the query data for the named VM
def filter_data(data, filter_dict): for key, match_string in filter_dict.items(): if key not in data: logger.warning("{0} doesn't match a top level key".format(key)) continue values = data[key] matcher = re.compile(match_string) if isinstance(values, list): ...
module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list call...
filter a data dictionary for values only matching the filter
def _truncate(self, x, k): not_F = np.argsort(np.abs(x))[:-k] x[not_F] = 0 return x
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier slice unary_operator identifier expression_statement assignment su...
given a vector x, leave its top-k absolute-value entries alone, and set the rest to 0
def imagej_metadata(self): if not self.is_imagej: return None page = self.pages[0] result = imagej_description_metadata(page.is_imagej) if 'IJMetadata' in page.tags: try: result.update(page.tags['IJMetadata'].value) except Exception: ...
module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block return_statement none expression_statement assignment identifier subscript attribute identifier identifier integer expression_statement assignment identifier call identifier argument_list at...
Return consolidated ImageJ metadata as dict.
def notifications(self): self.__init() items = [] for n in self._notifications: if "id" in n: url = "%s/%s" % (self.root, n['id']) items.append(self.Notification(url=url, securityHandler=self._securityHand...
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier list for_statement identifier attribute identifier identifier block if_statement comparison_operator string string_start string_content str...
gets the user's notifications
def draw(self, surfaceObj): if self._visible: if self.buttonDown: surfaceObj.blit(self.surfaceDown, self._rect) elif self.mouseOverButton: surfaceObj.blit(self.surfaceHighlight, self._rect) else: surfaceObj.blit(self.surfaceNorm...
module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier elif_...
Blit the current button's appearance to the surface object.
def pack(self): return self.key + self.uid.ljust(pyhsm.defines.UID_SIZE, chr(0))
module function_definition identifier parameters identifier block return_statement binary_operator attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier call identifier argument_list integer
Return key and uid packed for sending in a command to the YubiHSM.
def parse_stream(stream): code = [] for (line, col, (token, value)) in Tokenizer(stream).tokenize(): if token == Tokenizer.STRING: value = '"' + value + '"' code.append(value) return code
module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement tuple_pattern identifier identifier tuple_pattern identifier identifier call attribute call identifier argument_list identifier identifier argument_list block if_statement comparison_operator ...
Parse a Forth-like language and return code.
def clean_resource_json(resource_json): for a in ('parent_docname', 'parent', 'template', 'repr', 'series'): if a in resource_json: del resource_json[a] props = resource_json['props'] for prop in ( 'acquireds', 'style', 'in_nav', 'nav_title', 'weight', 'auto_excer...
module function_definition identifier parameters identifier block for_statement identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content stri...
The catalog wants to be smaller, let's drop some stuff
def dfs_do_func_on_graph(node, func, *args, **kwargs): for _node in node.tree_iterator(): func(_node, *args, **kwargs)
module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block for_statement identifier call attribute identifier identifier argument_list block expression_statement call identifier argument_list identifier list_splat identifier dictionary_...
invoke func on each node of the dr graph
def unhook_wnd_proc(self): if not self.__local_wnd_proc_wrapped: return SetWindowLong(self.__local_win_handle, GWL_WNDPROC, self.__old_wnd_proc) self.__local_wnd_proc_wrapped = None
module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block return_statement expression_statement call identifier argument_list attribute identifier identifier identifier attribute identifier identifier expression_statement assignment attribute ident...
Restore previous Window message handler
def set(self, varname, value, idx=0, units=None): if not varname in self.mapping.vars: raise fgFDMError('Unknown variable %s' % varname) if idx >= self.mapping.vars[varname].arraylength: raise fgFDMError('index of %s beyond end of array idx=%u arraylength=%u' % ( ...
module function_definition identifier parameters identifier identifier identifier default_parameter identifier integer default_parameter identifier none block if_statement not_operator comparison_operator identifier attribute attribute identifier identifier identifier block raise_statement call identifier argument_list...
set a variable value
def cublasSgbmv(handle, trans, m, n, kl, ku, alpha, A, lda, x, incx, beta, y, incy): status = _libcublas.cublasSgbmv_v2(handle, trans, m, n, kl, ku, ctypes.byref(ctypes.c_float(alpha)), ...
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identi...
Matrix-vector product for real general banded matrix.
def eval_file(file): 'evaluate file content as expressions' fname = os.path.realpath(os.path.expanduser(file)) with open(fname) as f: inscript = f.read() sh = run_write_read(['plash', 'eval'], inscript.encode()).decode() if sh.endswith('\n'): return sh[:-1] return sh
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list ...
evaluate file content as expressions
def to_user_agent(self): ua = "" if self.user_agent is not None: ua += "{user_agent} " ua += "gl-python/{python_version} " if self.grpc_version is not None: ua += "grpc/{grpc_version} " ua += "gax/{api_core_version} " if self.gapic_version is not N...
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_end if_statement comparison_operator attribute identifier identifier none block expression_statement augmented_assignment identifier string string_start string_content string_end expre...
Returns the user-agent string for this client info.
def generate(self, pattern=None): lst = self._lists[pattern] while True: result = lst[self._randrange(lst.length)] n = len(result) if (self._ensure_unique and len(set(result)) != n or self._check_prefix and len(set(x[:self._check_prefix] for x in r...
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier subscript attribute identifier identifier identifier while_statement true block expression_statement assignment identifier subscript identifier call attribute identifier identif...
Generates and returns random name as a list of strings.
def _group(self, obj, val, behavior): ns = self.Namespace() ns.result = {} iterator = self._lookupIterator(val) def e(value, index, *args): key = iterator(value, index) behavior(ns.result, key, value) _.each(obj, e) if len(ns.result) == 1: ...
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier dictionary expression_statement assignment identifier call attr...
An internal function used for aggregate "group by" operations.
def info(gandi): output_keys = ['handle', 'credit', 'prepaid'] account = gandi.account.all() account['prepaid_info'] = gandi.contact.balance().get('prepaid', {}) output_account(gandi, account, output_keys) return account
module function_definition identifier parameters identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute attribute ...
Display information about hosting account.