Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
200
def find_slot(self, wanted, slots=None): for slot in self.find_slots(wanted, slots): return slot return None
Searches the given slots or, if not given, active hotbar slot, hotbar, inventory, open window in this order. Args: wanted: function(Slot) or Slot or itemID or (itemID, metadata) Returns: Optional[Slot]: The first slot containing the item or N...
201
def on_open(self): filename, filter = QtWidgets.QFileDialog.getOpenFileName( self, _()) if filename: self.open_file(filename)
Shows an open file dialog and open the file if the dialog was accepted.
202
def setColumnCount( self, count ): super(XColorTreeWidget, self).setColumnCount(count) header = self.header() header.setResizeMode(0, header.Stretch) for i in range(1, count): header.setResizeMode(i, header.Fixed)
Sets the number of columns used for this tree widget, updating the \ column resizing modes to stretch the first column. :param count | <int>
203
def add_unique_rule(self, rule, opname, arg_count, customize): if rule not in self.new_rules: self.new_rules.add(rule) self.addRule(rule, nop_func) customize[opname] = arg_count pass return
Add rule to grammar, but only if it hasn't been added previously opname and stack_count are used in the customize() semantic the actions to add the semantic action rule. Stack_count is used in custom opcodes like MAKE_FUNCTION to indicate how many arguments it has. Often it i...
204
def ParseFromUnicode(self, value): precondition.AssertType(value, Text) value = value.strip() super(ClientURN, self).ParseFromUnicode(value) match = self.CLIENT_ID_RE.match(self._string_urn) if not match: raise type_info.TypeValueError("Client urn malformed: %s" % value) clientid =...
Parse a string into a client URN. Convert case so that all URNs are of the form C.[0-9a-f]. Args: value: string value to parse
205
def get_matrix(self, x1, x2=None): x1 = self.parse_samples(x1) if x2 is None: return self.kernel.get_value(x1) x2 = self.parse_samples(x2) return self.kernel.get_value(x1, x2)
Get the covariance matrix at a given set or two of independent coordinates. :param x1: ``(nsamples,)`` or ``(nsamples, ndim)`` A list of samples. :param x2: ``(nsamples,)`` or ``(nsamples, ndim)`` (optional) A second list of samples. If this is given, the cross covarian...
206
def update(self, model_alias, code=, name=None, order=None, display_filter=None): model_alias = self.get_model_alias(model_alias) for item in self.tabs[model_alias]: if item.code != code: continue if name: item.name = name if o...
Update given tab :param model_alias: :param code: :param name: :param order: :param display_filter: :return:
207
def _warn_deprecated_outside_JSONField(self): if not isinstance(self, JSONField) and not self.warned: warnings.warn( "Deprecated. JSONifiable fields should derive from JSONField ({name})".format(name=self.name), DeprecationWarning, stackleve...
Certain methods will be moved to JSONField. This warning marks calls when the object is not derived from that class.
208
def delete(self, dict_name): conn = redis.Redis(connection_pool=self.pool) script = conn.register_script() res = script(keys=[self._lock_name, self._namespace(dict_name), self._namespace(dict_name) + ], args=[sel...
Delete an entire dictionary. This operation on its own is atomic and does not require a session lock, but a session lock is honored. :param str dict_name: name of the dictionary to delete :raises rejester.exceptions.LockError: if called with a session lock, but the system doe...
209
async def sign_url(self, url, method=HASH): token = await self.get_token() if method == self.QUERY: return patch_qs(url, { settings.WEBVIEW_TOKEN_KEY: token, }) elif method == self.HASH: hash_id = 5 p = list(urlparse(url)...
Sign an URL with this request's auth token
210
def startProducing(self, consumer): self._task = self._cooperate(self._writeloop(consumer)) d = self._task.whenDone() def maybeStopped(reason): reason.trap(task.TaskStopped) return defer.Deferred() d.addCallbacks(lambda ignored: ...
Start a cooperative task which will read bytes from the input file and write them to C{consumer}. Return a L{Deferred} which fires after all bytes have been written. @param consumer: Any L{IConsumer} provider
211
def _load_features_from_array(self, features): self.feature_images = np.load(features) self.feature_names = range(self.feature_images.shape[1])
Load feature data from a 2D ndarray on disk.
212
def register_seo_admin(admin_site, metadata_class): if metadata_class._meta.use_sites: path_admin = SitePathMetadataAdmin model_instance_admin = SiteModelInstanceMetadataAdmin model_admin = SiteModelMetadataAdmin view_admin = SiteViewMetadataAdmin else: path_admin =...
Register the backends specified in Meta.backends with the admin.
213
def draw_to_notebook(layers, **kwargs): from IPython.display import Image layers = (layers.get_all_layers() if hasattr(layers, ) else layers) dot = make_pydot_graph(layers, **kwargs) return Image(dot.create_png())
Draws a network diagram in an IPython notebook :parameters: - layers : list or NeuralNet instance List of layers or the neural net to draw. - **kwargs : see the docstring of make_pydot_graph for other options
214
def is_integer(self, value, strict=False): if value is not None: if isinstance(value, numbers.Number): return value = stringify(value) if value is not None and value.isnumeric(): return self.shout(, strict, value)
if value is an integer
215
def post(method, hmc, uri, uri_parms, body, logon_required, wait_for_completion): assert wait_for_completion is True cpc_oid = uri_parms[0] try: cpc = hmc.cpcs.lookup_by_oid(cpc_oid) except KeyError: raise InvalidResourceError(method, uri) ...
Operation: Create Hipersocket (requires DPM mode).
216
def sqlalch_datetime(dt): if isinstance(dt, str): return datetime.strptime(dt, "%Y-%m-%d %H:%M:%S.%f").replace(tzinfo=UTC) if dt.tzinfo is not None and dt.tzinfo.utcoffset(dt) is not None: return dt.astimezone(UTC) return dt.replace(tzinfo=UTC)
Convert a SQLAlchemy datetime string to a datetime object.
217
def is_parent_of_gradebook(self, id_, gradebook_id): if self._catalog_session is not None: return self._catalog_session.is_parent_of_catalog(id_=id_, catalog_id=gradebook_id) return self._hierarchy_session.is_parent(id_=gradebook_id, parent_id=id_)
Tests if an ``Id`` is a direct parent of a gradebook. arg: id (osid.id.Id): an ``Id`` arg: gradebook_id (osid.id.Id): the ``Id`` of a gradebook return: (boolean) - ``true`` if this ``id`` is a parent of ``gradebook_id,`` ``false`` otherwise raise: NotFound - ``gr...
218
def _normal_model(self, beta): Y = np.array(self.data[self.max_lag:]) z = np.array([self.latent_variables.z_list[k].prior.transform(beta[k]) for k in range(beta.shape[0])]) if self.ar != 0: mu = np.matmul(np.transpose(self.X),z[:-self.family_z_no-se...
Creates the structure of the model (model matrices etc) for a Normal family ARIMA model. Parameters ---------- beta : np.ndarray Contains untransformed starting values for the latent variables Returns ---------- mu : np.ndarray Contains t...
219
def find_period(data, min_period=0.2, max_period=32.0, coarse_precision=1e-5, fine_precision=1e-9, periodogram=Lomb_Scargle, period_jobs=1): if min_period >= max_period: return min_period coarse_period = periodogram(data, coarse_preci...
find_period(data, min_period=0.2, max_period=32.0, coarse_precision=1e-5, fine_precision=1e-9, periodogram=Lomb_Scargle, period_jobs=1) Returns the period of *data* according to the given *periodogram*, searching first with a coarse precision, and then a fine precision. **Parameters** data : array-li...
220
def resolve_compound_variable_fields(dbg, thread_id, frame_id, scope, attrs): var = getVariable(dbg, thread_id, frame_id, scope, attrs) try: _type, _typeName, resolver = get_type(var) return _typeName, resolver.get_dictionary(var) except: pydev_log.exception(, thre...
Resolve compound variable in debugger scopes by its name and attributes :param thread_id: id of the variable's thread :param frame_id: id of the variable's frame :param scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME :param attrs: after reaching the proper scope, we have to get the attributes unt...
221
def neural_gpu_body(inputs, hparams, name=None): with tf.variable_scope(name, "neural_gpu"): def step(state, inp): x = tf.nn.dropout(state, 1.0 - hparams.dropout) for layer in range(hparams.num_hidden_layers): x = common_layers.conv_gru( x, (hparams.kernel_height, hparams.ker...
The core Neural GPU.
222
def create_asset_browser(self, ): assetbrws = ListBrowser(4, headers=[, , , ]) self.asset_browser_vbox.insertWidget(0, assetbrws) return assetbrws
Create the asset browser This creates a list browser for assets and adds it to the ui :returns: the created borwser :rtype: :class:`jukeboxcore.gui.widgets.browser.ListBrowser` :raises: None
223
def drop_namespace_by_url(self, url: str) -> None: namespace = self.get_namespace_by_url(url) self.session.query(NamespaceEntry).filter(NamespaceEntry.namespace == namespace).delete() self.session.delete(namespace) self.session.commit()
Drop the namespace at the given URL. Won't work if the edge store is in use. :param url: The URL of the namespace to drop
224
def bayesfactor_pearson(r, n): from scipy.special import gamma def fun(g, r, n): return np.exp(((n - 2) / 2) * np.log(1 + g) + (-(n - 1) / 2) * np.log(1 + (1 - r**2) * g) + (-3 / 2) * np.log(g) + - n / (2 * g)) integr = quad(fun, 0, np.inf...
Bayes Factor of a Pearson correlation. Parameters ---------- r : float Pearson correlation coefficient n : int Sample size Returns ------- bf : str Bayes Factor (BF10). The Bayes Factor quantifies the evidence in favour of the alternative hypothesis....
225
def find_by_any(self, identifier, how): if "i" in how: match = self.find_by_id(identifier) if match: return match if "l" in how: match = self.find_by_localpath(identifier) if match: return match if "c" in ho...
how should be a string with any or all of the characters "ilc"
226
def initialize_repository(path, spor_dir=): path = pathlib.Path(path) spor_path = path / spor_dir if spor_path.exists(): raise ValueError(.format(spor_path)) spor_path.mkdir() return Repository(path, spor_dir)
Initialize a spor repository in `path` if one doesn't already exist. Args: path: Path to any file or directory within the repository. spor_dir: The name of the directory containing spor data. Returns: A `Repository` instance. Raises: ValueError: A repository already exists at `pat...
227
def close(self): if self.ipmi_session: self.ipmi_session.unregister_keepalive(self.keepaliveid) if self.activated: try: self.ipmi_session.raw_command(netfn=6, command=0x49, data=(1, 1, 0, 0, 0, 0)) ...
Shut down an SOL session,
228
def func_str(func, args=[], kwargs={}, type_aliases=[], packed=False, packkw=None, truncate=False): import utool as ut truncatekw = {} argrepr_list = ([] if args is None else ut.get_itemstr_list(args, nl=False, truncate=truncate, ...
string representation of function definition Returns: str: a representation of func with args, kwargs, and type_aliases Args: func (function): args (list): argument values (default = []) kwargs (dict): kwargs values (default = {}) type_aliases (list): (default = []) ...
229
def valid_flows_array(catchment): return np.array([record.flow for record in catchment.amax_records if record.flag == 0])
Return array of valid flows (i.e. excluding rejected years etc) :param catchment: gauged catchment with amax_records set :type catchment: :class:`floodestimation.entities.Catchment` :return: 1D array of flow values :rtype: :class:`numpy.ndarray`
230
def vars(self): return self.independent_vars + self.dependent_vars + [self.sigmas[var] for var in self.dependent_vars]
:return: Returns a list of dependent, independent and sigma variables, in that order.
231
def add_directories(self, directories, except_blacklisted=True): directories = util.to_absolute_paths(directories) if except_blacklisted: directories = self._remove_blacklisted(directories) self.plugin_directories.update(directories)
Adds `directories` to the set of plugin directories. `directories` may be either a single object or a iterable. `directories` can be relative paths, but will be converted into absolute paths based on the current working directory. if `except_blacklisted` is `True` all `directories` in...
232
def stream(self, model, position): validate_not_abstract(model) if not model.Meta.stream or not model.Meta.stream.get("arn"): raise InvalidStream("{!r} does not have a stream arn".format(model)) stream = Stream(model=model, engine=self) stream.move_to(position=positi...
Create a :class:`~bloop.stream.Stream` that provides approximate chronological ordering. .. code-block:: pycon # Create a user so we have a record >>> engine = Engine() >>> user = User(id=3, email="user@domain.com") >>> engine.save(user) >>> user.ema...
233
def keypoint_scale(keypoint, scale_x, scale_y, **params): x, y, a, s = keypoint return [x * scale_x, y * scale_y, a, s * max(scale_x, scale_y)]
Scales a keypoint by scale_x and scale_y.
234
def get_backend(alias): if alias not in settings.BACKENDS: raise VCSError("Given alias is not recognized! Allowed aliases:\n" "%s" % (alias, pformat(settings.BACKENDS.keys()))) backend_path = settings.BACKENDS[alias] klass = import_class(backend_path) return klass
Returns ``Repository`` class identified by the given alias or raises VCSError if alias is not recognized or backend class cannot be imported.
235
def is_fnmatch_regex(string): is_regex = False regex_chars = [, , ] for c in regex_chars: if string.find(c) > -1: return True return is_regex
Returns True if the given string is considered a fnmatch regular expression, False otherwise. It will look for :param string: str
236
def get_instance(self, payload): return SessionInstance(self._version, payload, service_sid=self._solution[], )
Build an instance of SessionInstance :param dict payload: Payload response from the API :returns: twilio.rest.proxy.v1.service.session.SessionInstance :rtype: twilio.rest.proxy.v1.service.session.SessionInstance
237
async def main(): redis = await create_pool(RedisSettings()) job = await redis.enqueue_job() print(await job.status()) print(await job.result(timeout=5))
> 68362958a244465b9be909db4b7b5ab4 (or whatever)
238
def _endCodeIfNeeded(line, inCodeBlock): assert isinstance(line, str) if inCodeBlock: line = .format(linesep, line.rstrip()) inCodeBlock = False return line, inCodeBlock
Simple routine to append end code marker if needed.
239
def configure(self, cfg, handler, path=""): for name, attr in handler.attributes(): if cfg.get(name) is not None: continue if attr.expected_type not in [list, dict]: cfg[name] = self.set(handler, attr, name, path, cfg) elif ...
Start configuration process for the provided handler Args: cfg (dict): config container handler (config.Handler class): config handler to use path (str): current path in the configuration progress
240
def keep_entry_range(entry, lows, highs, converter, regex): return any( low <= converter(num) <= high for num in regex.findall(entry) for low, high in zip(lows, highs) )
Check if an entry falls into a desired range. Every number in the entry will be extracted using *regex*, if any are within a given low to high range the entry will be kept. Parameters ---------- entry : str lows : iterable Collection of low values against which to compare the entry...
241
def card_names_and_ids(self): b = Board(self.client, self.board_id) cards = b.getCards() card_names_and_ids = [(unidecode(c.name), c.id) for c in cards] return card_names_and_ids
Returns [(name, id), ...] pairs of cards from current board
242
def close(self): if self._buffer: self.flush() self._handle.write(_bgzf_eof) self._handle.flush() self._handle.close()
Flush data, write 28 bytes BGZF EOF marker, and close BGZF file. samtools will look for a magic EOF marker, just a 28 byte empty BGZF block, and if it is missing warns the BAM file may be truncated. In addition to samtools writing this block, so too does bgzip - so this implementation do...
243
def get_sds_by_ip(self,ip): if self.conn.is_ip_addr(ip): for sds in self.sds: for sdsIp in sds.ipList: if sdsIp == ip: return sds raise KeyError("SDS of that name not found") else: raise ValueError("...
Get ScaleIO SDS object by its ip address :param name: IP address of SDS :return: ScaleIO SDS object :raise KeyError: No SDS with specified ip found :rtype: SDS object
244
def mass_fraction_within_radius(self, kwargs_lens, center_x, center_y, theta_E, numPix=100): x_grid, y_grid = util.make_grid(numPix=numPix, deltapix=2.*theta_E / numPix) x_grid += center_x y_grid += center_y mask = mask_util.mask_sphere(x_grid, y_grid, center_x, center_y, theta_...
computes the mean convergence of all the different lens model components within a spherical aperture :param kwargs_lens: lens model keyword argument list :param center_x: center of the aperture :param center_y: center of the aperture :param theta_E: radius of aperture :return: l...
245
def isometric_load(script, AbsName="TEMP3D.abs"): filter_xml = .join([ , , % AbsName, , , , , ]) util.write_filter(script, filter_xml) return None
Isometric parameterization: Load Abstract Domain
246
def patches(self, dwn, install, comp_sum, uncomp_sum): dwnp, installp, comp_sump, uncomp_sump = ([] for i in range(4)) for d, i, c, u in zip(dwn, install, comp_sum, uncomp_sum): if "_slack" + slack_ver() in i: dwnp.append(d) dwn.remove(d) ...
Seperates packages from patches/ directory
247
def inject_url_defaults(self, endpoint, values): funcs = self.url_default_functions.get(None, ()) if in endpoint: bp = endpoint.rsplit(, 1)[0] funcs = chain(funcs, self.url_default_functions.get(bp, ())) for func in funcs: func(endpoint, values)
Injects the URL defaults for the given endpoint directly into the values dictionary passed. This is used internally and automatically called on URL building. .. versionadded:: 0.7
248
async def forget(request, response): identity_policy = request.config_dict.get(IDENTITY_KEY) if identity_policy is None: text = ("Security subsystem is not initialized, " "call aiohttp_security.setup(...) first") raise web.HTTPInternalServerError(r...
Forget previously remembered identity. Usually it clears cookie or server-side storage to forget user session.
249
def _parse_array(stream): logger.debug("parsing array") arr = [] while True: c = stream.read(1) if c in _GDB_MI_VALUE_START_CHARS: stream.seek(-1) val = _parse_val(stream) arr.append(val) elif c in _WHITESPACE: pass elif ...
Parse an array, stream should be passed the initial [ returns: Parsed array
250
def _classify_move_register(self, regs_init, regs_fini, mem_fini, written_regs, read_regs): matches = [] regs_init_inv = self._invert_dictionary(regs_init) for dst_reg, dst_val in regs_fini.items(): if dst_reg not in written_regs: cont...
Classify move-register gadgets.
251
def parse(cls, args): try: (options, args) = cls.optparser.parse_args(args) if options.db_tap_id is None: raise ParseError("db_tap_id is required", cls.optparser.format_help()) if options.query is None and options.scr...
Parse command line arguments to construct a dictionary of command parameters that can be used to create a command Args: `args`: sequence of arguments Returns: Dictionary that can be used in create method Raises: ParseError: when the arguments are no...
252
def dump_artifact(obj, path, filename=None): p_sha1 = None if not os.path.exists(path): os.makedirs(path, mode=0o700) else: p_sha1 = hashlib.sha1() p_sha1.update(obj.encode(encoding=)) if filename is None: fd, fn = tempfile.mkstemp(dir=path) else: fn = ...
Write the artifact to disk at the specified path Args: obj (string): The string object to be dumped to disk in the specified path. The artifact filename will be automatically created path (string): The full path to the artifacts data directory. filename (string, optional): Th...
253
def parse_args(self, argv=None): arg_input = shlex.split(argv) if argv is not None else None self.get_or_create_session() return self.argparser.parse_args(arg_input)
Return an argparse.Namespace of the argv string or sys.argv if argv is None.
254
def _get_base_url(request): if request.is_secure(): base_url = else: base_url = base_url %= request.META[] return base_url
Construct a base URL, given a request object. This comprises the protocol prefix (http:// or https://) and the host, which can include the port number. For example: http://www.openquake.org or https://www.openquake.org:8000.
255
def split_certificate(certificate_path, destination_folder, password=None): try: p = subprocess.Popen( ["openssl", "version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE ) sout, serr = p.communicate() openssl_executable_version = sout.decode().lower() ...
Splits a PKCS12 certificate into Base64-encoded DER certificate and key. This method splits a potentially password-protected `PKCS12 <https://en.wikipedia.org/wiki/PKCS_12>`_ certificate (format ``.p12`` or ``.pfx``) into one certificate and one key part, both in `pem <https://en.wikipedia.org/wiki/X.5...
256
def map_sprinkler(self, sx, sy, watered_crop=, watered_field=, dry_field=, dry_crop=): maplist = [list(s) for s in self.maplist] for y, row in enumerate(maplist): for x, cell in enumerate(row): if sprinkler_reaches_cell(x, y, sx, sy, self.r): ...
Return a version of the ASCII map showing reached crop cells.
257
def search(self, cond): if cond in self._query_cache: return self._query_cache.get(cond, [])[:] docs = [doc for doc in self.all() if cond(doc)] self._query_cache[cond] = docs return docs[:]
Search for all documents matching a 'where' cond. :param cond: the condition to check against :type cond: Query :returns: list of matching documents :rtype: list[Element]
258
def diff_archives(archive1, archive2, verbosity=0, interactive=True): util.check_existing_filename(archive1) util.check_existing_filename(archive2) if verbosity >= 0: util.log_info("Comparing %s with %s ..." % (archive1, archive2)) res = _diff_archives(archive1, archive2, verbosity=verbosit...
Print differences between two archives.
259
def get_question_mdata(): return { : { : { : , : str(DEFAULT_LANGUAGE_TYPE), : str(DEFAULT_SCRIPT_TYPE), : str(DEFAULT_FORMAT_TYPE), }, : { : , : str(DEFAULT_LANGUAGE_TYPE...
Return default mdata map for Question
260
def _remove_call(self, real_time, call): try: (delayed_call, calls) = self._buckets[real_time] except KeyError: return calls.remove(call) if not calls: del self._buckets[real_time] delayed_call.cancel...
Internal helper. Removes a (possibly still pending) call from a bucket. It is *not* an error of the bucket is gone (e.g. the call has already happened).
261
def install_python_package(self, arch, name=None, env=None, is_dir=True): if name is None: name = self.name if env is None: env = self.get_recipe_env(arch) info(.format(self.name)) with current_directory(self.get_build_dir(arch.arch)): ...
Automate the installation of a Python package (or a cython package where the cython components are pre-built).
262
def walk_links(directory, prefix=, linkbase=None): links = {} try: for child in os.listdir(directory): fullname = os.path.join(directory, child) if os.path.islink(fullname): link_path = os.path.normpath(os.path.join(directory, os.readlink(fullname))) ...
Return all links contained in directory (or any sub directory).
263
def _add_cytomine_cli_args(argparse): argparse.add_argument(*_cytomine_parameter_name_synonyms("host"), dest="host", help="The Cytomine host (without protocol).", required=True) argparse.add_argument(*_cytomine_parameter_name_synonyms("public_key"), ...
Add cytomine CLI args to the ArgumentParser object: cytomine_host, cytomine_public_key, cytomine_private_key and cytomine_verbose. Parameters ---------- argparse: ArgumentParser The argument parser Return ------ argparse: ArgumentParser T...
264
def clean_conf_folder(self, locale): dirname = self.configuration.get_messages_dir(locale) dirname.removedirs_p()
Remove the configuration directory for `locale`
265
def create_user(username): "Create a new user." password = prompt_pass("Enter password") user = User(username=username, password=password) db.session.add(user) db.session.commit()
Create a new user.
266
def admin_tools_render_menu_css(context, menu=None): if menu is None: menu = get_admin_menu(context) context.update({ : , : menu.Media.css, }) return context
Template tag that renders the menu css files,, it takes an optional ``Menu`` instance as unique argument, if not given, the menu will be retrieved with the ``get_admin_menu`` function.
267
def isConnected(self, signal, slot): sig_calls = self._callbacks.get(signal, []) for callback in sig_calls: if callback == slot: return True return False
Returns if the given signal is connected to the inputted slot. :param signal | <variant> slot | <callable> :return <bool> | is connected
268
def community_post_comment_down_create(self, post_id, id, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/votes api_path = "/api/v2/community/posts/{post_id}/comments/{id}/down.json" api_path = api_path.format(post_id=post_id, id=id) return self.call(api_path, m...
https://developer.zendesk.com/rest_api/docs/help_center/votes#create-vote
269
def put_multi(entities): if not entities: return [] adapter, requests = None, [] for entity in entities: if adapter is None: adapter = entity._adapter entity.pre_put_hook() requests.append(PutRequest(entity.key, entity.unindexed_properties, entity)) ke...
Persist a set of entities to Datastore. Note: This uses the adapter that is tied to the first Entity in the list. If the entities have disparate adapters this function may behave in unexpected ways. Warning: You must pass a **list** and not a generator or some other kind of iter...
270
def get_bel_resource_hash(location, hash_function=None): resource = get_bel_resource(location) return hash_names( resource[], hash_function=hash_function )
Get a BEL resource file and returns its semantic hash. :param str location: URL of a resource :param hash_function: A hash function or list of hash functions, like :func:`hashlib.md5` or :code:`hashlib.sha512` :return: The hexadecimal digest of the hash of the values in the resource :rtype: str :ra...
271
def installed(name, pkgs=None, pip_bin=None, requirements=None, bin_env=None, use_wheel=False, no_use_wheel=False, log=None, proxy=None, timeout=None, repo=None, edit...
Make sure the package is installed name The name of the python package to install. You can also specify version numbers here using the standard operators ``==, >=, <=``. If ``requirements`` is given, this parameter will be ignored. Example: .. code-block:: yaml django: ...
272
def _create_bv_circuit(self, bit_map: Dict[str, str]) -> Program: unitary, _ = self._compute_unitary_oracle_matrix(bit_map) full_bv_circuit = Program() full_bv_circuit.defgate("BV-ORACLE", unitary) full_bv_circuit.inst(X(self.ancilla), H(self.ancilla)) full_b...
Implementation of the Bernstein-Vazirani Algorithm. Given a list of input qubits and an ancilla bit, all initially in the :math:`\\vert 0\\rangle` state, create a program that can find :math:`\\vec{a}` with one query to the given oracle. :param Dict[String, String] bit_map: truth-table...
273
def register(self, model_cls): assert issubclass(model_cls, peewee.Model) assert not hasattr(model_cls._meta, ) if model_cls in self: raise RuntimeError("Model already registered") self.append(model_cls) model_cls._meta.database = self.dbm return mode...
Register model(s) with app
274
def DisplayGetter(accessor, *args, **kwargs): short_description = get_pretty_name(accessor) accessor = % accessor getter = Getter(accessor, *args, **kwargs) getter.short_description = short_description return getter
Returns a Getter that gets the display name for a model field with choices.
275
def start_state_manager_watches(self): Log.info("Start state manager watches") statemgr_config = StateMgrConfig() statemgr_config.set_state_locations(configloader.load_state_manager_locations( self.cluster, state_manager_config_file=self.state_manager_config_file, overrides={"heron.stat...
Receive updates to the packing plan from the statemgrs and update processes as needed.
276
def merge_arena(self, mujoco_arena): self.arena = mujoco_arena self.bin_offset = mujoco_arena.bin_abs self.bin_size = mujoco_arena.table_full_size self.bin2_body = mujoco_arena.bin2_body self.merge(mujoco_arena)
Adds arena model to the MJCF model.
277
def ParseTable(table): precondition.AssertIterableType(table, dict) result = rdf_osquery.OsqueryTable() result.header = ParseHeader(table) for row in table: result.rows.append(ParseRow(result.header, row)) return result
Parses table of osquery output. Args: table: A table in a "parsed JSON" representation. Returns: A parsed `rdf_osquery.OsqueryTable` instance.
278
def bestfit(self): try: import statsmodels.api as sm except: raise Exception("statsmodels is required: " \ "please run " \ "pip install statsmodels" ) x=pd.Series(list(range(1,len(self)+1)),index=self.index) x=sm.add_constant(x) model=sm.OLS(self,x) fit=model.fit() vals=fit.params.values...
Returns a series with the bestfit values. Example: Series.bestfit() Returns: series The returned series contains a parameter called 'formula' which includes the string representation of the bestfit line.
279
def rebuild_system(self, override=False, **kwargs): supercell_333 = create_supercell(self.system, **kwargs) discrete = discrete_molecules(self.system, rebuild=supercell_333) coordinates = np.array([], dtype=np.float...
Rebuild molecules in molecular system. Parameters ---------- override : :class:`bool`, optional (default=False) If False the rebuild molecular system is returned as a new :class:`MolecularSystem`, if True, the current :class:`MolecularSystem` is modified.
280
def render_exception_js(self, exception): from .http import JsonResponse response = {} response["error"] = exception.error response["error_description"] = exception.reason return JsonResponse(response, status=getattr(exception, , 400))
Return a response with the body containing a JSON-formatter version of the exception.
281
def set_temperature(self, temp): self.set_service_value( self.thermostat_setpoint, , , temp) self.set_cache_value(, temp)
Set current goal temperature / setpoint
282
def _update_records(self, records, data): data = {k: v for k, v in data.items() if v} records = [dict(record, **data) for record in records] return self._apicall( , domainname=self.domain, dnsrecordset={: records}, ).get(, [])
Insert or update a list of DNS records, specified in the netcup API convention. The fields ``hostname``, ``type``, and ``destination`` are mandatory and must be provided either in the record dict or through ``data``!
283
def get_input_shape(sym, proto_obj): arg_params = proto_obj.arg_dict aux_params = proto_obj.aux_dict model_input_shape = [data[1] for data in proto_obj.model_metadata.get()] data_names = [data[0] for data in proto_obj.model_metadata.get()] inputs = [] for in_shape in model_input_s...
Helper function to obtain the shape of an array
284
def get_program(self, program_resource_name: str) -> Dict: return self.service.projects().programs().get( name=program_resource_name).execute()
Returns the previously created quantum program. Params: program_resource_name: A string of the form `projects/project_id/programs/program_id`. Returns: A dictionary containing the metadata and the program.
285
def _execute_callback_async(self, callback, data): if asyncio.iscoroutine(callback): asyncio.ensure_future( callback(rtm_client=self, web_client=self._web_client, data=data) ) else: asyncio.ensure_future( asyncio.coroutine(call...
Execute the callback asynchronously. If the callback is not a coroutine, convert it. Note: The WebClient passed into the callback is running in "async" mode. This means all responses will be futures.
286
def remove_image_info_cb(self, viewer, channel, image_info): return self.remove_image_cb(viewer, channel.name, image_info.name, image_info.path)
Almost the same as remove_image_cb().
287
def rect(self, x, y, width, height, roundness=0.0, draw=True, **kwargs): path = self.BezierPath(**kwargs) path.rect(x, y, width, height, roundness, self.rectmode) if draw: path.draw() return path
Draw a rectangle from x, y of width, height. :param startx: top left x-coordinate :param starty: top left y-coordinate :param width: height Size of rectangle. :roundness: Corner roundness defaults to 0.0 (a right-angle). :draw: If True draws immediately. :fill: Optiona...
288
def infer(self, **options): descriptor = deepcopy(self.__current_descriptor) if self.__source_inspection.get(): return descriptor if not descriptor.get(): descriptor[] = self.__source_inspection[] if not self.inline and not s...
https://github.com/frictionlessdata/datapackage-py#resource
289
def get(self): if not HAS_SQL: return requests.session() try: conn, c = self.connect() except: log.traceback(logging.DEBUG) return requests.session() session = None try: c.execute() c.execute(.f...
Returns a requests.Session object. Gets Session from sqlite3 cache or creates a new Session.
290
def update(self, instance, condition): item = self.dbi.get(condition) if item is None: return None item.update(instance.as_dict()) self.dbi.update(item, condition) return item.eid
Update the instance to the database :param instance: an instance of modeled data object :param condition: condition evaluated to determine record(s) to update :returns: record id updated or None :rtype: int
291
def get_instance(self, payload): return TranscriptionInstance( self._version, payload, account_sid=self._solution[], recording_sid=self._solution[], )
Build an instance of TranscriptionInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance
292
def content(self): if self.cache_content and self.cached_content: return self.cached_content try: with self._open_dockerfile() as dockerfile: content = b2u(dockerfile.read()) if self.cache_content: self.cached_content ...
:return: string (unicode) with Dockerfile content
293
def decode_offset_commit_response(cls, data): ((correlation_id,), cur) = relative_unpack(, data, 0) ((num_topics,), cur) = relative_unpack(, data, cur) for _ in xrange(num_topics): (topic, cur) = read_short_string(data, cur) ((num_partitions,), cur) = relative_u...
Decode bytes to an OffsetCommitResponse Arguments: data: bytes to decode
294
def create_from_fitsfile(cls, fitsfile): from fermipy.skymap import Map index_map = Map.create_from_fits(fitsfile) mult_map = Map.create_from_fits(fitsfile, hdu=1) ff = fits.open(fitsfile) hpx = HPX.create_from_hdu(ff[0]) mapping_data = dict(ipixs=index_map.count...
Read a fits file and use it to make a mapping
295
def add_raw_code(self, string_or_list): if _is_string(string_or_list): self._GMSH_CODE.append(string_or_list) else: assert isinstance(string_or_list, list) for string in string_or_list: self._GMSH_CODE.append(string) return
Add raw Gmsh code.
296
def dump_dict_to_file(dictionary, filepath): create_dirs( os.path.dirname(filepath) ) with open(filepath, ) as outfile: json.dump(dictionary, outfile) outfile.write()
Dump @dictionary as a line to @filepath.
297
def get_globals(self): if self.shell: globals_ = dict(_initial_globals) else: globals_ = dict(self.current_frame.f_globals) globals_[] = self.db.last_obj if cut is not None: globals_.setdefault(, cut) globals_[] = self.db ...
Get enriched globals
298
def truncate(self, before=None, after=None): if after and before and after < before: raise ValueError() i, j = self.levels[0].slice_locs(before, after) left, right = self.slice_locs(before, after) new_levels = list(self.levels) new_levels[0] = new_levels[0]...
Slice index between two labels / tuples, return new MultiIndex Parameters ---------- before : label or tuple, can be partial. Default None None defaults to start after : label or tuple, can be partial. Default None None defaults to end Returns --...
299
def launch_frozen(in_name, out_name, script_path, frozen_tar_path=None, temp_path=, cache=True, check_script=False, **kw): if (( in kw and isinstance(kw[], (str, unicode))) or ( in kw and isinstance(kw[], (str, unicode))) or ( in kw and isinstance(kw[], (str,...
Freezes a script and then launches it. This function will freeze your python program, and place it on HDFS in 'temp_path'. It will not remove it afterwards as they are typically small, you can easily reuse/debug them, and to avoid any risks involved with removing the file. :param in_name: Input p...