code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def serialize_instance(instance): model_name = force_text(instance._meta) return '{}:{}'.format(model_name, instance.pk)
Serialize Django model instance
def use_comparative_relationship_view(self): self._object_views['relationship'] = COMPARATIVE for session in self._get_provider_sessions(): try: session.use_comparative_relationship_view() except AttributeError: pass
Pass through to provider RelationshipLookupSession.use_comparative_relationship_view
def gen_send_version_url(ip, port): return '{0}:{1}{2}{3}/{4}/{5}'.format(BASE_URL.format(ip), port, API_ROOT_URL, VERSION_API, NNI_EXP_ID, NNI_TRIAL_JOB_ID)
Generate send error url
def print_languages_and_exit(lst, status=1, header=True): if header: print("Available languages:") for lg in lst: print("- %s" % lg) sys.exit(status)
print a list of languages and exit
def read_PIA0_A_control(self, cpu_cycles, op_address, address): value = 0xb3 log.error( "%04x| read $%04x (PIA 0 A side Control reg.) send $%02x (%s) back.\t|%s", op_address, address, value, byte2bit_string(value), self.cfg.mem_info.get_shortest(op_address) ) ...
read from 0xff01 -> PIA 0 A side control register
def add(self, *tokens: str) -> None: from wdom.web_node import WdomElement _new_tokens = [] for token in tokens: self._validate_token(token) if token and token not in self: self._list.append(token) _new_tokens.append(token) if isins...
Add new tokens to list.
def send_reminder(self, user, sender=None, **kwargs): if user.is_active: return False token = RegistrationTokenGenerator().make_token(user) kwargs.update({"token": token}) self.email_message( user, self.reminder_subject, self.reminder_body, sender, **kwargs ...
Sends a reminder email to the specified user
def _return_result(self, result, comparison_vectors=None): return_type = cf.get_option('classification.return_type') if type(result) != np.ndarray: raise ValueError("numpy.ndarray expected.") if return_type == 'index': return comparison_vectors.index[result.astype(bool)] ...
Return different formatted classification results.
def _unquote(self, value): if not value: raise SyntaxError if (value[0] == value[-1]) and (value[0] in ('"', "'")): value = value[1:-1] return value
Return an unquoted version of a value
def toys(self) -> Tuple[timetools.TOY, ...]: return tuple(toy for (toy, _) in self)
A sorted |tuple| of all contained |TOY| objects.
def _serialize_zebra_family_prefix(prefix): if ip.valid_ipv4(prefix): family = socket.AF_INET prefix_addr, prefix_num = prefix.split('/') return family, struct.pack( _ZEBRA_FAMILY_IPV4_PREFIX_FMT, family, addrconv.ipv4.text_to_bin(prefix_addr), ...
Serializes family and prefix in Zebra format.
def validatetag(context): "Check to make sure that a tag exists for the current HEAD and it looks like a valid version number" result = context.run("git describe --exact-match --tags $(git log -n1 --pretty='%h')") tag = result.stdout.rstrip() ver_regex = re.compile('(\d+)\.(\d+)\.(\d+)') match = ver...
Check to make sure that a tag exists for the current HEAD and it looks like a valid version number
def add_rulegroup(self, rulegroup): body = rulegroup response = self._post("/segments/%s/rules.json" % self.segment_id, json.dumps(body))
Adds a rulegroup to this segment.
def run(self): paths = [x for x in practices.__dict__.values() if hasattr(x, 'code')] for node in ast.walk(self.tree): try: lineno, col_offset = node.lineno, node.col_offset except AttributeError: continue for checker i...
Primary entry point to the plugin, runs once per file.
def regs(self): regs = set() for operand in self.operands: if not operand.type.has_reg: continue regs.update(operand.regs) return regs
Names of all registers used by the instruction.
def create_ports(port, mpi, rank): if port == "random" or port is None: ports = {} else: port = int(port) ports = { "REQ": port + 0, "PUSH": port + 1, "SUB": port + 2 } if mpi == 'all': fo...
create a list of ports for the current rank
def _log_length_error(self, key, length): extra = { "max_detail_length": settings.defaults["max_detail_length"], "len": length } if self.key_name: extra[self.key_name] = key msg = "Length of data in %s is too long." % self.__class__.__name__ lo...
Helper function for logging a response length error.
def _fixedpoint(D, tol=1e-7, maxiter=None): N, K = D.shape logp = log(D).mean(axis=0) a0 = _init_a(D) if maxiter is None: maxiter = MAXINT for i in xrange(maxiter): a1 = _ipsi(psi(a0.sum()) + logp) if abs(loglikelihood(D, a1)-loglikelihood(D, a0)) < tol: return a1...
Simple fixed point iteration method for MLE of Dirichlet distribution
def tmpfile(*args, **kwargs): (fd, fname) = tempfile.mkstemp(*args, **kwargs) try: yield fname finally: os.close(fd) if os.path.exists(fname): os.remove(fname)
Make a tempfile, safely cleaning up file descriptors on completion.
def go_to_line(self, line=None): editorstack = self.get_current_editorstack() if editorstack is not None: editorstack.go_to_line(line)
Open 'go to line' dialog
def generate_uppercase_key(key, namespace=None): if namespace: namespace = [part for part in listify(namespace) if part] key = '_'.join(namespace + [key]) key = key.upper() return key
Given a key and a namespace, generates a final uppercase key.
def exec_module(self, module): path = [os.path.dirname(module.__file__)] file = None try: file, pathname, description = imp.find_module(module.__name__.rpartition('.')[-1], path) module = imp.load_module(module.__name__, file, pathname, description) finally: ...
Execute the module using the old imp.
def recvline(sock): reply = io.BytesIO() while True: c = sock.recv(1) if not c: return None if c == b'\n': break reply.write(c) result = reply.getvalue() log.debug('-> %r', result) return result
Receive a single line from the socket.
def off(self): self._send_method(StandardSend(self._address, COMMAND_LIGHT_OFF_0X13_0X00), self._off_message_received)
Send OFF command to device.
def make_structure_from_geos(geos): model_structure=initialize_res(geos[0]) for i in range(1,len(geos)): model_structure=add_residue(model_structure, geos[i]) return model_structure
Creates a structure out of a list of geometry objects.
def group(self, groupId): url = "%s/%s" % (self.root, groupId) return Group(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port, initalize=False)
gets a group based on it's ID
def as_bel(self) -> str: return 'pmod({}{})'.format( str(self[IDENTIFIER]), ''.join(', {}'.format(self[x]) for x in PMOD_ORDER[2:] if x in self) )
Return this protein modification variant as a BEL string.
def sound_mode(self): sound_mode_matched = self._parent_avr.match_sound_mode( self._parent_avr.sound_mode_raw) return sound_mode_matched
Return the matched current sound mode as a string.
def write(self, data): self._check_not_closed() if not data: return 0 enc_data = self.encryptor.update(data) self.next_fp.write(enc_data) self.offset += len(data) return len(data)
Encrypt and write the given bytes
def export_to_dicts(table, *args, **kwargs): field_names = table.field_names return [{key: getattr(row, key) for key in field_names} for row in table]
Export a `rows.Table` to a list of dicts
def on_batch_begin(self, last_input, last_target, **kwargs): "accumulate samples and batches" self.acc_samples += last_input.shape[0] self.acc_batches += 1
accumulate samples and batches
def observe_all(self, callback: Callable[[str, Any, Any], None]): self._all_callbacks.append(callback)
Subscribes to all keys changes
def init(name, runtime): runtime = click.unstyle(runtime) stdout.write( style.format_command( 'Initializing', '%s %s %s' % (name, style.gray('@'), style.green(runtime)) ) ) config = Config(os.getcwd()) config.set('runtime', runtime) config.save() gener...
Create a new Django app.
def public(self, *args, **kwargs): kwargs['public'] = True return self.filter(*args, **kwargs)
Only return public actions
def image_mapped(name): try: out = check_output(['rbd', 'showmapped']) if six.PY3: out = out.decode('UTF-8') except CalledProcessError: return False return name in out
Determine whether a RADOS block device is mapped locally.
def click_a_point(self, x=0, y=0, duration=100): self._info("Clicking on a point (%s,%s)." % (x,y)) driver = self._current_application() action = TouchAction(driver) try: action.press(x=float(x), y=float(y)).wait(float(duration)).release().perform() except: ...
Click on a point
def getRloc16(self): print '%s call getRloc16' % self.port rloc16 = self.__sendCommand('rloc16')[0] return int(rloc16, 16)
get rloc16 short address
def copy_files(src, ext, dst): src_path = os.path.join(os.path.dirname(__file__), src) dst_path = os.path.join(os.path.dirname(__file__), dst) file_list = os.listdir(src_path) for f in file_list: if f == '__init__.py': continue f_path = os.path.join(src_path, f) if os...
Copies files with extensions "ext" from "src" to "dst" directory.
def line(self, text=''): self.out.write(text) self.out.write('\n')
A simple helper to write line with `\n`
def update(self,record,**kw): vals = self._make_sql_params(kw) sql = "UPDATE %s SET %s WHERE rowid=?" %(self.name, ",".join(vals)) self.cursor.execute(sql,kw.values()+[record['__id__']])
Update the record with new keys and values
def bookmarks_changed(self): bookmarks = self.editor.get_bookmarks() if self.editor.bookmarks != bookmarks: self.editor.bookmarks = bookmarks self.sig_save_bookmarks.emit(self.filename, repr(bookmarks))
Bookmarks list has changed.
def out_filename(template, n_val, mode): return '{0}_{1}_{2}.cpp'.format(template.name, n_val, mode.identifier)
Determine the output filename
def add_reference(self, source, target, **kwargs): addRef_kw = kwargs.copy() addRef_kw.setdefault("referenceClass", self.referenceClass) if "schema" in addRef_kw: del addRef_kw["schema"] uid = api.get_uid(target) rc = api.get_tool("reference_catalog") rc.addRe...
Add a new reference
def draw_image( self, img_filename:str, x:float, y:float, w:float, h:float ) -> None: pass
Draws the given image.
def split_on_condition(seq, condition): l1, l2 = tee((condition(item), item) for item in seq) return (i for p, i in l1 if p), (i for p, i in l2 if not p)
Split a sequence into two iterables without looping twice
def to_wire(self, file, compress=None, origin=None, **kw): return super(RRset, self).to_wire(self.name, file, compress, origin, self.deleting, **kw)
Convert the RRset to wire format.
def validate_with_schema(self, collection=None, context=None): if self._schema is None or not collection: return result = [] try: for index, item in enumerate(collection): item_result = self._schema.validate( model=item, ...
Validate each item in collection with our schema
def create_role(name): role = role_manager.create(name=name) if click.confirm(f'Are you sure you want to create {role!r}?'): role_manager.save(role, commit=True) click.echo(f'Successfully created {role!r}') else: click.echo('Cancelled.')
Create a new role.
def address_inline(request, prefix="", country_code=None, template_name="postal/form.html"): country_prefix = "country" prefix = request.POST.get('prefix', prefix) if prefix: country_prefix = prefix + '-country' country_code = request.POST.get(country_prefix, country_code) form_class = form_...
Displays postal address with localized fields
def remove_file(file_path): if path.exists(file_path): try: rmtree(file_path) except Exception: print('Unable to remove temporary workdir {}'.format(file_path))
Remove a file from the filesystem.
def async_step(self): assert len(self._agents_to_act) == 0 self._init_step() t = time.time() aiomas.run(until=self.env.trigger_all()) self._agents_to_act = [] self._step_processing_time = time.time() - t self._finalize_step()
Progress simulation by running all agents once asynchronously.
def render_check_and_set_platforms(self): phase = 'prebuild_plugins' plugin = 'check_and_set_platforms' if not self.pt.has_plugin_conf(phase, plugin): return if self.user_params.koji_target.value: self.pt.set_plugin_arg(phase, plugin, "koji_target", ...
If the check_and_set_platforms plugin is present, configure it
def normalize_urls(urls): _urls = [] if isinstance(urls, list): if urls: if isinstance(urls[0], list): _urls = urls elif isinstance(urls[0], str): _urls = [urls] else: raise RuntimeError("No target host url provided.") elif ...
Overload urls and make list of lists of urls.
def adjust(self, ln): adj_ln = ln need_unskipped = 0 for i in self.skips: if i <= ln: need_unskipped += 1 elif adj_ln + need_unskipped < i: break else: need_unskipped -= i - adj_ln - 1 adj_ln = i ...
Converts a parsing line number into an original line number.
def load_data(self): options=self.options command = open(self.options.data_script).read() self.result["data_script"]=command t0=time.time() data=None exec(command) t1=time.time() print(("Elapsed time for data reading is %.2f seconds" % (t1-t0))) se...
Run the job specified in data_script
def stars_list(self, **kwargs) -> SlackResponse: self._validate_xoxp_token() return self.api_call("stars.list", http_verb="GET", params=kwargs)
Lists stars for a user.
def copy_figure(self): if self.figviewer and self.figviewer.figcanvas.fig: self.figviewer.figcanvas.copy_figure()
Copy figure from figviewer to clipboard.
def convert(outputfile, inputfile, to_format, from_format): emb = word_embedding.WordEmbedding.load( inputfile, format=_input_choices[from_format][1], binary=_input_choices[from_format][2]) emb.save(outputfile, format=_output_choices[to_format][1], binary=_output_choices[to_format][...
Convert pretrained word embedding file in one format to another.
def decorate_callable(self, target): def absorb_mocks(test_case, *args): return target(test_case) should_absorb = not (self.pass_mocks or isinstance(target, type)) result = absorb_mocks if should_absorb else target for patcher in self.patchers: result = patcher(re...
Called as a decorator.
def vport_meta(self, vip): vport_meta = self.meta(vip, 'vport', None) if vport_meta is None: vport_meta = self.meta(vip, 'port', {}) return vport_meta
Get the vport meta, no matter which name was used
def _check_repos(self, repos): self._checking_repos = [] self._valid_repos = [] for repo in repos: worker = self.download_is_valid_url(repo) worker.sig_finished.connect(self._repos_checked) worker.repo = repo self._checking_repos.append(repo)
Check if repodata urls are valid.
def str_fmthdr(self, goid, goobj): go_txt = goid.replace("GO:", "G") if 'mark_alt_id' in self.present and goid != goobj.id: go_txt += 'a' return go_txt
Return hdr line seen inside a GO Term box.
def insert(self, crc, toc): if self._rw_cache: try: filename = '%s/%08X.json' % (self._rw_cache, crc) cache = open(filename, 'w') cache.write(json.dumps(toc, indent=2, default=self._encoder)) cache...
Save a new cache to file
def rssi_bars(self) -> int: rssi_db = self.rssi_db if rssi_db < 45: return 0 elif rssi_db < 60: return 1 elif rssi_db < 75: return 2 elif rssi_db < 90: return 3 return 4
Received Signal Strength Indication, from 0 to 4 bars.
def user_get_websudo(self): url = 'secure/admin/WebSudoAuthenticate.jspa' headers = self.form_token_headers data = { 'webSudoPassword': self.password, } return self.post(path=url, data=data, headers=headers)
Get web sudo cookies using normal http request
def load_interfaces(self, interfaces_dict): if interfaces_dict.get('apilist', {}).get('interfaces', None) is None: raise ValueError("Invalid response for GetSupportedAPIList") interfaces = interfaces_dict['apilist']['interfaces'] if len(interfaces) == 0: raise ValueError(...
Populates the namespace under the instance
def random_sample(self, num_samples, df=None, replace=False, weights=None, random_state=100, axis='row'): if df is None: df = self.dat_to_df() if axis == 'row': axis = 0 if axis == 'col': axis = 1 df = self.export_df() df = df.sample(n=num_samples, replace=replace, weights=weights,...
Return random sample of matrix.
def UpdateClientsFromFleetspeak(clients): if not fleetspeak_connector.CONN or not fleetspeak_connector.CONN.outgoing: return id_map = {} for client in clients: if client.fleetspeak_enabled: id_map[fleetspeak_utils.GRRIDToFleetspeakID(client.client_id)] = client if not id_map: return res = fl...
Updates ApiClient records to include info from Fleetspeak.
def _flattenPortsSide(side: List[LNode]) -> List[LNode]: new_side = [] for i in side: for new_p in flattenPort(i): new_side.append(new_p) return new_side
Flatten hierarchical ports on node side
def switch_state(context, ain): context.obj.login() actor = context.obj.get_actor_by_ain(ain) if actor: click.echo("State for {} is: {}".format(ain,'ON' if actor.get_state() else 'OFF')) else: click.echo("Actor not found: {}".format(ain))
Get an actor's power state
def canonical_names(self): cns = [] for r_id in relation_ids('identity-service'): for unit in related_units(r_id): rdata = relation_get(rid=r_id, unit=unit) for k in rdata: if k.startswith('ssl_key_'): cns.append(k.l...
Figure out which canonical names clients will access this service.
def example_splits(url_file, all_files): def generate_hash(inp): h = hashlib.sha1() h.update(inp) return h.hexdigest() all_files_map = {f.split("/")[-1]: f for f in all_files} urls = [line.strip().encode("utf-8") for line in tf.gfile.Open(url_file)] filelist = [] for url in urls: url_hash = ge...
Generate splits of the data.
def iterkeys(self): def _iterkeys(bin): for item in bin: yield item.key for bin in self.bins: yield _iterkeys(bin)
An iterator over the keys of each bin.
def getCorner(index,top,left,expand=0,y=206): x = str(-(expand+old_div(ARENA_WIDTH,2))) if left else str(expand+old_div(ARENA_WIDTH,2)) z = str(-(expand+old_div(ARENA_BREADTH,2))) if top else str(expand+old_div(ARENA_BREADTH,2)) return 'x'+index+'="'+x+'" y'+index+'="' +str(y)+'" z'+index+'="'+z+'"'
Return part of the XML string that defines the requested corner
def _is_socket(cls, stream): try: fd = stream.fileno() except ValueError: return False sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_RAW) try: sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE) except socket.error as ex: if e...
Check if the given stream is a socket.
def _linearInterpolationTransformMatrix(matrix1, matrix2, value): return tuple(_interpolateValue(matrix1[i], matrix2[i], value) for i in range(len(matrix1)))
Linear, 'oldstyle' interpolation of the transform matrix.
def _term_str(term: TermAtom) -> str: if is_operation(term): return term.name + '(' elif is_symbol_wildcard(term): return '*{!s}'.format(term.__name__) elif isinstance(term, Wildcard): return '*{!s}{!s}'.format(term.min_count, (not term.fixed_size) and '+' or '') elif term == Wil...
Return a string representation of a term atom.
def getPlaintextLen(self, ciphertext): completeCiphertextHeader = (len(ciphertext) >= 16) if completeCiphertextHeader is False: raise RecoverableDecryptionError('Incomplete ciphertext header.') ciphertext_header = ciphertext[:16] L = self._ecb_enc_K1.decrypt(ciphertext_header...
Given a ``ciphertext`` with a valid header, returns the length of the plaintext payload.
def query(self, query, inplace=True): result = self.data.query(query, inplace=inplace) return result
State what you want to keep
def default_values_of(func): signature = inspect.signature(func) return [k for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty or v.kind != inspect.Parameter.POSITIONAL_OR_KEYWORD]
Return the defaults of the function `func`.
def prune_clusters(clusters, index, n=3): torem = set(c for c in clusters if c.size < n) pruned_clusters = [c for c in clusters if c.size >= n] terms_torem = [] for term, clusters in index.items(): index[term] = clusters - torem if len(index[term]) == 0: terms_torem.append(te...
Delete clusters with fewer than n elements.
def _verify_config_dict(self, valid, config, dev_os, key_path=None): if not key_path: key_path = [] for key, value in valid.items(): self._verify_config_key(key, value, valid, config, dev_os, key_path)
Verify if the config dict is valid.
def _str_elem(config, key): _value = config.pop(key, '') if _valid_str(_value): config[key] = _value
Re-adds the value of a specific key in the dict, only in case of valid str value.
def bind_to_provider(self, cls, provider): self._check_class(cls) if provider is None: raise InjectorException('Provider cannot be None, key=%s' % cls) self._bindings[cls] = provider logger.debug('Bound %s to a provider %s', cls, provider) return self
Bind a class to a callable instance provider executed for each injection.
def inject_pid(self, data): pid_value = data.pop('pid', None) if pid_value: pid_field = current_app.config['PIDSTORE_RECID_FIELD'] data.setdefault(pid_field, pid_value) return data
Inject context PID in the RECID field.
def make_file_system_tree(root_folder, _parent=None): root_node = Node(os.path.basename(root_folder), _parent) root_node.path = root_folder for item in os.listdir(root_folder): item_path = os.path.join(root_folder, item) if os.path.isfile(item_path): file_node = Node(os.path.base...
This function makes a tree from folders and files.
def datedif(ctx, start_date, end_date, unit): start_date = conversions.to_date(start_date, ctx) end_date = conversions.to_date(end_date, ctx) unit = conversions.to_string(unit, ctx).lower() if start_date > end_date: raise ValueError("Start date cannot be after end date") if unit == 'y': ...
Calculates the number of days, months, or years between two dates.
def items(self): if hasattr(self, '_items'): return self.filter_items(self._items) self._items = self.get_items() return self.filter_items(self._items)
access for filtered items
def _get_headers(self, resource): if type(resource) == file: resource.seek(0) reader = csv.reader(resource) elif isinstance(resource, basestring): result = six.moves.urllib.parse.urlparse(resource) if result.scheme in ['http', 'https']: wit...
Get CSV file headers from the provided resource.
def register_workflow(self, name, workflow): assert name not in self.workflows self.workflows[name] = workflow
Register an workflow to be showed in the workflows list.
def _update_conda_devel(): conda_bin = _get_conda_bin() channels = _get_conda_channels(conda_bin) assert conda_bin, "Could not find anaconda distribution for upgrading bcbio" subprocess.check_call([conda_bin, "install", "--quiet", "--yes"] + channels + ["bcbio-nextgen>=%s" % v...
Update to the latest development conda package.
def id_to_symbol(self, entrez_id): entrez_id = str(entrez_id) if entrez_id not in self.ids_to_symbols: m = 'Could not look up symbol for Entrez ID ' + entrez_id raise Exception(m) return self.ids_to_symbols[entrez_id]
Gives the symbol for a given entrez id)
def p2pardict(self, p): d = {} N = self.Nstars i = 0 for s in self.systems: age, feh, dist, AV = p[i+N[s]:i+N[s]+4] for j in xrange(N[s]): l = '{}_{}'.format(s,j) mass = p[i+j] d[l] = [mass, age, feh, dist, AV] ...
Given leaf labels, turns parameter vector into pardict
def write_bubble(self, filename:str): from bubbletools import converter converter.tree_to_bubble(self, filename)
Write in given filename the lines of bubble describing this instance
def _log(self, fname, txt, prg=''): if os.sep not in fname: fname = self.log_folder + os.sep + fname delim = ',' q = '"' dte = TodayAsString() usr = GetUserName() hst = GetHostName() i = self.session_id if prg == '': prg = 'cls_log....
logs an entry to fname along with standard date and user details
def load_modules(self, data=None, proxy=None): self.functions = self.wrapper self.utils = salt.loader.utils(self.opts) self.serializers = salt.loader.serializers(self.opts) locals_ = salt.loader.minion_mods(self.opts, utils=self.utils) self.states = salt.loader.states(self.opts, ...
Load up the modules for remote compilation via ssh
def _thread_listen(self): while self._running: try: rest = requests.get(URL_LISTEN.format(self._url), timeout=self._timeout) if rest.status_code == 200: self._queue.put(rest.json()) else: ...
The main &listen loop.
def _POUpdateBuilder(env, **kw): import SCons.Action from SCons.Tool.GettextCommon import _POFileBuilder action = SCons.Action.Action(_update_or_init_po_files, None) return _POFileBuilder(env, action=action, target_alias='$POUPDATE_ALIAS')
Create an object of `POUpdate` builder
def fit(self, data): _raise_error_if_not_sframe(data, "data") fitted_state = {} feature_columns = _internal_utils.get_column_names(data, self._exclude, self._features) if not feature_columns: raise RuntimeError("No valid feature columns specified in transformation.") ...
Fits the transformer using the given data.
def _add_referrer(cls, request: Request, url_record: URLRecord): if url_record.parent_url.startswith('https://') and \ url_record.url_info.scheme == 'http': return request.fields['Referer'] = url_record.parent_url
Add referrer URL to request.