Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
347,400
def process_dns_frame(self, id=None, msg=None): df = json_normalize(msg) dt = json.loads(df.to_json()) flat_msg = {} for k in dt: new_key = "dns_{}".format(k) flat_msg[new_key] = dt[...
process_dns_frame Convert a complex nested json dictionary to a flattened dictionary and capture all unique keys for table construction :param id: key for this msg :param msg: dns frame for packet
347,401
def _init_nodes(self, config): if not isinstance(config, dict): raise TypeError() for (name, conf) in six.iteritems(config): args = [] if not in conf else conf[] kwargs = {} if not in conf else conf[] dependencies = set() arg_deps ...
Gathers dependency sets onto _nodes
347,402
def Nu_horizontal_cylinder_Kuehn_Goldstein(Pr, Gr): r Ra = Pr*Gr return 2./log(1 + 2./((0.518*Ra**0.25*(1. + (0.559/Pr)**0.6)**(-5/12.))**15 + (0.1*Ra**(1/3.))**15)**(1/15.))
r'''Calculates Nusselt number for natural convection around a horizontal cylinder according to the Kuehn-Goldstein [1]_ correlation, also shown in [2]_. Cylinder must be isothermal. .. math:: \frac{2}{Nu_D} = \ln\left[1 + \frac{2}{\left[\left\{0.518Ra_D^{0.25} \left[1 + \left(\frac{0.559}{P...
347,403
def resample(self,N,**kwargs): lovals = self.mu - np.absolute(rand.normal(size=N)*self.siglo) hivals = self.mu + np.absolute(rand.normal(size=N)*self.sighi) u = rand.random(size=N) hi = (u < float(self.sighi)/(self.sighi + self.siglo)) lo = (u >= float(self.sighi)/(self...
Random resampling of the doublegauss distribution
347,404
def load_writer(writer, ppp_config_dir=None, **writer_kwargs): if ppp_config_dir is None: ppp_config_dir = get_environ_config_dir() config_fn = writer + ".yaml" if "." not in writer else writer config_files = config_search_paths( os.path.join("writers", config_fn), ppp_config_dir) ...
Find and load writer `writer` in the available configuration files.
347,405
def validation_requests(self): if self._validation_requests is None: self._validation_requests = ValidationRequestList(self._version, account_sid=self._solution[], ) return self._validation_requests
Access the validation_requests :returns: twilio.rest.api.v2010.account.validation_request.ValidationRequestList :rtype: twilio.rest.api.v2010.account.validation_request.ValidationRequestList
347,406
def _get_crl_url(self, distribution_points): if distribution_points is None: return None for distribution_point in distribution_points: name = distribution_point[] if name.name == and name.chosen[0].name == : return name.chosen[0].chosen.na...
Grabs the first URL out of a asn1crypto.x509.CRLDistributionPoints object :param distribution_points: The x509.CRLDistributionPoints object to pull the URL out of :return: A unicode string or None
347,407
def ls(path, force=False): path = expand_filepath(path) logger.debug(.format(path)) if os.path.isfile(path): return path elif os.path.isdir(path): return os.listdir(path) elif not force: return os.listdir(path) try: return os.listdir(path) except IOError:...
bash `ls -a`: List both file paths or directory contents (files and directories) >>> ls('.') [...] >>> ls('~/') [...] >>> __file__.endswith(os.path.join('nlpia', 'futil.py')) True >>> ls(__file__).endswith(os.path.join('nlpia', 'futil.py')) True
347,408
def get(self, key, default=None): try: return self.items[key] except IndexError: return value(default)
Get an element of the collection. :param key: The index of the element :type key: mixed :param default: The default value to return :type default: mixed :rtype: mixed
347,409
def href_filter(self, href): require_abs_urldomain_substrings if self.config[]: if not href.lower().startswith((, )): return False if self.config[]: return True if self.config[]: parts = href.split() if len(par...
Test whether an href string meets criteria specified by configuration parameters 'require_abs_url', which means "does it look like it is probably an absolute URL?" and 'domain_substrings'. It searches for each of the domain_substrings in the href individually, and if any match, ...
347,410
def main(): parser = argparse.ArgumentParser(description=, add_help=False) parser.add_argument(, type=str, help=) parser.add_argument(, , action=, help=) parser.add_argument(, action=, dest=, default=, type=str, help=) parser.add_...
Main function that is called when DistanceClassifier is run on the command line
347,411
def _replace_qs(self, url, qs): url_parts = list(urlparse(url)) url_parts[4] = qs return urlunparse(url_parts)
Replace the query string of ``url`` with ``qs`` and return the new URL.
347,412
def add(self, timer): with self.lock: if self.heap: top = self.heap[0] else: top = None assert timer not in self.timers self.timers[timer] = timer heapq.heappush(self.heap, timer) ...
Add a timer to the heap
347,413
def ensure_samples_is_ndim_ndarray(samples, name=, ndim=2): assert isinstance(ndim, int) assert isinstance(name, str) if not isinstance(samples, np.ndarray) or not (samples.ndim == ndim): sample_name = name + "_samples" msg = "`{}` MUST be a {}D ndarray.".format(sample_name, ndim) ...
Ensures that `samples` is an `ndim` numpy array. Raises a helpful ValueError if otherwise.
347,414
def srandmember(self, key, count=None, *, encoding=_NOTSET): args = [key] count is not None and args.append(count) return self.execute(b, *args, encoding=encoding)
Get one or multiple random members from a set.
347,415
def get_live_league_games(self): url = self.__build_url(urls.GET_LIVE_LEAGUE_GAMES) req = self.executor(url) if self.logger: self.logger.info(.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
Returns a dictionary containing a list of ticked games in progress :return: dictionary of live games, see :doc:`responses </responses>`
347,416
def recognise(self): if not isinstance(self.cube, Cube): raise ValueError("Use Solver.feed(cube) to feed the cube to solver.") result = "" for face in "LFRB": for square in self.cube.get_face(face)[0]: result += str(int(square == self.cube["U"]["U...
Recognise which is Cube's OLL case.
347,417
def multithreader(args, paths): def shellprocess(path): import subprocess return subprocess.Popen(args + [path], stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL) processes = [shellprocess(path) for path in paths...
Execute multiple processes at once.
347,418
def reviews(self, packageName, filterByDevice=False, sort=2, nb_results=None, offset=None): path = REVIEWS_URL + "?doc={}&sort={}".format(requests.utils.quote(packageName), sort) if nb_results is not None: path += "&n={}".format(nb_results) if offset...
Browse reviews for an application Args: packageName (str): app unique ID. filterByDevice (bool): filter results for current device sort (int): sorting criteria (values are unknown) nb_results (int): max number of reviews to return offset (int): return...
347,419
def apply(self, word, ctx=None): return Sequential.in_sequence(word,AdjacentVowels.uyir_letters,AdjacentVowels.reason)
ignore ctx information right now
347,420
def vagrant(self, name=): r = self.local_renderer config = self.ssh_config(name) extra_args = self._settings_dict(config) r.genv.update(extra_args)
Run the following tasks on a vagrant box. First, you need to import this task in your ``fabfile.py``:: from fabric.api import * from burlap.vagrant import vagrant @task def some_task(): run('echo hello') Then you can easily run tasks on...
347,421
def register_filters(self, filters, force=False): for filter_name, filter_ref in filters.items(): self.register_filter(filter_name, filter_ref, force)
Add/register filters. Args: filters (dict): Dictionary of Python functions to use as :program:`Jinja2` filters. force (bool): If set to ``True``, forces the registration of a filter no matter if it already exists or not.
347,422
def plot_mean_quantile_returns_spread_time_series(mean_returns_spread, std_err=None, bandwidth=1, ax=None): if isinstance(mean_returns_spread, pd.DataFrame): ...
Plots mean period wise returns for factor quantiles. Parameters ---------- mean_returns_spread : pd.Series Series with difference between quantile mean returns by period. std_err : pd.Series Series with standard error of difference between quantile mean returns each period. ...
347,423
def backwards(self, orm): "Write your backwards methods here." for c in orm["contenttypes.contenttype"].objects.all(): if c.app_label == "dublincore": c.app_label = "DublinCore" c.save()
Write your backwards methods here.
347,424
def qualified_name(obj) -> str: if not isclass(obj): obj = type(obj) if obj.__module__ == : return obj.__name__ else: return .format(obj.__module__, obj.__qualname__)
Return the qualified name (e.g. package.module.Type) for the given object. If ``obj`` is not a class, the returned name will match its type instead.
347,425
def relative_filename_within_dir(filename: str, directory: str) -> str: filename = os.path.abspath(filename) directory = os.path.abspath(directory) if os.path.commonpath([directory, filename]) != directory: return "" return os.path.relpath(filename, start=directory)
Starting with a (typically absolute) ``filename``, returns the part of the filename that is relative to the directory ``directory``. If the file is *not* within the directory, returns an empty string.
347,426
def dump_type(self, obj): if not isinstance(obj.relation_type, RelationType): return resolve_relation_type_config(obj.relation_type).name else: return obj.relation_type.name
Dump the text name of the relation.
347,427
def isUrl(urlString): parsed = urlparse.urlparse(urlString) urlparseValid = parsed.netloc != and parsed.scheme != regex = re.compile( r r r r r r r, re.IGNORECASE) return regex.match(urlString) and urlparseValid
Attempts to return whether a given URL string is valid by checking for the presence of the URL scheme and netloc using the urlparse module, and then using a regex. From http://stackoverflow.com/questions/7160737/
347,428
def get_contributor_sort_value(self, obj): user = obj.contributor if user.first_name or user.last_name: contributor = user.get_full_name() else: contributor = user.username return contributor.strip().lower()
Generate display name for contributor.
347,429
def potinflayers(self, x, y, layers, aq=None): if aq is None: aq = self.model.aq.find_aquifer_data(x, y) pot = self.potinf(x, y, aq) rv = np.sum(pot[:,np.newaxis,:] * aq.eigvec, 2).T return rv[layers,:]
Returns array of size (len(layers),nparam) only used in building equations
347,430
def comments_block(context, comments, form, obj, url, **kwargs): data = kwargs if in data: data[] += else: data[] = if context[].user.is_authenticated(): del form.fields[] return {: comments, : form, : url, : obj, : data}
Тег для отображения блока комментариев Пример использования (комментарии к текстовой странице):: {% comments comments comments_form page "midnight_main:page_comments" %} :param context: контекст :param comments: список комментариев :param form: форма добавления комментария :param obj: объ...
347,431
def search_by_release(self, release_id, limit=0, order_by=None, sort_order=None, filter=None): url = "%s/release/series?release_id=%d" % (self.root_url, release_id) info = self.__get_search_results(url, limit, order_by, sort_order, filter) if info is None: raise ValueError( ...
Search for series that belongs to a release id. Returns information about matching series in a DataFrame. Parameters ---------- release_id : int release id, e.g., 151 limit : int, optional limit the number of results to this value. If limit is 0, it means fetchin...
347,432
def _is_symlink(self): return len(self.dr_entries.sl_records) > 0 or len(self.ce_entries.sl_records) > 0
Internal method to determine whether this Rock Ridge entry is a symlink.
347,433
def _bgzip_file(finput, config, work_dir, needs_bgzip, needs_gunzip, needs_convert, data): if isinstance(finput, six.string_types): in_file = finput else: assert not needs_convert, "Do not yet handle quality conversion with multiple inputs" return _bgzip_multiple_files(finput, work_...
Handle bgzip of input file, potentially gunzipping an existing file. Handles cases where finput might be multiple files and need to be concatenated.
347,434
def do_chan_log_all(self, line): self.application.channel.SetLogFilters(openpal.LogFilters(opendnp3.levels.ALL_COMMS)) print(.format(opendnp3.levels.ALL_COMMS))
Set the channel log level to ALL_COMMS. Command syntax is: chan_log_all
347,435
def get_group_by_id(self, group_id: str) -> typing.Optional[]: VALID_POSITIVE_INT.validate(group_id, , exc=ValueError) for group in self.groups: if group.group_id == group_id: return group return None
Gets a group by id Args: group_id: group id Returns: Group
347,436
def gen_radio_view(sig_dic): view_zuoxiang = .format(sig_dic[]) dic_tmp = sig_dic[] for key in dic_tmp.keys(): tmp_str = {0}{0}.format(sig_dic[], key, dic_tmp[key]) view_zuoxiang += tmp_str view_zuoxiang += return view_zuoxiang
for checkbox
347,437
def majority(p, a, b, c): p.cx(c, b) p.cx(c, a) p.ccx(a, b, c)
Majority gate.
347,438
def add_logging_level(name, value, method_name=None): if not method_name: method_name = name.lower() logging.addLevelName(value, name) setattr(logging, name, value) level_map[name.lower()] = value if value == getattr(logging, , None): def logForLevel(self, message=, *ar...
Comprehensively adds a new logging level to the ``logging`` module and the currently configured logging class. Derived from: https://stackoverflow.com/a/35804945/450917
347,439
def expand_actions(self, actions): results = list() for action in actions: if action in self.aliased_actions: results.append(action) for item in self.expand_actions(self.aliased_actions[action]): results.append(item) e...
Accepts an array of actions and returns an array of actions which match. This should be called before "matches?" and other checking methods since they rely on the actions to be expanded.
347,440
def ReqConnect(self, pAddress: str): self.q.CreateApi() spi = self.q.CreateSpi() self.q.RegisterSpi(spi) self.q.OnFrontConnected = self._OnFrontConnected self.q.OnFrontDisconnected = self._OnFrontDisConnected self.q.OnRspUserLogin = self._OnRspUserLogin ...
连接行情前置 :param pAddress:
347,441
def parse_text_to_table(txt): res = [] delim = identify_delim(txt) print(, txt, ,delim) if delim == or delim == : fixed_split = identify_col_pos(txt) if fixed_split == []: res = [] else: res = parse_text_by_col_pos(txt, fixed_split) else: res = parse_text_by_delim(txt, d...
takes a blob of text and finds delimiter OR guesses the column positions to parse into a table. input: txt = blob of text, lines separated by \n output: res = table of text
347,442
def ticket_audit_show(self, ticket_id, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/ticket_audits api_path = "/api/v2/tickets/{ticket_id}/audits/{id}.json" api_path = api_path.format(ticket_id=ticket_id, id=id) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/ticket_audits#show-audit
347,443
def showbox(self, force_rerun=False): log.debug(.format(self.id)) if not self.sphsel_path: return ValueError() boxfile = op.join(self.dock_dir, "{}_box.pdb".format(self.id)) boxscript = op.join(self.dock_dir, "{}_box.in".format(self.id)) if ssbio.utils.for...
Create the dummy PDB box around the selected spheres. Args: force_rerun (bool): If method should be rerun even if output file exists
347,444
def cert_verify(self, conn, url, verify, cert): if url.lower().startswith() and verify: cert_loc = None if verify is not True: cert_loc = verify if not cert_loc: cert_loc = DEFAULT_CA_BUNDLE_PATH if not cer...
Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param conn: The urllib3 connection object associated with the cert. :param url: The requested URL. :...
347,445
async def async_run(self) -> None: self.main_task = self.loop.create_task(self.main()) await self.main_task
Asynchronously run the worker, does not close connections. Useful when testing.
347,446
def log_middleware(store): def wrapper(next_): def log_dispatch(action): print(, action) return next_(action) return log_dispatch return wrapper
log all actions to console as they are dispatched
347,447
def value(self): if hasattr(self, ): return self._value_decoded if self.value_blob is not None: encoded_value = self.value_blob.open().read() else: encoded_value = self.value_text self._value_decoded = json.loads(encoded_value, cls=util.JsonDecoder) return self._value_decode...
Returns the value of this Slot.
347,448
def _generate_base_lsid(self): domain = self._generate_domain() namespace = self._generate_namespace() return "urn:lsid:" + domain + ":" + namespace
Generates and returns a base LSID :return:
347,449
def delete(name, remove=False, force=False, root=None): * cmd = [] if remove: cmd.append() if force and __grains__[] != and __grains__[] != : cmd.append() cmd.append(name) if root is not None and __grains__[] != : cmd.extend((, root)) ret = __salt__[](cmd, pytho...
Remove a user from the minion name Username to delete remove Remove home directory and mail spool force Force some actions that would fail otherwise root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.delete name remove=Tru...
347,450
def get_constant(self, const_name, context): const = self._constants[const_name] if isinstance(const, ast.AnnAssign): if context: expr = Expr(const.value, context).lll_node return expr else: raise VariableDecla...
Return unrolled const
347,451
def add_update_handler(self, callback): self._update_callbacks.append(callback) return self.UpdateHandlerRemover(lambda: self._update_callbacks.remove(callback))
Args: callback: The specified callback will be invoked when: - A new node appears - Node info for an existing node gets updated - Node goes offline Returns: Call remove() or try_remove() on the returned object to unregister...
347,452
def generate_navigator_js(os=None, navigator=None, platform=None, device_type=None): config = generate_navigator(os=os, navigator=navigator, platform=platform, device_type=device_type) return { : config[], ...
Generates web navigator's config with keys corresponding to keys of `windows.navigator` JavaScript object. :param os: limit list of oses for generation :type os: string or list/tuple or None :param navigator: limit list of browser engines for generation :type navigator: string or list/tuple or None...
347,453
def _get_config_generator(filename): for d in _get_config(filename): repo = d[] parsedrepo = giturlparse.parse(repo) name = .format(parsedrepo.owner, parsedrepo.name) src_dir = os.path.join(_get_clone_dir(), name) files = d.get() post_commands = d.get(, []) ...
A generator which populates and return a dict. :parse filename: A string containing the path to YAML file. :return: dict
347,454
def fetch(self, url, payload=None, headers=None, method=HttpClient.GET, stream=False): if not self.from_archive: self.sleep_for_rate_limit() response = super().fetch(url, payload, headers, method, stream) if not self.from_archive: self.update_rate_limit(respons...
Fetch the data from a given URL. :param url: link to the resource :param payload: payload of the request :param headers: headers of the request :param method: type of request call (GET or POST) :param stream: defer downloading the response body until the response content is avai...
347,455
def get_objective_requisite_session_for_objective_bank(self, objective_bank_id, proxy): if not self.supports_objective_requisite(): raise errors.Unimplemented() return sessions.ObjectiveRequisiteSession(objective_bank_id, proxy, self._runtime)
Gets the ``OsidSession`` associated with the objective sequencing service for the given objective bank. arg: objective_bank_id (osid.id.Id): the ``Id`` of the objective bank arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ObjectiveRequisiteSession) - an ...
347,456
def forward(self, data_batch, is_train=None): assert self.binded and self.params_initialized data_batch = copy.copy(data_batch) for i_layer, module in enumerate(self._modules): module.forward(data_batch, is_train=is_train) if i_layer+1 == len...
Forward computation. Parameters ---------- data_batch : DataBatch is_train : bool Default is ``None``, in which case `is_train` is take as ``self.for_training``.
347,457
def _get_row_within_width(self, row): table = self._table lpw, rpw = table.left_padding_widths, table.right_padding_widths wep = table.width_exceed_policy list_of_rows = [] if (wep is WidthExceedPolicy.WEP_STRIP or wep is WidthExceedPolicy.WEP_ELLIPSIS)...
Process a row so that it is clamped by column_width. Parameters ---------- row : array_like A single row. Returns ------- list of list: List representation of the `row` after it has been processed according to width exceed policy.
347,458
def setOverlayInputMethod(self, ulOverlayHandle, eInputMethod): fn = self.function_table.setOverlayInputMethod result = fn(ulOverlayHandle, eInputMethod) return result
Sets the input settings for the specified overlay.
347,459
def crash_handler_lite(etype, evalue, tb): traceback.print_exception(etype, evalue, tb) from IPython.core.interactiveshell import InteractiveShell if InteractiveShell.initialized(): config = "%config " else: config = "c." print >> sys.stderr, _lite_message...
a light excepthook, adding a small message to the usual traceback
347,460
def _get_expiration(self, headers: dict) -> int: expiration_str = headers.get() if not expiration_str: return 0 expiration = datetime.strptime(expiration_str, ) delta = (expiration - datetime.utcnow()).total_seconds() return math.ceil(abs(delta))
Gets the expiration time of the data from the response headers. Args: headers: dictionary of headers from ESI Returns: value of seconds from now the data expires
347,461
def getVertices(self,data): return self.bone.transformVertices(data,self.vertices,self.dims)
Returns the vertices of this region already transformed and ready-to-use. Internally uses :py:meth:`Bone.transformVertices()`\ .
347,462
def get_push_command(self, remote=None, revision=None): if revision: raise NotImplementedError(compact()) command = [, ] if remote: command.append(remote) return command
Get the command to push changes from the local repository to a remote repository.
347,463
def _escape(self, text): ret = EMPTYSTRING if text is None else str(text) if self.escape: return html_escape(ret) else: return ret
Escape text according to self.escape
347,464
def _get_internal_max_value(self): if self.max_value is None: return None else: if self._transformation is None: return self._external_max_value else: return self._transformation.forward(self....
This is supposed to be only used by fitting engines to get the maximum value in internal representation. It is supposed to be called only once before doing the minimization/sampling, to set the range of the parameter :return: maximum value in internal representation (or None if there is no minimum)
347,465
def lookup(self, c, lookup_order="CF"): if not isinstance(c, six.text_type): raise TypeError(u"Character to lookup must be of type !") for d in lookup_order: try: return self._casefold_map[d][c] except KeyError: pass re...
Function to lookup a character in the casefold map. The casefold map has four sub-tables, the 'C' or common table, the 'F' or full table, the 'S' or simple table and the 'T' or the Turkic special case table. These tables correspond to the statuses defined in the CaseFolding.txt file. ...
347,466
def _diff_disk_lists(old, new): targets = [] prefixes = [, , , , , ] for disk in new: target_node = disk.find() target = target_node.get() prefix = [item for item in prefixes if target.startswith(item)][0] new_target = [.format(prefix, string.ascii_lowerca...
Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks
347,467
def reap_fileserver_cache_dir(cache_base, find_func): for saltenv in os.listdir(cache_base): env_base = os.path.join(cache_base, saltenv) for root, dirs, files in salt.utils.path.os_walk(env_base): if not dirs and not files: ...
Remove unused cache items assuming the cache directory follows a directory convention: cache_base -> saltenv -> relpath
347,468
def to_python(self, value): if isinstance(value, six.string_types): return value if value is None: return value return _unsigned_integer_to_hex_string(value)
Return a str representation of the hexadecimal
347,469
def read_maxquant(f, header=0, index_col=, **kwargs): df = pd.read_csv(f, delimiter=, header=header, index_col=index_col, **kwargs) return df
Load the quantified table output from MaxQuant run, e.g. - Proteingroups.txt - Phospho (STY)Sites.txt :param f: Source file :return: Pandas dataframe of imported data
347,470
def _poseFromQuad(self, quad=None): if quad is None: quad = self.quad if quad.ndim == 3: quad = quad[0] img_pn = np.ascontiguousarray(quad[:, :2], dtype=np.float32).reshape((4, 1, 2)) obj_p...
estimate the pose of the object plane using quad setting: self.rvec -> rotation vector self.tvec -> translation vector
347,471
def substitute(search, replace, text): return re.sub(re.compile(str(search)), replace, text)
Regex substitution function. Replaces regex ``search`` with ``replace`` in ``text``
347,472
def process(self, frames, eod): src_index = 0 remaining = len(frames) while remaining: space = self.buffer_size - self.len copylen = remaining < space and remaining or space src = frames[src_index:src_index + copylen] if self.len == 0 and...
Returns an iterator over tuples of the form (buffer, eod) where buffer is a fixed-sized block of data, and eod indicates whether this is the last block. In case padding is deactivated the last block may be smaller than the buffer size.
347,473
def notification_channel_descriptor_path(cls, project, channel_descriptor): return google.api_core.path_template.expand( "projects/{project}/notificationChannelDescriptors/{channel_descriptor}", project=project, channel_descriptor=channel_descriptor, )
Return a fully-qualified notification_channel_descriptor string.
347,474
def _optimize(self, period, tmpid, use_gradient=True): theta_0 = [self.y.min(), self.y.max() - self.y.min(), 0] result = minimize(self._chi2, theta_0, jac=bool(use_gradient), bounds=[(None, None), (0, None), (None, None)], args=(period, tmpid,...
Optimize the model for the given period & template
347,475
def trigger(self, target: str, trigger: str, parameters: Dict[str, Any]={}): pass
Calls the specified Trigger of another Area with the optionally given parameters. Args: target: The name of the target Area. trigger: The name of the Trigger. parameters: The parameters of the function call.
347,476
def slugify(value): import re import unicodedata value = str(value) value = unicodedata.normalize(, value).encode(, ).decode().strip().lower() value = re.sub(r, , value) value = re.sub(r, , value) return value
Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens.type(
347,477
def to_internal_value(self, data): if not isinstance(data, list): message = self.error_messages[].format( input_type=type(data).__name__ ) raise serializers.ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: [message] })...
This implements the same relevant logic as ListSerializer except that if one or more items fail validation, processing for other items that did not fail will continue.
347,478
def write_pid_file(self, overwrite=False): pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u) if os.path.isfile(pid_file): pid = self.get_pid_from_file() if not overwrite: raise PIDFileError( % (pid_...
Create a .pid file in the pid_dir with my pid. This must be called after pre_construct, which sets `self.pid_dir`. This raises :exc:`PIDFileError` if the pid file exists already.
347,479
def get_times_from_cli(cli_token): today = datetime.date.today() if cli_token=="thisday": return today, today elif cli_token=="thisweek": return today, today - dateutil.relativedelta.relativedelta(days=7) elif cli_token=="thismonth": return today, today - dateutil.relatived...
Convert a CLI token to a datetime tuple. Argument: cli_token (str): an isoformat datetime token ([ISO date]:[ISO date]) or a special value among: * thisday * thisweek * thismonth * thisyear Returns: tuple: a datetime.d...
347,480
def workerTypeRemoved(self, *args, **kwargs): ref = { : , : , : [ { : , : False, : , }, { : False, : , ...
WorkerType Removed Message When a `workerType` is removed a message will be published to this exchange. This exchange outputs: ``http://schemas.taskcluster.net/aws-provisioner/v1/worker-type-message.json#``This exchange takes the following keys: * routingKeyKind: Identifier for the r...
347,481
def command(self, name: str) -> Callable: def inner(f: Callable): self._commands.append((name, f)) return inner
Decorator to wrap methods to register them as commands The argument to this method is the command that you want to trigger your callback. If you want users to send "!hello bob" and your method "command_hello" to get called when someone does, then your setup will look like: @pycord....
347,482
def plot_world_with_elegans( world, radius=None, width=350, height=350, config=None, grid=True, wireframe=False, species_list=None, debug=None, max_count=1000, camera_position=(-22, 23, 32), camera_rotation=(-0.6, 0.5, 0.6), return_id=False, predicator=None): config = config or ...
Generate a plot from received instance of World and show it on IPython notebook. This method returns the instance of dict that indicates color setting for each speices. You can use the dict as the parameter of plot_world, in order to use the same colors in another plot. Parameters ---------- wo...
347,483
def disassemble(nex): rev_opcodes = {} for op in interpreter.opcodes: rev_opcodes[interpreter.opcodes[op]] = op r_constants = 1 + len(nex.signature) r_temps = r_constants + len(nex.constants) def getArg(pc, offset): if sys.version_info[0] < 3: arg = ord(nex.program[...
Given a NumExpr object, return a list which is the program disassembled.
347,484
def he_uniform(name, shape, scale=1, dtype=tf.sg_floatx, summary=True, regularizer=None, trainable=True): r fin, _ = _get_fans(shape) s = np.sqrt(1. * scale / fin) return uniform(name, shape, s, dtype, summary, regularizer, trainable)
r"""See [He et al. 2015](http://arxiv.org/pdf/1502.01852v1.pdf) Args: name: The name of new variable shape: A tuple/list of integers. scale: A Python scalar. Scale to initialize. Default is 1. dtype: The data type. Default is float32. summary: If True, add this constant to tensor boar...
347,485
def height(self, container): height = float(self.get_style(, container)) script_level = self.script_level(container) if script_level > -1: height *= self.position_size * (5 / 6)**script_level return height
Font size after super/subscript size adjustment.
347,486
def folderitems(self): items = super(AnalysisRequestAnalysesView, self).folderitems() self.categories.sort() return items
XXX refactor if possible to non-classic mode
347,487
def lookup_ip(self, mac): res = self.lookup_by_lease(mac=mac) try: return res["ip-address"] except KeyError: raise OmapiErrorAttributeNotFound()
Look for a lease object with given mac address and return the assigned ip address. @type mac: str @rtype: str or None @raises ValueError: @raises OmapiError: @raises OmapiErrorNotFound: if no lease object with the given mac could be found @raises OmapiErrorAttributeNotFound: if lease could be found, but ...
347,488
def get_subscriptions(self, nodes=[]): if len(nodes) > 0: data = [node for node in self.get_clients() if node[] in nodes] else: data = self.get_clients() channels = [] for client in data: if in client: if isinstance(client[], ...
Returns all the channels where (optionally specified) nodes are subscribed
347,489
def OnRangeSelected(self, event): if not self.grid.IsEditable(): selection = self.grid.selection row, col, __ = self.grid.sel_mode_cursor if (row, col) in selection: self.grid.ClearSelection() else: self.grid.SetG...
Event handler for grid selection
347,490
def info(dataset, indent, meta_member): table = bcdata.validate_name(dataset) wfs = WebFeatureService(url=bcdata.OWS_URL, version="2.0.0") info = {} info["name"] = table info["count"] = bcdata.get_count(table) info["schema"] = wfs.get_schema("pub:" + table) if meta_member: click...
Print basic metadata about a DataBC WFS layer as JSON. Optionally print a single metadata item as a string.
347,491
def list_pkgs(versions_as_list=False, **kwargs): <package_name><version>* versions_as_list = salt.utils.data.is_true(versions_as_list) if any([salt.utils.data.is_true(kwargs.get(x)) for x in (, )]): return {} if in __context__: if versions_as_list: return _...
List the packages currently installed in a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs
347,492
def _get_hash_object(hash_algo_name): algorithms = (hashlib.algorithms_guaranteed if six.PY3 else hashlib.algorithms) if hash_algo_name not in algorithms: msg = ("Unsupported/Invalid hash name provided." % hash_algo_name) raise exception.InvalidInputError(m...
Create a hash object based on given algorithm. :param hash_algo_name: name of the hashing algorithm. :raises: InvalidInputError, on unsupported or invalid input. :returns: a hash object based on the given named algorithm.
347,493
def gen_tasks(self, urls): tasks = [] if isinstance(urls, list): for url in urls: dat = { : url, : url.split()[-1] } if not self.overwrite and helper.is_file_ok(dat[]): self.r...
according the urls gen {name:'', url:''} dict. :param urls: :type urls: :return: :rtype:
347,494
def load_credentials(self, profile="default"): f = profile_path(DBPY_PROFILE_ID, profile) if f: creds = load_from_json(f) self.username = creds.get() self.password = creds.get() self.hostname = creds.get() self.port = creds.get() ...
Loads crentials for a given profile. Profiles are stored in ~/.db.py_{profile_name} and are a base64 encoded JSON file. This is not to say this a secure way to store sensitive data, but it will probably stop your little sister from stealing your passwords. Parameters ---------- ...
347,495
def register(name=None, exprresolver=None, params=None, reg=None): def _register(exprresolver, _name=name, _params=params): _exprresolver = exprresolver if isclass(exprresolver): if _params is None: _params = {} _exprresolver = _exprresolve...
Register an expression resolver. Can be used such as a decorator. For example all remainding expressions are the same. .. code-block:: python @register('myresolver') def myresolver(**kwargs): pass .. code-block:: python def myresolver(**kwargs): pass register('myre...
347,496
def update_batches(self, X_batch, L, Min): self.X_batch = X_batch if X_batch is not None: self.r_x0, self.s_x0 = self._hammer_function_precompute(X_batch, L, Min, self.model)
Updates the batches internally and pre-computes the
347,497
def GetFrequencyStopTimes(self, problems=None): stoptimes_list = [] stoptime_pattern = self.GetStopTimes() first_secs = stoptime_pattern[0].arrival_secs stoptime_class = self.GetGtfsFactory().StopTime for run_secs in self.GetFrequencyStartTimes(): stoptimes = [] ...
Return a list of StopTime objects for each headway-based run. Returns: a list of list of StopTime objects. Each list of StopTime objects represents one run. If this trip doesn't have headways returns an empty list.
347,498
def set_file_chksum(self, doc, chksum): if self.has_package(doc) and self.has_file(doc): if not self.file_chksum_set: self.file_chksum_set = True self.file(doc).chk_sum = checksum_from_sha1(chksum) return True else: ...
Raises OrderError if no package or file defined. Raises CardinalityError if more than one chksum set.
347,499
def blocks(self, lines): state = markdown.blockparser.State() blocks = [] state.set() currblock = 0 for line in lines: line += if state.isstate(): if line[:3] == : state.set() ...
Groups lines into markdown blocks