Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
347,300
def check_rotation(rotation): if rotation not in ALLOWED_ROTATION: allowed_rotation = .join(ALLOWED_ROTATION) raise UnsupportedRotation( % (rotation, allowed_rotation))
checks rotation parameter if illegal value raises exception
347,301
def perform_exit(): if SPLUNK_DEBUG: print(.format( rnow())) print(.format( rnow())) worked = True for instance in instances: try: if SPLUNK_DEBUG: print(.format( rnow(), instance)) ...
perform_exit Handling at-the-exit events --------------------------- This will cleanup each worker process which could be in the middle of a request/sleep/block action. This has been tested on python 3 with Celery and single processes.
347,302
def _switch(name, on, **kwargs): s /etc is mounted read-only and should point to a root directory where jail jail = kwargs.get(, ) chroot = kwargs.get(, ).rstrip() if not available(name, jail): return False rcvar = _get_rcv...
Switch on/off service start at boot. .. versionchanged:: 2016.3.4 Support for jail (representing jid or jail name) and chroot keyword argument in kwargs. chroot should be used when jail's /etc is mounted read-only and should point to a root directory where jail's /etc is mounted read-write.
347,303
def area_lfom_orifices_top(FLOW,HL_LFOM): return ((FLOW*width_stout(HL_LFOM*u.m,HL_LFOM*u.m-0.5*dist_center_lfom_rows(FLOW,HL_LFOM)).magnitude * dist_center_lfom_rows(FLOW,HL_LFOM).magnitude))
Estimate the orifice area corresponding to the top row of orifices. Another solution method is to use integration to solve this problem. Here we use the width of the stout weir in the center of the top row to estimate the area of the top orifice
347,304
def _git_diff(self): if self._diff_dict is None: result_dict = dict() for diff_str in self._get_included_diff_results(): diff_dict = self._parse_diff_str(diff_str) for src_path in diff_dict.keys(): ...
Run `git diff` and returns a dict in which the keys are changed file paths and the values are lists of line numbers. Guarantees that each line number within a file is unique (no repeats) and in ascending order. Returns a cached result if called multiple times. Raises a...
347,305
def default_username_algo(email): return smart_text(username)
Generate username for the Django user. :arg str/unicode email: the email address to use to generate a username :returns: str/unicode
347,306
def load_cli(subparsers): for command_name in available_commands(): module = .format(__package__, command_name) loader, description = _import_loader(module) parser = subparsers.add_parser(command_name, description=description) command = loa...
Given a parser, load the CLI subcommands
347,307
def gen_weights(self, f_target): x_track = self.cs.rollout() psi_track = self.gen_psi(x_track) self.w = np.zeros((self.dmps, self.bfs)) for d in range(self.dmps): k = 1. for b in range(self.bfs): numer = np...
Generate a set of weights over the basis functions such that the target forcing term trajectory is matched. f_target np.array: the desired forcing term trajectory
347,308
def SecurityCheck(self, func, request, *args, **kwargs): request.user = u"" authorized = False try: auth_type, authorization = request.headers.get("Authorization", " ").split(" ", 1) if auth_type == "Basic": authorization_string...
Wrapping function.
347,309
def _delete_widget_content(sender, instance, **kwargs): if not issubclass(sender, WidgetContentModel): return wcs = WidgetContent.objects.filter( content_pk=instance.pk, content_model=( % instance.__class__).replace("<class >", )) for wc in wcs: logger.debug(%wc) ...
delete the widget content instance when a WidgetContentModel is deleted
347,310
def send(message, asynchronous=False, ip_pool=None, send_at=None, api_url=None, api_version=None, api_key=None, **kwargs): reject*subjectHifrom_emailtest@example.comtoemailrecv@example.comtypeto if in kwargs: salt.utils.versions.warn_unti...
Send out the email using the details from the ``message`` argument. message The information on the message to send. This argument must be sent as dictionary with at fields as specified in the Mandrill API documentation. asynchronous: ``False`` Enable a background sending mode t...
347,311
def validate_query_structure(query): query_dict = dict(query) filters = query_dict.pop(, None) if filters: try: f = json.loads(filters) except ValueError: msg = raise JsonValidaitonError(msg) else: query_dict[] = f try: ...
Validate query arguments in list request. :param query: mapping with pagination and filtering information
347,312
def f_set_single(self, name, item): if type(item) in [SpikeMonitor, StateMonitor, PopulationRateMonitor]: if self.v_stored: self._logger.warning( ) self._extract_monitor_data(item) ...
To add a monitor use `f_set_single('monitor', brian_monitor)`. Otherwise `f_set_single` works similar to :func:`~pypet.parameter.Result.f_set_single`.
347,313
def deterministic(__func__=None, **kwds): def instantiate_n(__func__): junk, parents = _extract( __func__, kwds, keys, , probe=False) return Deterministic(parents=parents, **kwds) keys = [] instantiate_n.kwds = kwds if __func__: return instantiate_n(__func__) ...
Decorator function instantiating deterministic variables. Usage: @deterministic def B(parent_name = ., ...) return baz(parent_name, ...) @deterministic(trace = trace_object) def B(parent_name = ., ...) return baz(parent_name, ...) where baz returns the variable B's value condition...
347,314
def translations(self, **kwargs): path = self._get_id_path() response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the translations for a specific movie id. Args: append_to_response: (optional) Comma separated, any movie method. Returns: A dict representation of the JSON returned from the API.
347,315
def mean_squared_error(true, pred): result = tf.reduce_sum( tf.squared_difference(true, pred)) / tf.to_float(tf.size(pred)) return result
L2 distance between tensors true and pred. Args: true: the ground truth image. pred: the predicted image. Returns: mean squared error between ground truth and predicted image.
347,316
def printer(self): if not self._has_loaded: self.load() if not self._printer_name: raise exceptions.ConfigSectionMissingError() if not self._printer: self._printer = getattr(printer, self._printer_name)(**self._printer_conf...
Returns a printer that was defined in the config, or throws an exception. This method loads the default config if one hasn't beeen already loaded.
347,317
def save(self, *args, **kwargs): lexer = get_lexer_by_name(self.language) linenos = self.linenos and or False options = self.title and {: self.title} or {} formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options) ...
Use the `pygments` library to create a highlighted HTML representation of the code snippet.
347,318
def __embed_branch(dfs_data): u = dfs_data[][0] dfs_data[] = [] dfs_data[] = [] dfs_data[] = {} n = dfs_data[].num_nodes() f0 = (0, n) g0 = (0, n) L0 = {: 0, : n} R0 = {: 0, : n} dfs_data[].append(f0) dfs_data[].append(g0) dfs_data[][0] = [L0, R0] dfs_data[][] = ...
Builds the combinatorial embedding of the graph. Returns whether the graph is planar.
347,319
def ls(params="", directory=".", printed=True): command = "{0} {1} {2}".format("ls" if not win_based else "dir", params, directory) response = run(command, shell=True) response.check_returncode() if printed: print(response.stdout.decode("utf-8")) els...
Know the best python implantation of ls? It's just to subprocess ls... (uses dir on windows). :param params: options to pass to ls or dir :param directory: if not this directory :param printed: If you're using this, you probably wanted it just printed :return: if not printed, you can parse it yours...
347,320
def _repo(self, args): args.pop(0) command = args[0] if command == : self._repo_list(args) elif command == : self._repo_packages(args) elif command == : self._repo_packages(args, search=True) elif command == : self....
Process repo commands
347,321
def set_variables(self, data): variables = etree.SubElement(self.bnmodel, "VARIABLES") for var in sorted(data): variable = etree.SubElement(variables, , attrib={: var, : data[var][], : data[var][], : data[var][]}) ...
Set variables for the network. Parameters ---------- data: dict dict for variable in the form of example as shown. Examples -------- >>> from pgmpy.readwrite.XMLBeliefNetwork import XBNWriter >>> writer = XBNWriter() >>> writer.set_variables(...
347,322
def alive(opts): if salt.utils.napalm.not_always_alive(opts): return True return True flag = is_alive_ret.get(, {}).get(, False) log.debug(, opts.get(), if flag else ) return flag
Return the connection status with the remote device. .. versionadded:: 2017.7.0
347,323
def quat_conjugate(quaternion): return np.array( (-quaternion[0], -quaternion[1], -quaternion[2], quaternion[3]), dtype=np.float32, )
Return conjugate of quaternion. >>> q0 = random_quaternion() >>> q1 = quat_conjugate(q0) >>> q1[3] == q0[3] and all(q1[:3] == -q0[:3]) True
347,324
def snli_token_generator(tmp_dir, train, vocab_size): _download_and_parse_dataset(tmp_dir, train) symbolizer_vocab = _get_or_generate_vocab( tmp_dir, , vocab_size) file_name = if train else data_file = os.path.join(tmp_dir, file_name + ) with tf.gfile.GFile(data_file, mode=) as f: for line in...
Generate example dicts.
347,325
def run(self): for task in self.get_next_tasks(None): self.executor.add_task(task, None) while not self.executor.is_done(): done_task_and_result = self.executor.wait_for_tasks() for task, task_result in done_task_and_result: self._add_sub_task...
Runs all tasks in this runner on the executor. Blocks until all tasks have been completed. :return:
347,326
def get_number(self, question, min_i=float("-inf"), max_i=float("inf"), just_these=None): try: user_answer = self.get_answer(question) user_answer = float(user_answer) if min_i < user_answer < max_i: if just_these: ...
Parses answer and gets number :param question: Question: to ask user :param min_i: min acceptable number :param max_i: max acceptable number :param just_these: Accept only these numbers :return: User answer
347,327
def listen(self, address=): if isinstance(address, six.string_types): addresses = parse_dbus_address(address) else: addresses = [address] for addr in addresses: try: super(DbusServer, self).listen(addr) except pyuv.error.UV...
Start listening on *address* for new connection. The *address* argument must be a D-BUS server address, in the format described in the D-BUS specification. It may also be one of the special addresses ``'session'`` or ``'system'``, to connect to the D-BUS session and system bus, respecti...
347,328
def startMenu(translator, navigation, tag): setTabURLs(navigation, translator) getp = IQ(tag).onePattern def fillSlots(tabs): for tab in tabs: if tab.children: kids = getp().fillSlots(, fillSlots(tab.children)) else: kids = ...
Drop-down menu-style navigation view. For each primary navigation element available, a copy of the I{tab} pattern will be loaded from the tag. It will have its I{href} slot filled with the URL for that navigation item. It will have its I{name} slot filled with the user-visible name of the navigation ...
347,329
def add_version_func(self, show_version): if callable(show_version): self.__show_version_func = show_version else: self.__show_version_func = lambda cli, args: print(show_version) self.parser.add_argument("-V", "--version", action="store_true")
Enable --version and -V to show version information
347,330
def get_user_properties(self): user = self.context.getUser() if user is None: return {} out = {} plone_user = user.getUser() userid = plone_user.getId() for sheet in plone_user.listPropertysheets(): ps = plone_user.getPropertys...
Return the properties of the User
347,331
def lsof(name): * sanitize_name = six.text_type(name) lsof_infos = __salt__[]("lsof -c " + sanitize_name) ret = [] ret.extend([sanitize_name, lsof_infos]) return ret
Retrieve the lsof information of the given process name. CLI Example: .. code-block:: bash salt '*' ps.lsof apache2
347,332
def has_attribute(self, attr): if not hasattr(self._subject, attr): raise self._error_factory(_format("Expected {} to have attribute {}", self._subject, attr)) return ReferenceInspector(getattr(self._subject, attr))
Ensures :attr:`subject` has an attribute *attr*.
347,333
def close(self): if not self.lock_disable and self.session_config_lock: self._unlock() self.device.close()
Close the connection.
347,334
def _exec_calcs(calcs, parallelize=False, client=None, **compute_kwargs): if parallelize: def func(calc): if in compute_kwargs: compute_kwargs[] = False return _compute_or_skip_on_error(calc, compute_kwargs) if client is None: n...
Execute the given calculations. Parameters ---------- calcs : Sequence of ``aospy.Calc`` objects parallelize : bool, default False Whether to submit the calculations in parallel or not client : distributed.Client or None The distributed Client used if parallelize is set to True; if ...
347,335
def _CopyFileLocal(source_filename, target_filename, copy_symlink=True): import shutil try: dir_name = os.path.dirname(target_filename) if dir_name and not os.path.isdir(dir_name): os.makedirs(dir_name) if copy_symlink and IsLink(source_filename): ...
Copy a file locally to a directory. :param unicode source_filename: The filename to copy from. :param unicode target_filename: The filename to copy to. :param bool copy_symlink: If True and source_filename is a symlink, target_filename will also be created as a symlink. ...
347,336
def resolve_variables(self, provided_variables): self.resolved_variables = {} variable_dict = dict((var.name, var) for var in provided_variables) for var_name, _var_def in variable_dict.items(): value = resolve_variable( variable_dict.get(var_name), ...
Resolve the values of the blueprint variables. This will resolve the values of the template parameters with values from the env file, the config, and any lookups resolved. The resolution is run twice, in case the blueprint is jinja2 templated and requires provided variables to render. ...
347,337
def request(self, send_terminator = False): try: retA = self.requestA() retB = self.requestB() if retA and retB: self.makeAB() self.calculateFields() self.updateObservers() return True except: ...
Combined A and B read for V4 meter. Args: send_terminator (bool): Send termination string at end of read. Returns: bool: True on completion.
347,338
def abs_path(rel_path): return os.path.abspath( os.path.join(os.path.dirname(sys._getframe(1).f_code.co_filename), rel_path) )
Convert a path that is relative to the module from which this function is called, to an absolute path. Args: rel_path: str Path relative to the location of the module file from which this function is called. Returns: str : Absolute path to the location specified by ``rel_path``.
347,339
def bottomAt(self, offset=0): return Location(self.getX() + (self.getW() / 2), self.getY() + self.getH() + offset)
Returns point in the center of the region's bottom side (offset to the bottom by ``offset``)
347,340
def findViewByTagOrRaise(self, tag, root="ROOT"): view = self.findViewWithAttribute(, tag, root) if view: return view else: raise ViewNotFoundException("tag", tag, root)
Finds the View with the specified tag or raise a ViewNotFoundException
347,341
def byweekday(self): retval = [] if self.rule._byweekday: retval += [Weekday(day) for day in self.rule._byweekday] if self.rule._bynweekday: retval += [Weekday(day, n) for day, n in self.rule._bynweekday] return retval
The weekdays where the recurrence will be applied. In RFC5545 this is called BYDAY, but is renamed by dateutil to avoid ambiguity.
347,342
def numpy_normxcorr(templates, stream, pads, *args, **kwargs): import bottleneck from scipy.signal.signaltools import _centered used_chans = ~np.isnan(templates).any(axis=1) stream = stream.astype(np.float64) templates = templates.astype(np.float64) template_length = templat...
Compute the normalized cross-correlation using numpy and bottleneck. :param templates: 2D Array of templates :type templates: np.ndarray :param stream: 1D array of continuous data :type stream: np.ndarray :param pads: List of ints of pad lengths in the same order as templates :type pads: list ...
347,343
def get_jtimes(self): if self._jtimes is False: return False if self._jtimes is True: r = self.be.Dummy() v = tuple(self.be.Dummy(.format(i)) for i in range(self.ny)) f = self.be.Matrix(1, self.ny, self.exprs) f = f.subs([(x_i, x_i + ...
Derive the jacobian-vector product from ``self.exprs`` and ``self.dep``
347,344
def read_configuration(self): c = self._get_pypirc_command() c.repository = self.url cfg = c._read_pypirc() self.username = cfg.get() self.password = cfg.get() self.realm = cfg.get(, ) self.url = cfg.get(, self.url)
Read the PyPI access configuration as supported by distutils, getting PyPI to do the actual work. This populates ``username``, ``password``, ``realm`` and ``url`` attributes from the configuration.
347,345
def signHostCsr(self, xcsr, signas, outp=None, sans=None): myca pkey = xcsr.get_pubkey() name = xcsr.get_subject().CN return self.genHostCert(name, csr=pkey, signas=signas, outp=outp, sans=sans)
Signs a host CSR with a CA keypair. Args: cert (OpenSSL.crypto.X509Req): The certificate signing request. signas (str): The CA keypair name to sign the CSR with. outp (synapse.lib.output.Output): The output buffer. sans (list): List of subject alternative names. ...
347,346
def draw(self): from calysto.display import display, clear_output canvas = self.render() clear_output(wait=True) display(canvas)
Render and draw the world and robots.
347,347
def closestTrainingPattern(self, inputPattern, cat): dist = self._getDistances(inputPattern) sorted = dist.argsort() for patIdx in sorted: patternCat = self._categoryList[patIdx] if patternCat == cat: if self.useSparseMemory: closestPattern = self._Memory.getRow(i...
Returns the closest training pattern to inputPattern that belongs to category "cat". :param inputPattern: The pattern whose closest neighbor is sought :param cat: The required category of closest neighbor :returns: A dense version of the closest training pattern, or None if no such patterns e...
347,348
def read_in_config(self): log.info("Attempting to read in config file") if self._get_config_type() not in constants.SUPPORTED_EXTENSIONS: raise errors.UnsupportedConfigError(self._get_config_type()) with open(self._get_config_file()) as fp: f = fp.read() ...
Vyper will discover and load the configuration file from disk and key/value stores, searching in one of the defined paths.
347,349
def _create_body(self, name, cooldown, min_entities, max_entities, launch_config_type, server_name, image, flavor, disk_config=None, metadata=None, personality=None, networks=None, load_balancers=None, scaling_policies=None, group_metadata=None, key_name=None, config_driv...
Used to create the dict required to create any of the following: A Scaling Group
347,350
def from_input_lookup(s): for pseudo_abi in FourByteDirectory.get_pseudo_abi_for_input(s): method = AbiMethod(pseudo_abi) types_def = pseudo_abi["inputs"] types = [t["type"] for t in types_def] names = [t["name"] for t in types_def] values = ...
Return a new AbiMethod object from an input stream :param s: binary input :return: new AbiMethod object matching the provided input stream
347,351
def get_proficiency_query_session_for_objective_bank(self, objective_bank_id, proxy): if not objective_bank_id: raise NullArgument if not self.supports_proficiency_query(): raise Unimplemented() try: from . import sessions except ImportError: ...
Gets the ``OsidSession`` associated with the proficiency query service for the given objective bank. :param objective_bank_id: the ``Id`` of the obective bank :type objective_bank_id: ``osid.id.Id`` :param proxy: a proxy :type proxy: ``osid.proxy.Proxy`` :return: a ``Proficiency...
347,352
def flag(self, payload): url = "{url_base}/resource/{pid}/flag/".format(url_base=self.hs.url_base, pid=self.pid) r = self.hs._request(, url, None, payload) return r
Set a single flag on a resource. :param payload: t: can be one of make_public, make_private, make_shareable, make_not_shareable, make_discoverable, make_not_discoverable :return: empty but with 202 status_code
347,353
def get(cls, block_type): if isinstance(block_type, (BlockType, CustomBlockType)): return block_type if isinstance(block_type, PluginBlockType): block_type = block_type.command block = kurt.plugin.Kurt.block_by_command(block_type) if block: ...
Return a :class:`BlockType` instance from the given parameter. * If it's already a BlockType instance, return that. * If it exactly matches the command on a :class:`PluginBlockType`, return the corresponding BlockType. * If it loosely matches the text on a PluginBlockType, return th...
347,354
def download_layers(self, repo_name, digest=None, destination=None): from sregistry.main.workers import Workers from sregistry.main.workers.aws import download_task self._get_manifest(repo_name, digest) digests = self._get_digests(repo_name, digest) destination = self._get_download_cache(...
download layers is a wrapper to do the following for a client loaded with a manifest for an image: 1. use the manifests to retrieve list of digests (get_digests) 2. atomically download the list to destination (get_layers) This function uses the MultiProcess client to download lay...
347,355
def square_off(samples, run_parallel): to_process = [] extras = [] for data in [utils.to_single_data(x) for x in samples]: added = False if tz.get_in(("metadata", "batch"), data): for add in genotype.handle_multiple_callers(data, "jointcaller", require_bam=False): ...
Perform joint calling at all variants within a batch.
347,356
def submissions_between(reddit_session, subreddit, lowest_timestamp=None, highest_timestamp=None, newest_first=True, extra_cloudsearch_fields=None, verbosity=1): def d...
Yield submissions between two timestamps. If both ``highest_timestamp`` and ``lowest_timestamp`` are unspecified, yields all submissions in the ``subreddit``. Submissions are yielded from newest to oldest(like in the "new" queue). :param reddit_session: The reddit_session to make requests from. In al...
347,357
def adjust_whitespace(text): state = [False, False] (backslashed, triplequoted) = (0, 1) def in_multi_line(line): start_state = (state[backslashed] or state[triplequoted]) if re.search(r"\\$", line): state[backslashed] = True else: state[backslashed] =...
remove the left-whitespace margin of a block of Python code.
347,358
def user_get_session_token(self, app_id=None, email=None, password=None, ekey=None, fb_access_token=None, tw_oauth_token=None, tw_oauth_token_secret=None, api_key=None): if app_id is None: raise Va...
user/get_session_token http://www.mediafire.com/developers/core_api/1.3/user/#get_session_token
347,359
def page_index(self, page_index): if page_index is None: raise ValueError("Invalid value for `page_index`, must not be `None`") if page_index > 6: raise ValueError("Invalid value for `page_index`, must be a value less than or equal to `6`") if page_index < 0: ...
Sets the page_index of this V1Page. The page's position in the merchant's list of pages. Always an integer between 0 and 6, inclusive. :param page_index: The page_index of this V1Page. :type: int
347,360
def start(self): if is_anaconda(): self.url = if os.name == : self.url += elif sys.platform == : self.url += else: self.url += else: self.url = ( ) sel...
Main method of the WorkerUpdates worker
347,361
def get_subclasses(modulepath, parent_class): if isinstance(modulepath, ModuleType): modules = get_modules(modulepath.__name__) else: modules = get_modules(modulepath) ret = set() for m in modules: cs = inspect.getmembers(m, lambda v: inspect.isclass(v) and issubclass(v, pa...
given a module return all the parent_class subclasses that are found in that module and any submodules. :param modulepath: string, a path like foo.bar.che :param parent_class: object, the class whose children you are looking for :returns: set, all the found child classes in modulepath of parent_class
347,362
async def restart(request: web.Request) -> web.Response: session = session_from_request(request) if session and session.stage != Stages.READY_FOR_RESTART: return web.json_response( data={: , : f}, status=409) asyncio.get_event_loop()...
Serves /update/server/restart
347,363
def _set_option_by_index(self, index): if index < len(self._options): self._selected.set(self._options[index]) return True else: return False
Sets a single option in the Combo by its index, returning True if it was able too.
347,364
def get_ancestor_item(self, tree_alias, base_item): parent = None if hasattr(base_item, ) and base_item.parent is not None: parent = self.get_ancestor_item(tree_alias, self.get_item_by_id(tree_alias, base_item.parent.id)) if parent is None: return base_item ...
Climbs up the site tree to resolve root item for chosen one. :param str|unicode tree_alias: :param TreeItemBase base_item: :rtype: TreeItemBase
347,365
def is_equivalent(self, callback, details_filter=None): cb = self.callback if cb is None and callback is not None: return False if cb is not None and callback is None: return False if cb is not None and callback is not None \ and not reflection...
Check if the callback provided is the same as the internal one. :param callback: callback used for comparison :param details_filter: callback used for comparison :returns: false if not the same callback, otherwise true :rtype: boolean
347,366
def create_new_locale( self, template_id, locale, version_name, subject, text=, html=, timeout=None ): payload = { : locale, : version_name, : subject } if html: payload[...
API call to create a new locale and version of a template
347,367
def set_ss_value(tag, value): if tag.VR == or tag.VR == : value = struct.pack(, value) tag.value = value
Setter for data that also work with implicit transfersyntax :param value: the value to set on the tag :param tag: the tag to read
347,368
def _calc_selection_shape(self): n_ints = int(self.t_stop - self.t_start) n_chan = int(np.round((self.f_stop - self.f_start) / abs(self.header[b]))) selection_shape = (n_ints,int(self.header[b]),n_chan) return selection_shape
Calculate shape of data of interest.
347,369
def is_all_field_none(self): if self._id_ is not None: return False if self._created is not None: return False if self._updated is not None: return False if self._description is not None: return False if self._ip is no...
:rtype: bool
347,370
def _par_vector2dict(v, pars, dims, starts=None): if starts is None: starts = _calc_starts(dims) d = OrderedDict() for i in range(len(pars)): l = int(np.prod(dims[i])) start = starts[i] end = start + l y = np.asarray(v[start:end]) if len(dims[i]) > 1: ...
Turn a vector of samples into an OrderedDict according to param dims. Parameters ---------- y : list of int or float pars : list of str parameter names dims : list of list of int list of dimensions of parameters Returns ------- d : dict Examples -------- >>...
347,371
def _canFormAraPhrase( araVerb, otherVerb ): äraäraära global _verbAraAgreements for i in range(0, len(_verbAraAgreements), 2): araVerbTemplate = _verbAraAgreements[i] otherVerbTemplate = _verbAraAgreements[i+1] matchingAraAnalyses = araVerbTemplate.matchingAnalyseIndexes(ara...
Teeb kindlaks, kas etteantud 'ära' verb (araVerb) yhildub teise verbiga; Arvestab järgimisi ühilduvusi: ains 2. pööre: ära_neg.o + V_o ains 3. pööre: ära_neg.gu + V_gu mitm 1. pööre: ära_neg.me + V_me ära_neg.me + V_o ...
347,372
def GetRandomLocationsNearStops(schedule): locations = [] for s in schedule.GetStopList(): locations.append(AddNoiseToLatLng(s.stop_lat, s.stop_lon)) return locations
Return a list of (lat, lng) tuples.
347,373
def upgrade(): op.create_index(op.f(), , [], unique=False) op.drop_constraint(u, , type_=) op.create_foreign_key(op.f(), , , [], [], ondelete=) op.create_index(op.f(), , [], unique=Fal...
Upgrade database.
347,374
def slice(self, start=None, stop=None, step=None): check_type(start, int) check_type(stop, int) check_type(step, int) if step is not None and step < 0: raise ValueError() return _series_str_result(self, weld_str_slice, start=start, stop=stop, step=step)
Slice substrings from each element. Note that negative step is currently not supported. Parameters ---------- start : int stop : int step : int Returns ------- Series
347,375
def rpr(s): if s is None: return seen_unicode = False results = [] for cc in s: ccn = ord(cc) if ccn >= 32 and ccn < 127: if cc == "\\\\\\u\\U" + "".join(results) + "'" if seen_unicode: return "u(" + result + ")" else: return result
Create a representation of a Unicode string that can be used in both Python 2 and Python 3k, allowing for use of the u() function
347,376
def create_database(self): from chatterbot.ext.sqlalchemy_app.models import Base Base.metadata.create_all(self.engine)
Populate the database with the tables.
347,377
def _assign_intersection(lhs_arr, rhs_arr, offset): lhs_slc, rhs_slc = _intersection_slice_tuples(lhs_arr, rhs_arr, offset) lhs_arr[lhs_slc] = rhs_arr[rhs_slc]
Assign the intersecting region from ``rhs_arr`` to ``lhs_arr``.
347,378
def get_td_from_final_mass_spin(template=None, taper=None, distance=None, **kwargs): input_params = props(template, mass_spin_required_args, **kwargs) final_mass = input_params[] final_spin = input_params[] lmns = input_params[] for lmn in lmns: if...
Return time domain ringdown with all the modes specified. Parameters ---------- template: object An object that has attached properties. This can be used to substitute for keyword arguments. A common example would be a row in an xml table. taper: {None, float}, optional Tapering...
347,379
def or_where_pivot(self, column, operator=None, value=None): return self.where_pivot(column, operator, value, "or")
Set an or where clause for a pivot table column. :param column: The column of the where clause, can also be a QueryBuilder instance for sub where :type column: str|Builder :param operator: The operator of the where clause :type operator: str :param value: The value of the wher...
347,380
def _call_wait(self, hints, name, args, kwargs, topics=(), raw=False, limit=None, retry=False, max_retries=None): col = self.collector if not col.is_running(): col.start() call_id = uuid4_bytes() reply_to = (DUPLEX if self.socket is col.socket else...
Allocates a call id and emit.
347,381
def apply_effect_expression_filters( effects, gene_expression_dict, gene_expression_threshold, transcript_expression_dict, transcript_expression_threshold): if gene_expression_dict: effects = apply_filter( lambda effect: ( gene_express...
Filter collection of varcode effects by given gene and transcript expression thresholds. Parameters ---------- effects : varcode.EffectCollection gene_expression_dict : dict gene_expression_threshold : float transcript_expression_dict : dict transcript_expression_threshold : float
347,382
def which(cmd, mode=os.F_OK | os.X_OK, path=None): def _access_check(fn, mode): return (os.path.exists(fn) and os.access(fn, mode) and not os.path.isdir(fn)) if os.path.dirname(cmd): if _access_check(cmd, mode): return cmd r...
Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result of os.environ.get("PATH"), or can be overridden with a custom search path. Note: This func...
347,383
def synonyms(self): if self.cid: results = get_json(self.cid, operation=) return results[][][0][] if results else []
A ranked list of all the names associated with this Compound. Requires an extra request. Result is cached.
347,384
def is_address_guard(self, address): try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_guard()
Determines if an address belongs to a guard page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a guard page. @raise WindowsError: An exce...
347,385
def list_firewall_rules(self, retrieve_all=True, **_params): return self.list(, self.firewall_rules_path, retrieve_all, **_params)
Fetches a list of all firewall rules for a project.
347,386
def get_cantera_mole_fraction(self, species_conversion=None): if self.composition_type == : raise ValueError( .format(self.composition)) else: return self.get_cantera_composition_string(species_conversion)
Get the mole fractions in a string format suitable for input to Cantera. Arguments: species_conversion (`dict`, optional): Mapping of species identifier to a species name. This argument should be supplied when the name of the species in the ChemKED YAML file does not...
347,387
def convert(self, values, nan_rep, encoding, errors): if values.dtype.fields is not None: values = values[self.cname] self.set_data(values) meta = _ensure_decoded(self.meta) if self.dtype is not None: dtype = _ensure_decoded...
set the data from this selection (and convert to the correct dtype if we can)
347,388
def char_tokens_to_char_offsets(si_tokens): for token in si_tokens: offset = token.offsets[OffsetType.CHARS] yield offset.first, offset.first + offset.length
Convert character ``Offset``s to character ranges.
347,389
def zeros(cls, point_format, point_count): data = np.zeros(point_count, point_format.dtype) return cls(data, point_format)
Creates a new point record with all dimensions initialized to zero Parameters ---------- point_format_id: int The point format id the point record should have point_count : int The number of point the point record should have Returns ------- ...
347,390
def create_hls_stream(self, localStreamNames, targetFolder, **kwargs): return self.protocol.execute(, localStreamNames=localStreamNames, targetFolder=targetFolder, **kwargs)
Create an HTTP Live Stream (HLS) out of an existing H.264/AAC stream. HLS is used to stream live feeds to iOS devices such as iPhones and iPads. :param localStreamNames: The stream(s) that will be used as the input. This is a comma-delimited list of active stream names (local stream...
347,391
def read_csv(self, csv_location, csv_configs=None): csv_configs = self._generate_configs_from_default(csv_configs) with open(csv_location, ) as csv_file: csv_reader = csv.reader(csv_file) self.csv_data = list(csv_reader) self.csv_data = self.csv_data[csv...
Read the csv file
347,392
def f_load_items(self, iterator, *args, **kwargs): if not self._stored: raise TypeError( ) fetched_items = self._nn_interface._fetch_items(LOAD, iterator, args, kwargs) if fetched_items: self._storage_service.load(pypetconstants.LIST, fetched_it...
Loads parameters and results specified in `iterator`. You can directly list the Parameter objects or just their names. If names are given the `~pypet.naturalnaming.NNGroupNode.f_get` method is applied to find the parameters or results in the trajectory. Accordingly, the parameters and results ...
347,393
def _build_all_dependencies(self): ret = {} for model, schema in six.iteritems(self._models()): dep_list = self._build_dependent_model_list(schema) ret[model] = dep_list return ret
Helper function to build a map of model to their list of model reference dependencies
347,394
def create_session_entity_type(project_id, session_id, entity_values, entity_type_display_name, entity_override_mode): import dialogflow_v2 as dialogflow session_entity_types_client = dialogflow.SessionEntityTypesClient() session_path = session_entity_types_client.sessio...
Create a session entity type with the given display name.
347,395
def cell_centers(dataset, vertex=True): alg = vtk.vtkCellCenters() alg.SetInputDataObject(dataset) alg.SetVertexCells(vertex) alg.Update() output = _get_output(alg) return output
Generate points at the center of the cells in this dataset. These points can be used for placing glyphs / vectors. Parameters ---------- vertex : bool Enable/disable the generation of vertex cells.
347,396
def convex_comb_agg_log(model,a,b): K = len(a)-1 G = int(math.ceil((math.log(K)/math.log(2)))) w,g = {},{} for k in range(K+1): w[k] = model.addVar(lb=0, ub=1, vtype="C") for j in range(G): g[j] = model.addVar(vtype="B") X = model.addVar(lb=a[0], ub=a[K], vtype="C") ...
convex_comb_agg_log -- add piecewise relation with a logarithmic number of binary variables using the convex combination formulation -- non-disaggregated. Parameters: - model: a model where to include the piecewise linear relation - a[k]: x-coordinate of the k-th point in the piecewise linear re...
347,397
def parse_time_interval(slot): start = IntentParser.get_dict_value( slot, [, ]) end = IntentParser.get_dict_value(slot, [, ]) if not start or not end: return None start = parse(start) end = parse(end) if not start or not end: r...
Parse a slot into a TimeInterval object. Sample response: { "entity": "snips/datetime", "range": { "end": 42, "start": 13 }, "rawValue": "between tomorrow and saturday", "slotName": "weatherForecastStartDatetime", "val...
347,398
def log_url (self, url_data, priority=None): self.xml_starttag(u) self.xml_tag(u, url_data.url) if url_data.modified: self.xml_tag(u, self.format_modified(url_data.modified, sep="T")) self.xml_tag(u, self.frequency) self.xml_tag(u, "%.2f" % priority) ...
Log URL data in sitemap format.
347,399
def _weights_callback(self, msg): weights = np.array(msg.data) if len(self._weight_buffers) == 0: self._weight_buffers = [[] for i in range(len(weights))] for i, w in enumerate(weights): if len(self._weight_buffers[i]) == self._ntaps:...
Callback for recording weights from sensor.