code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def parse(cls, requester, entry): if not type(entry) is dict: return entry for key_to_parse, cls_to_parse in six.iteritems(cls.parser): if key_to_parse in entry: entry[key_to_parse] = cls_to_parse.parse( requester, entry[key_to_parse] ...
Turns a JSON object into a model instance.
def logout(self): from flask_login import logout_user, current_user if not current_user.is_authenticated: return True user = current_user events.logout_event.send(user) logout_user() app = current_app._get_current_object() identity_changed.send(app, id...
Logout user and emit event.
def clean_limit(self): "Ensure given limit is less than default if defined" limit = self.cleaned_data.get('limit', None) if (settings.SELECTABLE_MAX_LIMIT is not None and (not limit or limit > settings.SELECTABLE_MAX_LIMIT)): limit = settings.SELECTABLE_MAX_LIMIT ...
Ensure given limit is less than default if defined
def access_token(self): title = '%s.access_token' % self.__class__.__name__ from time import time import requests request_kwargs = { 'url': self.token_endpoint, 'data': { 'client_id': self.client_id, 'client_secret': self.client_sec...
a method to acquire an oauth access token
def dump_data(request): app_label = request.GET.get('app_label', []) if app_label: app_label = app_label.split(',') return dump_to_response(request, app_label=app_label, exclude=settings.SMUGGLER_EXCLUDE_LIST)
Exports data from whole project.
def define_options(default_conf): default = {} with open(default_conf, 'rb') as f: exec_in(native_str(f.read()), {}, default) for name, value in default.iteritems(): if name in options: setattr(options, name, value) else: define(name, value)
Define the options from default.conf dynamically
def match_head(subject, pattern): if isinstance(pattern, Pattern): pattern = pattern.expression pattern_head = get_head(pattern) if pattern_head is None: return True if issubclass(pattern_head, OneIdentityOperation): return True subject_head = get_head(subject) assert sub...
Checks if the head of subject matches the pattern's head.
def expand_region(tuple_of_s, a, b, start=0, stop=None): return tuple(expand_slice(s, a, b, start=start, stop=stop) for s in tuple_of_s)
Apply expend_slice on a tuple of slices
def initial_value(self, field_name: str = None): if self._meta.get_field(field_name).get_internal_type() == 'ForeignKey': if not field_name.endswith('_id'): field_name = field_name+'_id' attribute = self._diff_with_initial.get(field_name, None) if not attribute: ...
Get initial value of field when model was instantiated.
def _library_check(self): try: output = yield from gns3server.utils.asyncio.subprocess_check_output("ldd", self._path) except (FileNotFoundError, subprocess.SubprocessError) as e: log.warn("Could not determine the shared library dependencies for {}: {}".format(self._path, e)) ...
Checks for missing shared library dependencies in the IOU image.
def max_texture_limit(self): max_unit_array = (gl.GLint * 1)() gl.glGetIntegerv(gl.GL_MAX_TEXTURE_IMAGE_UNITS, max_unit_array) return max_unit_array[0]
The maximum number of textures available for this graphic card's fragment shader.
def lock_account(self, minutes=30): period = datetime.timedelta(minutes=minutes) self.locked_until = datetime.datetime.utcnow() + period
Lock user account for a period
def flatten(nested): flat_return = list() def __inner_flat(nested,flat): for i in nested: __inner_flat(i, flat) if isinstance(i, list) else flat.append(i) return flat __inner_flat(nested,flat_return) return flat_return
Return a flatten version of the nested argument
def refresh(self, include_fields=None, exclude_fields=None, extra_fields=None): r = self.bugzilla._getbug(self.bug_id, include_fields=include_fields, exclude_fields=exclude_fields, extra_fields=self._bug_fields + (extra_fields or [])) self._update_dict(r)
Refresh the bug with the latest data from bugzilla
def _interp_function(self, y_ip1, y_i, t_ip1, t_i, imt_per): return y_i + (y_ip1 - y_i) / (t_ip1 - t_i) * (imt_per - t_i)
Generic interpolation function used in equation 19 of 2013 report.
def write_cache(self): doc = { '__format__': 1, 'dependencies': self._cache, } with open(self._cache_file, 'w') as f: json.dump(doc, f, sort_keys=True)
Writes the cache to disk as JSON.
def EncodeForCSV(x): "Encodes one value for CSV." k = x.encode('utf-8') if ',' in k or '"' in k: return '"%s"' % k.replace('"', '""') else: return k
Encodes one value for CSV.
def clean(): d = ['build', 'dist', 'scikits.audiolab.egg-info', HTML_DESTDIR, PDF_DESTDIR] for i in d: paver.path.path(i).rmtree() (paver.path.path('docs') / options.sphinx.builddir).rmtree()
Remove build, dist, egg-info garbage.
def refresh(self): self._screen.force_update() self._screen.refresh() self._update(1)
Refresh the list and the screen
def _create_filter_by(self): filter_by = [] for name, values in request.args.copy().lists(): if name not in _SKIPPED_ARGUMENTS: column = _re_column_name.search(name).group(1) if column not in self._model_columns: continue fo...
Transform the json-server filter arguments to model-resource ones.
def create(self, name, data=None): return createPacket(self[name], data) if name in self else None
Creates a new packet with the given definition and raw data.
def format_meta_lines(cls, meta, labels, offset, **kwargs): lines = [] name = meta['package_name'] if 'version' in meta: name += '-' + meta['version'] if 'custom_location' in kwargs: name += ' ({loc})'.format(loc=kwargs['custom_location']) lines.append(nam...
Return all information from a given meta dictionary in a list of lines
def validate(self): if self.stoichiometry_matrix.cols != self.propensities.rows: raise ValueError('There must be a column in stoichiometry matrix ' 'for each row in propensities matrix. ' 'S ({0.rows}x{0.cols}): {0!r} , ' ...
Validates whether the particular model is created properly
def dynacRepresentation(self): if self.plane.val == 'H': p = 0 elif self.plane.val == 'V': p = 1 return ['STEER', [[self.field_strength.val], [p]]]
Return the Dynac representation of this steerer instance.
def batch_call(self, calls): req = self.protocol.create_batch_request() for call_args in calls: req.append(self.protocol.create_request(*call_args)) return self._send_and_handle_reply(req)
Experimental, use at your own peril.
def _extract_table_type(type): if isinstance(type, str): type = type.lower() if type[0:7] == 'binary': table_type = BINARY_TBL elif type[0:6] == 'ascii': table_type = ASCII_TBL else: raise ValueError( "table type string should begin...
Get the numerical table type
def detector_50_Cent(text): keywords = [ "50 Cent", "rap", "hip hop", "Curtis James Jackson III", "Curtis Jackson", "Eminem", "Dre", "Get Rich or Die Tryin'", "G-Unit", "Street King Immortal", "In da Club", "Interscope",...
Determine whether 50 Cent is a topic.
def angle_between_vectors(x, y): first_step = abs(x[0] * y[0] + x[1] * y[1] + x[2] * y[2]) / ( np.sqrt(x[0]**2 + x[1]**2 + x[2]**2) * np.sqrt(y[0]**2 + y[1]**2 + y[2]**2)) second_step = np.arccos(first_step) return (second_step)
Calculate the angle between two vectors x and y.
def process_status(self, helper, sess, check): if check == 'ntp_current_state': ntp_status_int = helper.get_snmp_value(sess, helper, self.oids['oid_ntp_current_state_int']) result = self.check_ntp_status(ntp_status_int) elif check == 'gps_mode': gps_status_int = helpe...
get the snmp value, check the status and update the helper
def getTarget(self, iid): sql = 'select name, path from {} where _id=?'.format(self.TABLE_ITEMS) data = self.db.execute(sql, (iid,)).fetchone() if data: return {'name': data[0], 'path': data[1]} return None
Returns a dictionary containing information about a certain target
def script_exists(self, digest, *digests): return self.execute(b'SCRIPT', b'EXISTS', digest, *digests)
Check existence of scripts in the script cache.
def _config_section(config, section): path = os.path.join(config.get('config_path'), config.get('config_file')) conf = _config_ini(path) return conf.get(section)
Read the configuration file and return a section.
def add(self, domain_accession, domain_type, match_quality): self.matches[domain_type] = self.matches.get(domain_type, {}) self.matches[domain_type][domain_accession] = match_quality
match_quality should be a value between 0 and 1.
def sortJobs(jobTypes, options): longforms = {"med": "median", "ave": "average", "min": "min", "total": "total", "max": "max",} sortField = longforms[options.sortField] if (options.sortCategory == "time" or options.sortCategory == "...
Return a jobTypes all sorted.
def _pca(x, k=2): "Compute PCA of `x` with `k` dimensions." x = x-torch.mean(x,0) U,S,V = torch.svd(x.t()) return torch.mm(x,U[:,:k])
Compute PCA of `x` with `k` dimensions.
def clear_database(self) -> None: self._next_entity_id = 0 self._dead_entities.clear() self._components.clear() self._entities.clear() self.clear_cache()
Remove all Entities and Components from the World.
def cli(ctx, config_file, profile, endpoint_url, output, color, debug): config = Config(config_file) config.get_config_for_profle(profile) config.get_remote_config(endpoint_url) ctx.obj = config.options ctx.obj['output'] = output or config.options['output'] ctx.obj['color'] = color or os.environ...
Alerta client unified command-line tool.
def name_file(lane: int, flowcell: str, sample: str, read: int, undetermined: bool=False, date: dt.datetime=None, index: str=None) -> str: flowcell = f"{flowcell}-undetermined" if undetermined else flowcell date_str = date.strftime('%y%m%d') if date else '171015' index = index ...
Name a FASTQ file following MIP conventions.
def git_hook(error=True): _, files_modified, _ = run("git diff-index --cached --name-only HEAD") options = parse_options() setup_logger(options) if sys.version_info >= (3,): candidates = [f.decode('utf-8') for f in files_modified] else: candidates = [str(f) for f in files_modified] ...
Run pylama after git commit.
def args(self): if self.space.has_basis or isinstance(self.label, SymbolicLabelBase): return (self.label, ) else: return (self.index, )
Tuple containing `label_or_index` as its only element.
def getunzipped(username, repo, thedir): theurl = "https://github.com/" + username + "/" + repo + "/archive/master.zip" name = os.path.join(thedir, 'temp.zip') try: name = urllib.urlretrieve(theurl, name) name = os.path.join(thedir, 'temp.zip') except IOError as e: print("Can't r...
Downloads and unzips a zip file
def as_iframe(self, html_data): srcdoc = html_data.replace('"', "'") return ('<iframe id="{div_id}", srcdoc="{srcdoc}" style="width: {width}; ' 'height: {height};"></iframe>'.format( div_id=self.div_id, srcdoc=srcdoc, width=self...
Build the HTML representation for the mapviz.
def bidcollateral( ctx, collateral_symbol, collateral_amount, debt_symbol, debt_amount, account ): print_tx( ctx.bitshares.bid_collateral( Amount(collateral_amount, collateral_symbol), Amount(debt_amount, debt_symbol), account=account, ) )
Bid for collateral in the settlement fund
def _setSkipRecords(self, skipRec): if type(skipRec) == int or (type(skipRec) == str and skipRec.isdigit()): self._skipRecords = skipRec else: raise FMError, 'Unsupported -skip value (not a number).'
Specifies how many records to skip in the found set
def hmean_int(a, a_min=5778, a_max=1149851): from scipy.stats import hmean return int(round(hmean(np.clip(a, a_min, a_max))))
Harmonic mean of an array, returns the closest int
def format_ubuntu_dialog(df): s = '' for i, record in df.iterrows(): statement = list(split_turns(record.Context))[-1] reply = list(split_turns(record.Utterance))[-1] s += 'Statement: {}\n'.format(statement) s += 'Reply: {}\n\n'.format(reply) return s
Print statements paired with replies, formatted for easy review
def GetLocalU2FInterface(origin=socket.gethostname()): hid_transports = hidtransport.DiscoverLocalHIDU2FDevices() for t in hid_transports: try: return U2FInterface(security_key=hardware.SecurityKey(transport=t), origin=origin) except errors.UnsupportedVersionException: ...
Obtains a U2FInterface for the first valid local U2FHID device found.
def sum(self, axis): axis = self.get_axis_number(axis) if self.dimensions == 2: new_hist = Hist1d else: new_hist = Histdd return new_hist.from_histogram(np.sum(self.histogram, axis=axis), bin_edges=itemgetter(*self.other_axes...
Sums all data along axis, returns d-1 dimensional histogram
def work(): with rq.Connection(create_connection()): worker = rq.Worker(list(map(rq.Queue, listen))) worker.work()
Start an rq worker on the connection provided by create_connection.
def md5_of_file(abspath): chunk_size = 1024 * 1024 m = hashlib.md5() with open(abspath, "rb") as f: while True: data = f.read(chunk_size) if not data: break m.update(data) return m.hexdigest()
Md5 value of a file.
def segment_radii(neurites, neurite_type=NeuriteType.all): def _seg_radii(sec): pts = sec.points[:, COLS.R] return np.divide(np.add(pts[:-1], pts[1:]), 2.0) return map_segments(_seg_radii, neurites, neurite_type)
arithmetic mean of the radii of the points in segments in a collection of neurites
def _join_partner(self, partner: Address): try: self.api.channel_open( self.registry_address, self.token_address, partner, ) except DuplicatedChannelError: pass total_deposit = self._initial_funding_per_partner ...
Ensure a channel exists with partner and is funded in our side
def push_design_documents(self, design_path): for db_name in os.listdir(design_path): if db_name.startswith("__") or db_name.startswith("."): continue db_path = os.path.join(design_path, db_name) doc = self._folder_to_dict(db_path) doc_id = "_desig...
Push the design documents stored in `design_path` to the server
def multipart(body, content_length=0, **header_params): header_params.setdefault('CONTENT-LENGTH', content_length) if header_params and 'boundary' in header_params: if type(header_params['boundary']) is str: header_params['boundary'] = header_params['boundary'].encode() form = parse_mult...
Converts multipart form data into native Python objects
def on_load(target: "EncryptableMixin", context): decrypt, plaintext = decrypt_instance(target) if decrypt: target.plaintext = plaintext
Intercept SQLAlchemy's instance load event.
def _filter_nodes(superclass, all_nodes=_all_nodes): node_names = (node.__name__ for node in all_nodes if issubclass(node, superclass)) return frozenset(node_names)
Filter out AST nodes that are subclasses of ``superclass``.
def _from_dict(cls, _dict): args = {} if 'key' in _dict: args['key'] = _dict.get('key') if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'aggregations' in _dict: args['aggregations'] = [ QueryA...
Initialize a AggregationResult object from a json dictionary.
def _get_users_of_group(config, group): if not group: return set() fas = fmn.rules.utils.get_fas(config) return fmn.rules.utils.get_user_of_group(config, fas, group)
Utility to query fas for users of a group.
def _send(self): self.queue.submit() self.queue_max_timestamp = int(time.time() + self.queue_max_interval) self.current_n_measurements = 0
Send data to Librato.
def _update_subscribers(self, val): self._value = val for callback in self._observer_callbacks: callback(self._address, self._group, val)
Save state value and notify listeners of the change.
def fix_all(override_debug=False, override_all=False): fix_base(True) fix_builtins(override_debug) fix_subprocess(override_debug, override_all) return True
Activate the full compatibility.
def finalize(self): print('{} default sprite names found:'.format(self.total_default)) for name in self.list_default: print(name)
Output the default sprite names found in the project.
def find_default_container(builder, default_container=None, use_biocontainers=None, ): if not default_container and use_biocontainers: default_container = get_container_from_software_requirements( use_biocontainers, ...
Default finder for default containers.
def filter_infinity(self): mask = self.coordinates[:, 2] > self.coordinates[:, 2].min() coords = self.coordinates[mask] colors = self.colors[mask] return PointCloud(coords, colors)
Filter infinite distances from ``PointCloud.``
def config_function(self, token): match = token["match"] function = match.group(2).lower() param = match.group(3) or "" value_type = match.group(6) or "auto" param = param.replace(r"\)", ")") CONFIG_FUNCTIONS = { "base64": self.make_function_value_private, ...
Process a config function from a token
def complement(self): self.check() for key in CMAOptions.defaults(): if key not in self: self[key] = CMAOptions.defaults()[key] return self
add all missing options with their default values
def _get_search_text(self, cli): if self.preview_search(cli) and cli.buffers[self.search_buffer_name].text: return cli.buffers[self.search_buffer_name].text else: return self.get_search_state(cli).text
The text we are searching for.
def deregister_listener(self, member_uuid, listener): self._casts[str(member_uuid)]['listeners'].remove(listener)
Deregister listener for audio group changes of cast uuid.
def reload(self): if time.time() - self.updated > self.ttl: self.force_reload()
Reload catalog if sufficient time has passed
def _from_dict(cls, _dict): args = {} if 'feedback' in _dict: args['feedback'] = [ GetFeedback._from_dict(x) for x in (_dict.get('feedback')) ] return cls(**args)
Initialize a FeedbackList object from a json dictionary.
def __init(self): params = { "f" : "json" } json_dict = self._get(url=self._url, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._pr...
initializes all the properties
def exit(self, exit_code): self.inhibit_autoret = True self.state.options.discard(o.AST_DEPS) self.state.options.discard(o.AUTO_REFS) if isinstance(exit_code, int): exit_code = self.state.solver.BVV(exit_code, self.state.arch.bits) self.state.history.add_event('termin...
Add an exit representing terminating the program.
def main(): filename = pmag.get_named_arg('-f') if not filename: return with open(filename, 'rb+') as f: content = f.read() f.seek(0) f.write(content.replace(b'\r', b'')) f.truncate()
Take out dos problem characters from any file
def assemble_cx(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) ca = CxAssembler(stmts) model_str = ca.make_model() res = {'model': mode...
Assemble INDRA Statements and return CX network json.
def open_magnet(self): if sys.platform.startswith('linux'): subprocess.Popen(['xdg-open', self.magnet], stdout=subprocess.PIPE, stderr=subprocess.PIPE) elif sys.platform.startswith('win32'): os.startfile(self.magnet) elif sys.platform.startswi...
Open magnet according to os.
def getSkeletalTrackingLevel(self, action): fn = self.function_table.getSkeletalTrackingLevel pSkeletalTrackingLevel = EVRSkeletalTrackingLevel() result = fn(action, byref(pSkeletalTrackingLevel)) return result, pSkeletalTrackingLevel
Reads the level of accuracy to which the controller is able to track the user to recreate a skeletal pose
def add_threadlocal(self, **values): with self._lock: self._ensure_threadlocal() self._tpayload.context.update(**values)
Add `values` to current thread's logging context
def response_handler(msg: Dict[str, str]) -> None: from wdom.document import getElementByWdomId id = msg['id'] elm = getElementByWdomId(id) if elm: elm.on_response(msg) else: logger.warning('No such element: wdom_id={}'.format(id))
Handle response sent by browser.
def init_domain_ledger(self): if self.config.primaryStorage is None: genesis_txn_initiator = GenesisTxnInitiatorFromFile( self.genesis_dir, self.config.domainTransactionsFile) return Ledger( CompactMerkleTree( hashStore=self.getHashStor...
This is usually an implementation of Ledger
def chassis(self): self._check_session() status, data = self._rest.get_request('chassis') return data
Get list of chassis known to test session.
def createSections(self): self.soma = h.Section(name='soma', cell=self) self.dend = h.Section(name='dend', cell=self)
Create the sections of the cell.
def initializePage(self): tree = self.uiStructureTREE tree.blockSignals(True) tree.setUpdatesEnabled(False) self.uiStructureTREE.clear() xstruct = self.scaffold().structure() self._structure = xstruct for xentry in xstruct: XScaffoldElementItem...
Initializes the page based on the current structure information.
def remove_accents(value): search = 'ΆΈΉΊΌΎΏάέήίόύώΪϊΐϋΰ' replace = 'ΑΕΗΙΟΥΩαεηιουωΙιιυυ' def replace_accented_character(match): matched = match.group(0) if matched in search: return replace[search.find(matched)] return matched return re.sub(r'[{0}]+'.format(search), ...
Remove accents from characters in the given string.
def _safe_path(filepath, can_be_cwl=False): if filepath in {'.gitignore', '.gitattributes'}: return False if filepath.startswith('.renku'): if can_be_cwl and filepath.endswith('.cwl'): return True return False return True
Check if the path should be used in output.
def iter_parsed_values(self, field: Field) -> Iterable[Tuple[str, Any]]: for key, func in self.parsers.items(): value = func(field) if not value: continue yield key, value
Walk the dictionary of parsers and emit all non-null values.
def absolute(value): try: return abs(valid_numeric(value)) except (ValueError, TypeError): try: return abs(value) except Exception: return ''
Return the absolute value.
def refract(alt_degrees, temperature_C, pressure_mbar): alt = alt_degrees while True: alt1 = alt alt = alt_degrees + refraction(alt, temperature_C, pressure_mbar) converged = abs(alt - alt1) <= 3.0e-5 if converged.all(): break return alt
Given an unrefracted `alt` determine where it will appear in the sky.
def models_from_model(model, include_related=False, exclude=None): if exclude is None: exclude = set() if model and model not in exclude: exclude.add(model) if isinstance(model, ModelType) and not model._meta.abstract: yield model if include_related: ...
Generator of all model in model.
def mk_kwargs(cls, kwargs): ret = {} kws = ['row_factory', 'body', 'parent'] for k in kws: if k in kwargs: ret[k] = kwargs.pop(k) return ret
Pop recognized arguments from a keyword list.
def loadFromFile(self, filename): file = open(filename, 'rb') try: wsdl = self.loadFromStream(file) finally: file.close() return wsdl
Return a WSDL instance loaded from the given file.
def logout(request): request.response.headers.extend(forget(request)) return {'redirect': request.POST.get('came_from', '/')}
View to forget the user
def serverDirectories(self): directs = [] url = self._url + "/directories" params = { "f" : "json" } res = self._get(url=url, param_dict=params, securityHandler=self._securityHandler, pro...
returns the server directory object in a list
def flatten(items,enter=lambda x:isinstance(x, list)): for x in items: if enter(x): yield from flatten(x) else: yield x
Yield items from any nested iterable; see REF.
def visit_Name(self, node, store_as_param=False, **kwargs): if store_as_param or node.ctx == 'param': self.symbols.declare_parameter(node.name) elif node.ctx == 'store': self.symbols.store(node.name) elif node.ctx == 'load': self.symbols.load(node.name)
All assignments to names go through this function.
def _BuildHttpRoutingMap(self, router_cls): if not issubclass(router_cls, api_call_router.ApiCallRouter): raise ValueError("Router has to be an instance of ApiCallRouter.") routing_map = routing.Map() for _, metadata in iteritems(router_cls.GetAnnotatedMethods()): for http_method, path, unused_o...
Builds a werkzeug routing map out of a given router class.
def _getMessage(session, txid): while True: if txid in session.messages: msg = session.messages[txid] del session.messages[txid] return msg else: try: nextMessage = session.queue.get(timeout=100) except queue.Empty: ...
Getting message associated with txid
def find_binary(self, binary): if os.path.exists(binary): return binary binary_name = os.path.basename(binary) search_paths = os.environ['PATH'].split(':') default_paths = [ '/usr/bin', '/bin' '/usr/local/bin', '/usr/sbin', ...
Scan and return the first path to a binary that we can find
def listen(self): self.validate_listeners() with ARBITRATOR.condition: while self.connected: ARBITRATOR.condition.wait() if not self.run_queues(): break
Listen for changes in all registered listeners.
def evaluate_single_config( hparams, sampling_temp, max_num_noops, agent_model_dir, eval_fn=_eval_fn_with_learner ): tf.logging.info("Evaluating metric %s", get_metric_name( sampling_temp, max_num_noops, clipped=False )) eval_hparams = trainer_lib.create_hparams(hparams.base_algo_params) env = set...
Evaluate the PPO agent in the real environment.
def bounds_handler(ctx, param, value): retval = from_like_context(ctx, param, value) if retval is None and value is not None: try: value = value.strip(", []") retval = tuple(float(x) for x in re.split(r"[,\s]+", value)) assert len(retval) == 4 return retva...
Handle different forms of bounds.