code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def close_compute_projects(self, compute): for project in self._projects.values(): if compute in project.computes: yield from project.close()
module function_definition identifier parameters identifier identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list block if_statement comparison_operator identifier attribute identifier identifier block expression_statement yield call attribute identifier ident...
Close projects running on a compute
def build(templates=None, schemes=None, base_output_dir=None): template_dirs = templates or get_template_dirs() scheme_files = get_scheme_files(schemes) base_output_dir = base_output_dir or rel_to_cwd('output') if not template_dirs or not scheme_files: raise LookupError try: os.maked...
module function_definition identifier parameters default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier call identifier argument_list expression_statement assignment identifier call identifier arg...
Main build function to initiate building process.
def selectis(table, field, value, complement=False): return selectop(table, field, value, operator.is_, complement=complement)
module function_definition identifier parameters identifier identifier identifier default_parameter identifier false block return_statement call identifier argument_list identifier identifier identifier attribute identifier identifier keyword_argument identifier identifier
Select rows where the given field `is` the given value.
def getcoordinates(self, tree, location): return tuple(float(x) for x in tree.xpath('.//%s/*/text()' % location))
module function_definition identifier parameters identifier identifier identifier block return_statement call identifier generator_expression call identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end...
Gets coordinates from a specific element in PLIP XML
def visit(self, node): method = 'visit_' + type(node).__name__ return getattr(self, method, self.fallback)(node)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end attribute call identifier argument_list identifier identifier return_statement call call identifier argument_list identifier identifier at...
Visit the right method of the child class according to the node.
def register(cls, name): def register_decorator(reg_cls): def name_func(self): return name reg_cls.name = property(name_func) assert issubclass(reg_cls, cls), \ "Must be subclass matching your NamedRegistry class" cls.REGISTRY[name]...
module function_definition identifier parameters identifier identifier block function_definition identifier parameters identifier block function_definition identifier parameters identifier block return_statement identifier expression_statement assignment attribute identifier identifier call identifier argument_list ide...
Decorator to register a class.
def run(self, b, compute, times=[], **kwargs): self.run_checks(b, compute, times, **kwargs) logger.debug("rank:{}/{} calling get_packet_and_syns".format(mpi.myrank, mpi.nprocs)) packet, new_syns = self.get_packet_and_syns(b, compute, times, **kwargs) if mpi.enabled: mpi.comm....
module function_definition identifier parameters identifier identifier identifier default_parameter identifier list dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list identifier identifier identifier dictionary_splat identifier expression_statement call att...
if within mpirun, workers should call _run_worker instead of run
def print_with_pager(output): if sys.stdout.isatty(): try: pager = subprocess.Popen( ['less', '-F', '-r', '-S', '-X', '-K'], stdin=subprocess.PIPE, stdout=sys.stdout) except subprocess.CalledProcessError: print(output) return ...
module function_definition identifier parameters identifier block if_statement call attribute attribute identifier identifier identifier argument_list block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list list string string_start string_content string_en...
Print the output to `stdout` using less when in a tty.
def __restore_selection(self, start_pos, end_pos): cursor = self.textCursor() cursor.setPosition(start_pos) cursor.setPosition(end_pos, QTextCursor.KeepAnchor) self.setTextCursor(cursor)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifi...
Restore cursor selection from position bounds
def full_name(self): return "%s %s %s %s" % (self.get_title_display(), self.first_name, self.other_names.replace(",", ""), self.last_name)
module function_definition identifier parameters identifier block return_statement binary_operator string string_start string_content string_end tuple call attribute identifier identifier argument_list attribute identifier identifier call attribute attribute identifier identifier identifier argument_list string string_...
Return the title and full name
def option_getter(type): option_getters = {None: ConfigParser.get, int: ConfigParser.getint, float: ConfigParser.getfloat, bool: ConfigParser.getboolean} return option_getters.get(type, option_getters[None])
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair none attribute identifier identifier pair identifier attribute identifier identifier pair identifier attribute identifier identifier pair identifier attribute identifier identifier return_stateme...
Gets an unbound method to get a configuration option as the given type.
def keyword(self, text): cls = self.KEYWORDS[text] self.push_token(cls(text, self.lineno, self.offset))
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier attribute identifier identifier at...
Push a keyword onto the token queue.
def pixels(self, value: int) -> 'Gap': raise_not_number(value) self.gap = '{}px'.format(value) return self
module function_definition identifier parameters identifier typed_parameter identifier type identifier type string string_start string_content string_end block expression_statement call identifier argument_list identifier expression_statement assignment attribute identifier identifier call attribute string string_start...
Set the margin in pixels.
def make_student(user): tutor_group, owner_group = _get_user_groups() user.is_staff = False user.is_superuser = False user.save() owner_group.user_set.remove(user) owner_group.save() tutor_group.user_set.remove(user) tutor_group.save()
module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier false expression_statem...
Makes the given user a student.
def remove_sqlvm_from_aglistener(instance, sqlvm_resource_id): if not is_valid_resource_id(sqlvm_resource_id): raise CLIError("Invalid SQL virtual machine resource id.") vm_list = instance.load_balancer_configurations[0].sql_virtual_machine_instances if sqlvm_resource_id in vm_list: instance...
module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier attribute subscript attribute ident...
Remove a SQL virtual machine from an availability group listener.
def package( files, tag, metadata, extra_options, branch, template_dir, plugins_dir, static, install, spatialite, version_note, **extra_metadata ): "Package specified SQLite files into a new datasette Docker container" if not shutil.which("docker"): click....
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier dictionary_splat_pattern identifier block expression_statement string string_start string_content string_end if_statement not_operator call attribute ...
Package specified SQLite files into a new datasette Docker container
def uri(self, value): if value == self.__uri: return match = URI_REGEX.match(value) if match is None: raise ValueError('Unable to match URI from `{}`'.format(value)) for key, value in match.groupdict().items(): setattr(self, key, value)
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block return_statement expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identi...
Attempt to validate URI and split into individual values
def reset(self): self.reached_limit = False self.count = 0 self.seen.clear()
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list
Resets state and uid set. To be called asap to free memory
def data(self): if self.sort: xs = sorted(self.dataset, key=self.sort_key) elif self.shuffle: xs = [self.dataset[i] for i in self.random_shuffler(range(len(self.dataset)))] else: xs = self.dataset return xs
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier elif_clause attribute identifier ident...
Return the examples in the dataset in order, sorted, or shuffled.
def stddev(self): if len(self) < 2: return float('NaN') try: arr = self.samples() mean = sum(arr) / len(arr) bigsum = 0.0 for x in arr: bigsum += (x - mean)**2 return sqrt(bigsum / (len(arr) - 1)) except ZeroDivisionError: return float('NaN')
module function_definition identifier parameters identifier block if_statement comparison_operator call identifier argument_list identifier integer block return_statement call identifier argument_list string string_start string_content string_end try_statement block expression_statement assignment identifier call attri...
Return the sample standard deviation.
def _handle_rate_exceeded(self, response): waiting_time = int(response.headers.get("Retry-After", 10)) time.sleep(waiting_time)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end integer expression_statement call attribute identifi...
Handles rate exceeded errors
def coincidents(self): coincident_sites = [] for i, tag in enumerate(self.site_properties['grain_label']): if 'incident' in tag: coincident_sites.append(self.sites[i]) return coincident_sites
module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end block if_statement comparison_operator ...
return the a list of coincident sites.
def validate(self): if not isinstance(self.fold_scope_location, FoldScopeLocation): raise TypeError(u'Expected FoldScopeLocation fold_scope_location, got: {} {}'.format( type(self.fold_scope_location), self.fold_scope_location)) if self.fold_scope_location.field is None: ...
module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list attribute identifier identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier a...
Validate that the FoldedContextField is correctly representable.
def _check_update_(self): try: data = requests.get("https://pypi.python.org/pypi/jira/json", timeout=2.001).json() released_version = data['info']['version'] if parse_version(released_version) > parse_version(__version__): warnings.warn( "Y...
module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier float identifier argument_list expression_statement...
Check if the current version of the library is outdated.
def update(self): response = requests.get(self.update_url, timeout=timeout) match = ip_pattern.search(response.content) if not match: raise ApiError("Couldn't parse the server's response", response.content) self.ip = match.group(0)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_...
Updates remote DNS record by requesting its special endpoint URL
def compute_rewards(self, scores): for i in range(len(scores)): if i >= self.k: scores[i] = 0. return scores
module function_definition identifier parameters identifier identifier block for_statement identifier call identifier argument_list call identifier argument_list identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment subscript identifier identi...
Retain the K most recent scores, and replace the rest with zeros
def use_comparative_assessment_part_view(self): self._object_views['assessment_part'] = COMPARATIVE for session in self._get_provider_sessions(): try: session.use_comparative_assessment_part_view() except AttributeError: pass
module function_definition identifier parameters identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end identifier for_statement identifier call attribute identifier identifier argument_list block try_statement block expression_statement ...
Pass through to provider AssessmentPartLookupSession.use_comparative_assessment_part_view
def validate_number_attribute(self, attribute: str, value_type: Union[Type[int], Type[float]] = int, minimum: Optional[Union[int, float]] = None, maximum: Optional[Union[int, float]] =...
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_default_parameter identifier type generic_type identifier type_parameter type generic_type identifier type_parameter type identifier type generic_type identifier type_parameter type identifier identifier typed_d...
Validates that the attribute contains a numeric value within boundaries if specified
def _select_features(example, feature_list=None): feature_list = feature_list or ["inputs", "targets"] return {f: example[f] for f in feature_list}
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier list string string_start string_content string_end string string_start string_content string_end return_statement dictionary_comprehension pair ident...
Select a subset of features from the example dict.
def begin_transaction(self, transaction_type, trace_parent=None): return self.tracer.begin_transaction(transaction_type, trace_parent=trace_parent)
module function_definition identifier parameters identifier identifier default_parameter identifier none block return_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier
Register the start of a transaction on the client
def merge(self, other): assert self.attrs == other.attrs self.tokens.extend(other.tokens) self.spaces.extend(other.spaces) self.strings.update(other.strings)
module function_definition identifier parameters identifier identifier block assert_statement comparison_operator attribute identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statem...
Extend the annotations of this binder with the annotations from another.
def _get_nics(vm_): nics = [] if 'public_lan' in vm_: firewall_rules = [] if 'public_firewall_rules' in vm_: firewall_rules = _get_firewall_rules(vm_['public_firewall_rules']) nic = NIC(lan=set_public_lan(int(vm_['public_lan'])), name='public', ...
module function_definition identifier parameters identifier block expression_statement assignment identifier list if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier list if_statement comparison_operator string string_start string_co...
Create network interfaces on appropriate LANs as defined in cloud profile.
def population(self): "Class containing the population and all the individuals generated" try: return self._p except AttributeError: self._p = self._population_class(base=self, tournament_size=self._tournament_size, ...
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end try_statement block return_statement attribute identifier identifier except_clause identifier block expression_statement assignment attribute identifier identifier call attribute identifi...
Class containing the population and all the individuals generated
def mul_block(self, index, val): self._prepare_cache_slice(index) self.msinds[self.cache_slice] *= val
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement augmented_assignment subscript attribute identifier identifier attribute identifier identifier identifier
Multiply values in block
def boxed_text_to_image_block(tag): "covert boxed-text to an image block containing an inline-graphic" tag_block = OrderedDict() image_content = body_block_image_content(first(raw_parser.inline_graphic(tag))) tag_block["type"] = "image" set_if_value(tag_block, "doi", doi_uri_to_doi(object_id_doi(tag...
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list call identifier argument_list call attrib...
covert boxed-text to an image block containing an inline-graphic
def server_online(self): response = self._post(self.apiurl + '/v2/server/online', data={'apikey': self.apikey}) return self._raise_or_extract(response)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator attribute identifier identifier string string_start string_content string_end keyword_argument identifier dictionary pair string string_start st...
Returns True if the Joe Sandbox servers are running or False if they are in maintenance mode.
def convert_lat(Recs): New = [] for rec in Recs: if 'model_lat' in list(rec.keys()) and rec['model_lat'] != "": New.append(rec) elif 'average_age' in list(rec.keys()) and rec['average_age'] != "" and float(rec['average_age']) <= 5.: if 'site_lat' in list(rec.keys()) and r...
module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier identifier block if_statement boolean_operator comparison_operator string string_start string_content string_end call identifier argument_list call attribute identifier identifier a...
uses lat, for age<5Ma, model_lat if present, else tries to use average_inc to estimate plat.
def format_context( context: Context, formatter: typing.Union[str, Formatter] = "full" ) -> str: if not context: return "" if callable(formatter): formatter_func = formatter else: if formatter in CONTEXT_FORMATTERS: formatter_func = CONTEXT_FORMATTERS[formatter] ...
module function_definition identifier parameters typed_parameter identifier type identifier typed_default_parameter identifier type subscript attribute identifier identifier identifier identifier string string_start string_content string_end type identifier block if_statement not_operator identifier block return_statem...
Output the a context dictionary as a string.
def Intersect(self, mask1, mask2): _CheckFieldMaskMessage(mask1) _CheckFieldMaskMessage(mask2) tree = _FieldMaskTree(mask1) intersection = _FieldMaskTree() for path in mask2.paths: tree.IntersectPath(path, intersection) intersection.ToFieldMask(self)
module function_definition identifier parameters identifier identifier identifier block expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement ass...
Intersects mask1 and mask2 into this FieldMask.
def clear_extensions(self, group=None): if group is None: ComponentRegistry._registered_extensions = {} return if group in self._registered_extensions: self._registered_extensions[group] = []
module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment attribute identifier identifier dictionary return_statement if_statement comparison_operator identifier attribute identifier identifi...
Clear all previously registered extensions.
def reverse_compl_with_name(old_seq): new_seq = old_seq.reverse_complement() new_seq.id = old_seq.id new_seq.description = old_seq.description return new_seq
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier ...
Reverse a SeqIO sequence, but keep its name intact.
def _construct_from_json(self, rec): self.delete() for required_key in ['dagobah_id', 'created_jobs']: setattr(self, required_key, rec[required_key]) for job_json in rec.get('jobs', []): self._add_job_from_spec(job_json) self.commit(cascade=True)
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list for_statement identifier list string string_start string_content string_end string string_start string_content string_end block expression_statement call identifier argume...
Construct this Dagobah instance from a JSON document.
def _find_self(param_names: List[str], args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Any: instance_i = param_names.index("self") if instance_i < len(args): instance = args[instance_i] else: instance = kwargs["self"] return instance
module function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type ellipsis typed_parameter identifier type generic_type identifier type_parameter type identif...
Find the instance of ``self`` in the arguments.
def _get_template_dirs(type="plugin"): template_dirs = [ os.path.expanduser(os.path.join(USER_CONFIG_DIR, "templates", type)), os.path.join("rapport", "templates", type) ] return template_dirs
module function_definition identifier parameters default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier list call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_lis...
Return a list of directories where templates may be located.
def _sumterm(lexer): xorterm = _xorterm(lexer) sumterm_prime = _sumterm_prime(lexer) if sumterm_prime is None: return xorterm else: return ('or', xorterm, sumterm_prime)
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier none block return_statement identifier els...
Return a sum term expresssion.
def CheckClientApprovalRequest(approval_request): _CheckExpired(approval_request) _CheckHasEnoughGrants(approval_request) if not client_approval_auth.CLIENT_APPROVAL_AUTH_MGR.IsActive(): return True token = access_control.ACLToken(username=approval_request.requestor_username) approvers = set(g.grantor_use...
module function_definition identifier parameters identifier block expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list block return_statement true expr...
Checks if a client approval request is granted.
def _gap_progenitor_setup(self): self._gap_progenitor= self._progenitor().flip() self._gap_progenitor.turn_physical_off() ts= numpy.linspace(0.,self._tdisrupt,1001) self._gap_progenitor.integrate(ts,self._pot) self._gap_progenitor._orb.orbit[:,1]= -self._gap_progenitor._orb.orbit...
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute call attribute identifier identifier argument_list identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expres...
Setup an Orbit instance that's the progenitor integrated backwards
def _create_row_col_indices(ratings_df): user_id_to_user_idx = _create_index(ratings_df, "userId") item_id_to_item_idx = _create_index(ratings_df, "movieId") ratings_df["row"] = ratings_df["userId"].apply( lambda x: user_id_to_user_idx[x]) ratings_df["col"] = ratings_df["movieId"].apply( lambda x: i...
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier string string_start string_content strin...
Maps user and items ids to their locations in the rating matrix.
def outlierDetection_threaded(samples_x, samples_y_aggregation): outliers = [] threads_inputs = [[samples_idx, samples_x, samples_y_aggregation]\ for samples_idx in range(0, len(samples_x))] threads_pool = ThreadPool(min(4, len(threads_inputs))) threads_results = threads_pool...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list expression_statement assignment identifier list_comprehension list identifier identifier identifier line_continuation for_in_clause identifier call identifier argument_list integer call identifie...
Use Multi-thread to detect the outlier
def _with_env(self, env): res = self._browse(env, self._ids) return res
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier return_statement identifier
As the `with_env` class method but for recordset.
def _get_db_connect(dbSystem,db,user,password): if dbSystem=='SYBASE': import Sybase try: dbh = Sybase.connect(dbSystem, user, password, database=db ) except: dbh=No...
module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block import_statement dotted_name identifier try_statement block expression_statement assignment identifier call attribute identif...
Create a connection to the database specified on the command line
def create(client, _type, **kwargs): obj = client.factory.create("ns0:%s" % _type) for key, value in kwargs.items(): setattr(obj, key, value) return obj
module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end identifier for_statement patte...
Create a suds object of the requested _type.
def list_mypasswords_search(self, searchstring): log.debug('List MyPasswords with %s' % searchstring) return self.collection('my_passwords/search/%s.json' % quote_plus(searchstring))
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list binary_operator string string_...
List my passwords with searchstring.
def _safe_readinto(self, b): total_bytes = 0 mvb = memoryview(b) while total_bytes < len(b): if MAXAMOUNT < len(mvb): temp_mvb = mvb[0:MAXAMOUNT] n = self.fp.readinto(temp_mvb) else: n = self.fp.readinto(mvb) if ...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier integer expression_statement assignment identifier call identifier argument_list identifier while_statement comparison_operator identifier call identifier argument_list identifier block if_statement c...
Same as _safe_read, but for reading into a buffer.
def main(handwriting_datasets_file, analyze_features): logging.info("Start loading data '%s' ...", handwriting_datasets_file) loaded = pickle.load(open(handwriting_datasets_file)) raw_datasets = loaded['handwriting_datasets'] logging.info("%i datasets loaded.", len(raw_datasets)) logging.info("Start...
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argu...
Start the creation of the wanted metric.
def eval_str_to_list(input_str: str) -> List[str]: inner_cast = ast.literal_eval(input_str) if isinstance(inner_cast, list): return inner_cast else: raise ValueError
module function_definition identifier parameters typed_parameter identifier type identifier type generic_type identifier type_parameter type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call identifier argument_list identifier ide...
Turn str into str or tuple.
def _convert_and_assert_per_example_weights_compatible( input_, per_example_weights, dtype): per_example_weights = tf.convert_to_tensor( per_example_weights, name='per_example_weights', dtype=dtype) if input_.get_shape().ndims: expected_length = input_.get_shape().dims[0] message = ('per_example_w...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier if_statement a...
Converts per_example_weights to a tensor and validates the shape.
def all_active(cls): prefix = context.get_current_config()["redis_prefix"] queues = [] for key in context.connections.redis.keys(): if key.startswith(prefix): queues.append(Queue(key[len(prefix) + 3:])) return queues
module function_definition identifier parameters identifier block expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier list for_statement identifier call attribute attribute attrib...
List active queues, based on their lengths in Redis. Warning, uses the unscalable KEYS redis command
def _dump(file_obj, options, out=sys.stdout): total_count = 0 writer = None keys = None for row in DictReader(file_obj, options.col): if not keys: keys = row.keys() if not writer: writer = csv.DictWriter(out, keys, delimiter=u'\t', quotechar=u'\'', quoting=csv.QUO...
module function_definition identifier parameters identifier identifier default_parameter identifier attribute identifier identifier block expression_statement assignment identifier integer expression_statement assignment identifier none expression_statement assignment identifier none for_statement identifier call ident...
Dump to fo with given options.
def app_size(self): "Return the total apparent size, including children." if self._nodes is None: return self._app_size return sum(i.app_size() for i in self._nodes)
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement comparison_operator attribute identifier identifier none block return_statement attribute identifier identifier return_statement call identifier generator_expression call att...
Return the total apparent size, including children.
def _hashes_match(self, a, b): if len(a) != len(b): return False diff = 0 if six.PY2: a = bytearray(a) b = bytearray(b) for x, y in zip(a, b): diff |= x ^ y return not diff
module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator call identifier argument_list identifier call identifier argument_list identifier block return_statement false expression_statement assignment identifier integer if_statement attribute identifier ide...
Constant time comparison of bytes for py3, strings for py2
def _column_resized(self, col, old_width, new_width): self.dataTable.setColumnWidth(col, new_width) self._update_layout()
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list
Update the column width.
def _build_response(self, resp): self.response.content = resp.content self.response.status_code = resp.status_code self.response.headers = resp.headers
module function_definition identifier parameters identifier identifier block expression_statement assignment attribute attribute identifier identifier identifier attribute identifier identifier expression_statement assignment attribute attribute identifier identifier identifier attribute identifier identifier expressio...
Build internal Response object from given response.
def generate_security_hash(self, content_type, object_pk, timestamp): info = (content_type, object_pk, timestamp) key_salt = "django.contrib.forms.CommentSecurityForm" value = "-".join(info) return salted_hmac(key_salt, value).hexdigest()
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier tuple identifier identifier identifier expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call at...
Generate a HMAC security hash from the provided info.
def auto_scroll(self, thumbkey): if not self.gui_up: return scrollp = self.w.auto_scroll.get_state() if not scrollp: return bnch = self.thumb_dict[thumbkey] pan_x, pan_y = self.c_view.get_pan() self.c_view.panset_xy(pan_x, bnch.image.y)
module function_definition identifier parameters identifier identifier block if_statement not_operator attribute identifier identifier block return_statement expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list if_statement not_operator ...
Scroll the window to the thumb.
def mx_page_trees(self, mx_page): resp = dict() for tree_name, tree in self.scheduler.timetable.trees.items(): if tree.mx_page == mx_page: rest_tree = self._get_tree_details(tree_name) resp[tree.tree_name] = rest_tree.document return resp
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list for_statement pattern_list identifier identifier call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list block i...
return trees assigned to given MX Page
def get(cls, parent, name): return cls.query.filter_by(parent=parent, name=name).one_or_none()
module function_definition identifier parameters identifier identifier identifier block return_statement call attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier identifier argument_list
Get an instance matching the parent and name
def path_helper(self, operations, view, app=None, **kwargs): rule = self._rule_for_view(view, app=app) operations.update(yaml_utils.load_operations_from_docstring(view.__doc__)) if hasattr(view, 'view_class') and issubclass(view.view_class, MethodView): for method in view.methods: ...
module function_definition identifier parameters identifier identifier identifier default_parameter identifier none dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier expression_stateme...
Path helper that allows passing a Flask view function.
def create_tipo_rede(self): return TipoRede( self.networkapi_url, self.user, self.password, self.user_ldap)
module function_definition identifier parameters identifier block return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier
Get an instance of tipo_rede services facade.
def limiter(arr): dyn_range = 32767.0 / 32767.0 lim_thresh = 30000.0 / 32767.0 lim_range = dyn_range - lim_thresh new_arr = arr.copy() inds = N.where(arr > lim_thresh)[0] new_arr[inds] = (new_arr[inds] - lim_thresh) / lim_range new_arr[inds] = (N.arctan(new_arr[inds]) * 2.0 / N.pi) *\ ...
module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator float float expression_statement assignment identifier binary_operator float float expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment...
Restrict the maximum and minimum values of arr
def add_check(self, check_item): self.checks.append(check_item) for other in self.others: other.add_check(check_item)
module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list iden...
Adds a check universally.
def _get_firefox_start_cmd(self): start_cmd = "" if platform.system() == "Darwin": start_cmd = "/Applications/Firefox.app/Contents/MacOS/firefox-bin" if not os.path.exists(start_cmd): start_cmd = os.path.expanduser("~") + start_cmd elif platform.system() =...
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_end if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier s...
Return the command to start firefox.
def backward_step(self): logger.debug("Executing backward step ...") self.run_to_states = [] self.set_execution_mode(StateMachineExecutionStatus.BACKWARD)
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 expression_statement call attribute identifier identifier argument_...
Take a backward step for all active states in the state machine
def create_session(self, ticket, payload=None, expires=None): assert isinstance(self.session_storage_adapter, CASSessionAdapter) logging.debug('[CAS] Creating session for ticket {}'.format(ticket)) self.session_storage_adapter.create( ticket, payload=payload, ...
module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block assert_statement call identifier argument_list attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list call attribut...
Create a session record from a service ticket.
def _ProcessSources(self, sources, parser_factory): for source in sources: for action, request in self._ParseSourceType(source): yield self._RunClientAction(action, request, parser_factory, source.path_type)
module function_definition identifier parameters identifier identifier identifier block for_statement identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier block expression_statement yield call attribute identifier identifier argument_...
Iterates through sources yielding action responses.
def read_utf8(fh, byteorder, dtype, count, offsetsize): return fh.read(count).decode('utf-8')
module function_definition identifier parameters identifier identifier identifier identifier identifier block return_statement call attribute call attribute identifier identifier argument_list identifier identifier argument_list string string_start string_content string_end
Read tag data from file and return as unicode string.
def _set_req_to_reinstall(self, req): if not self.use_user_site or dist_in_usersite(req.satisfied_by): req.conflicts_with = req.satisfied_by req.satisfied_by = None
module function_definition identifier parameters identifier identifier block if_statement boolean_operator not_operator attribute identifier identifier call identifier argument_list attribute identifier identifier block expression_statement assignment attribute identifier identifier attribute identifier identifier expr...
Set a requirement to be installed.
def patched(attrs, updates): orig = patch(attrs, updates.items()) try: yield orig finally: patch(attrs, orig.items())
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier call attribute identifier identifier argument_list try_statement block expression_statement yield identifier finally_clause block expression_statement call ide...
A context in which some attributes temporarily have a modified value.
def cdfout(data, file): f = open(file, "w") data.sort() for j in range(len(data)): y = old_div(float(j), float(len(data))) out = str(data[j]) + ' ' + str(y) + '\n' f.write(out) f.close()
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list for_statement identifier call identifier ...
spits out the cdf for data to file
def _are_nearby_parallel_boxes(self, b1, b2): "Are two boxes nearby, parallel, and similar in width?" if not self._are_aligned_angles(b1.angle, b2.angle): return False angle = min(b1.angle, b2.angle) return abs(np.dot(b1.center - b2.center, [-np.sin(angle), np.cos(angle)])) <...
module function_definition identifier parameters identifier identifier identifier block expression_statement string string_start string_content string_end if_statement not_operator call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier block return_statement f...
Are two boxes nearby, parallel, and similar in width?
def ensure_a_list(data): if not data: return [] if isinstance(data, (list, tuple, set)): return list(data) if isinstance(data, str): data = trimmed_split(data) return data return [data]
module function_definition identifier parameters identifier block if_statement not_operator identifier block return_statement list if_statement call identifier argument_list identifier tuple identifier identifier identifier block return_statement call identifier argument_list identifier if_statement call identifier arg...
Ensure data is a list or wrap it in a list
def save_csv(self): self.results.sort_values(by=self.column_ids, inplace=True) self.results.reindex(columns=self.column_ids).to_csv( self.csv_filepath, index=False)
module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier true expression_statement call attribute call attribute attribute identif...
Dump all results to CSV.
def cli(ctx, env): env.out("Welcome to the SoftLayer shell.") env.out("") formatter = formatting.HelpFormatter() commands = [] shell_commands = [] for name in cli_core.cli.list_commands(ctx): command = cli_core.cli.get_command(ctx, name) if command.short_help is None: ...
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_end expression_statement a...
Print shell help text.
def adjust(color, attribute, percent): r, g, b, a, type = parse_color(color) r, g, b = hsl_to_rgb(*_adjust(rgb_to_hsl(r, g, b), attribute, percent)) return unparse_color(r, g, b, a, type)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier identifier identifier call identifier argument_list identifier expression_statement assignment pattern_list identifier identifier identifier call identifi...
Adjust an attribute of color by a percent
def _logprior(self): logj = self.logjacobian logp = self.prior_distribution(**self.current_params) + logj if numpy.isnan(logp): logp = -numpy.inf return logp
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list dictionary_splat attribute identifier identifier identifier if_statem...
Calculates the log prior at the current parameters.
def __BitList_to_String(self, data): result = [] pos = 0 c = 0 while pos < len(data): c += data[pos] << (7 - (pos % 8)) if (pos % 8) == 7: result.append(c) c = 0 pos += 1 if _pythonMajorVersion < 3: return ''.join([ chr(c) for c in result ]) else: return bytes(result)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list expression_statement assignment identifier integer expression_statement assignment identifier integer while_statement comparison_operator identifier call identifier argument_list identifier block...
Turn the list of bits -> data, into a string
def _refresh_and_update(self): if not self._operation.done: self._operation = self._refresh() self._set_result_from_operation()
module function_definition identifier parameters identifier block if_statement not_operator attribute attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identif...
Refresh the operation and update the result if needed.
def _lint(self): command = self._get_command() process = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) LOG.info('Finished %s', ' '.join(command)) stdout, stderr = self._get_output_lines(process) return self._linter.parse(...
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identi...
Run linter in a subprocess.
def _write_docs(module_list, output_dir): for module_meta in module_list: directory = module_meta['directory'] if directory and not path.isdir(directory): makedirs(directory) file = open(module_meta['output'], 'w') file.write(module_meta['content']) file.close()
module function_definition identifier parameters identifier identifier block for_statement identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement boolean_operator identifier not_operator call attribute identifier identifier ...
Write the document meta to our output location.
def lsmod(self): lines = shell_out("lsmod", timeout=0).splitlines() return [line.split()[0].strip() for line in lines]
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call identifier argument_list string string_start string_content string_end keyword_argument identifier integer identifier argument_list return_statement list_comprehension call attribute subscrip...
Return a list of kernel module names as strings.
def rlmb_tiny_sv2p(): hparams = rlmb_ppo_tiny() hparams.generative_model = "next_frame_sv2p" hparams.generative_model_params = "next_frame_sv2p_tiny" hparams.grayscale = False return hparams
module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier string string_star...
Tiny setting with a tiny sv2p model.
def ping(): try: response = salt.utils.http.query( "{0}/ping".format(CONFIG[CONFIG_BASE_URL]), decode_type='plain', decode=True, ) log.debug( 'marathon.info returned successfully: %s', response, ) if 'text' in respon...
module function_definition identifier parameters block try_statement block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list subscript identifier id...
Is the marathon api responding?
def _rlmb_tiny_overrides(): return dict( epochs=1, num_real_env_frames=128, model_train_steps=2, max_num_noops=1, eval_max_num_noops=1, generative_model_params="next_frame_tiny", stop_loop_early=True, resize_height_factor=2, resize_width_factor=2, wm_eval_ro...
module function_definition identifier parameters block return_statement call identifier argument_list keyword_argument identifier integer keyword_argument identifier integer keyword_argument identifier integer keyword_argument identifier integer keyword_argument identifier integer keyword_argument identifier string str...
Parameters to override for tiny setting excluding agent-related hparams.
def tickets(self, extra_params=None): tickets = [] for space in self.api.spaces(): tickets += filter( lambda ticket: ticket.get('assigned_to_id', None) == self['id'], space.tickets(extra_params=extra_params) ) return tickets
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier list for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement augmented_assignment identifier call identifier ...
A User's tickets across all available spaces
def _assemble_influence(stmt): subj_str = _assemble_agent_str(stmt.subj.concept) obj_str = _assemble_agent_str(stmt.obj.concept) if stmt.subj.delta['polarity'] is not None: subj_delta_str = ' decrease' if stmt.subj.delta['polarity'] == -1 \ else 'n increase' subj_str = 'a%s in %s...
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier if...
Assemble an Influence statement into text.
def built_datetime(self): from datetime import datetime try: return datetime.fromtimestamp(self.state.build_done) except TypeError: return None
module function_definition identifier parameters identifier block import_from_statement dotted_name identifier dotted_name identifier try_statement block return_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier except_clause identifier block return_stateme...
Return the built time as a datetime object
def db_insert(self): assert self.has_db coll = self.manager.db_connector.get_collection() print("Mongodb collection %s with count %d", coll, coll.count()) start = time.time() for work in self: for task in work: results = task.get_results() ...
module function_definition identifier parameters identifier block assert_statement attribute identifier identifier expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list expression_statement call identifier argument_list string string_star...
Insert results in the `MongDB` database.
def whowas(self, nick, max="", server=""): self.send_items('WHOWAS', nick, max, server)
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_end default_parameter identifier string string_start string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end ident...
Send a WHOWAS command.
def record_is_valid(record): "Checks if a record is valid for processing." if record.CHROM.startswith('GL'): return False if 'DP' in record.INFO and record.INFO['DP'] < 5: return False return True
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block return_statement false if_statement boolean_operat...
Checks if a record is valid for processing.
def append_onto_file(self, file_name, msg): with open(file_name, "a") as heart_file: heart_file.write(msg) heart_file.close()
module function_definition identifier parameters identifier 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 argu...
Appends msg onto the Given File