Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
340,200
def sample_function(self, f, N): x = self.interpolation_points(N+1) return f(x)
Sample a function on N+1 Chebyshev points.
340,201
def make_url(self, path, api_root=u): return urljoin(urljoin(self.url, api_root), path)
Gets a full URL from just path.
340,202
def _stop_timers(canvas): for attr in dir(canvas): try: attr_obj = getattr(canvas, attr) except NotImplementedError: attr_obj = None if isinstance(attr_obj, Timer): attr_obj.stop()
Stop all timers in a canvas.
340,203
def cashdraw(self, pin): if pin == 2: self._raw(CD_KICK_2) elif pin == 5: self._raw(CD_KICK_5) else: raise CashDrawerError()
Send pulse to kick the cash drawer
340,204
def write(self, message, opcode=None, encode=True, **kw): if encode: message = self.parser.encode(message, opcode=opcode, **kw) result = self.connection.write(message) if opcode == 0x8: self.connection.close() return result
Write a new ``message`` into the wire. It uses the :meth:`~.FrameParser.encode` method of the websocket :attr:`parser`. :param message: message to send, must be a string or bytes :param opcode: optional ``opcode``, if not supplied it is set to 1 if ``message`` is a string, ...
340,205
def remove_nan_observations(x, y, z): r x_ = x[~np.isnan(z)] y_ = y[~np.isnan(z)] z_ = z[~np.isnan(z)] return x_, y_, z_
r"""Remove all x, y, and z where z is nan. Will not destroy original values. Parameters ---------- x: array_like x coordinate y: array_like y coordinate z: array_like observation value Returns ------- x, y, z List of coordinate observation pairs wit...
340,206
async def put(self, data, ttl=None, ttr=None, delay=None): the_tuple = await self.queue.put(self, data, ttl=ttl, ttr=ttr, delay=delay) if the_tuple.rowcount: return Task.create_from_tuple(self, the_tuple)
Enqueue a task. Returns a `Task` object.
340,207
def held_time(self): if self._held_from is not None: return self.pin_factory.ticks_diff(self.pin_factory.ticks(), self._held_from) else: return None
The length of time (in seconds) that the device has been held for. This is counted from the first execution of the :attr:`when_held` event rather than when the device activated, in contrast to :attr:`~EventsMixin.active_time`. If the device is not currently held, this is :data:`None`.
340,208
def show_sentences(): cursor = CONN.cursor() query = "select sen_id, sentence from sursentences where sen_is_valid = order by sen_id asc" cursor.execute(query) result = cursor.fetchall() response_dict = {} for row in result: response_dict[row[0]] = row[1] return response_di...
Return all valid/active sentences ordered by ID to allow the user to pick and choose. :return: Dict containing the sentence ID as the key and the sentence structure as the value.
340,209
def create_policy(self, account, client, document, name, arn=None): if not arn and not name: raise ValueError() if arn: response = client.list_policy_versions(PolicyArn=arn) } ) return res
Create a new IAM policy. If the policy already exists, a new version will be added and if needed the oldest policy version not in use will be removed. Returns a dictionary containing the policy or version information Args: account (:obj:`Account`): Account to create the policy on ...
340,210
def start_linear_address(eip): b = [4, 0, 0, 0x05, (eip>>24)&0x0FF, (eip>>16)&0x0FF, (eip>>8)&0x0FF, eip&0x0FF] return Record._from_bytes(b)
Return Start Linear Address Record. @param eip 32-bit linear address for the EIP register. @return String representation of Intel Hex SLA record.
340,211
def create_or_update(cls, *props, **kwargs): lazy = kwargs.get(, False) relationship = kwargs.get() create_or_update_params = [] for specified, deflated in [(p, cls.deflate(p, skip_empty=True)) for p in props]: create_or_update_params.append({"create": defl...
Call to MERGE with parameters map. A new instance will be created and saved if does not already exists, this is an atomic operation. If an instance already exists all optional properties specified will be updated. Note that the post_create hook isn't called after create_or_update :param props:...
340,212
def accept(self, logevent): if self.fromReached and self.seek_to: if self.seek_to != -1: self.toReached = (self.mlogfilter.args[][0] .filehandle.tell() >= self.seek_to) return True else: dt = loge...
Process line. Overwrite BaseFilter.accept() and return True if the provided logevent should be accepted (causing output), or False if not.
340,213
def getAsKmlPngAnimation(self, tableName, timeStampedRasters=[], rasterIdFieldName=, rasterFieldName=, documentName=, noDataValue=0, alpha=1.0, drawOrder=0, cellSize=None, resampleMethod=, discreet=False): if not self.isNumber(noDataValue): ...
Return a sequence of rasters with timestamps as a kml with time markers for animation. :param tableName: Name of the table to extract rasters from :param timeStampedRasters: List of dictionaries with keys: rasterId, dateTime rasterId = a unique integer identifier used to locate the raste...
340,214
def get_attr_value(self, key, attr): idx = self._keys[key] return self._attrs[attr][idx].get_value()
returns the value of a given attribute for a given key >>> doc = Doc(docnum='1') >>> doc.terms = Text(multi=True, uniq=True, attrs={'tf': Numeric()}) >>> doc.terms.add('chat', tf=55) >>> doc.terms.get_attr_value('chat', 'tf') 55
340,215
def update(self, bundleId, dmeData): url = "api/v0002/mgmt/custom/bundle/%s" % (bundleId) r = self._apiClient.put(url, dmeData) if r.status_code == 200: return r.json() else: raise ApiException(r)
Update a device management extension package It accepts bundleId (string) as parameters In case of failure it throws APIException
340,216
def qemu_path(self, qemu_path): if qemu_path and os.pathsep not in qemu_path: if sys.platform.startswith("win") and ".exe" not in qemu_path.lower(): qemu_path += "w.exe" new_qemu_path = shutil.which(qemu_path, path=os.pathsep.join(self._manager.paths_list())) ...
Sets the QEMU binary path this QEMU VM. :param qemu_path: QEMU path
340,217
def get_cameras_battery_level(self): battery_levels = {} if not self.camera_properties: return None for camera in self.camera_properties: serialnum = camera.get() cam_battery = camera.get() battery_levels[serialnum] = cam_battery ...
Return a list of battery levels of all cameras.
340,218
def flush_commands(self, event=None): if self._do_CURRENT_command: self._do_CURRENT_command = False canvas = get_current_canvas() if canvas and hasattr(canvas, ): fbo = canvas._backend._vispy_get_fb_bind_location() else: fb...
Flush Parameters ---------- event : instance of Event The event.
340,219
def register_classes(yaml: ruamel.yaml.YAML, classes: Optional[Iterable[Any]] = None) -> ruamel.yaml.YAML: if classes is None: classes = [] for cls in classes: logger.debug(f"Registering class {cls} with YAML") yaml.register_class(cls) return yaml
Register externally defined classes.
340,220
def predict(self, u=0): self.x = dot(self.F, self.x) + dot(self.B, u)
Predict next position. Parameters ---------- u : ndarray Optional control vector. If non-zero, it is multiplied by `B` to create the control input into the system.
340,221
def revnet_step(name, x, hparams, reverse=True): with tf.variable_scope(name, reuse=tf.AUTO_REUSE): if hparams.coupling == "additive": coupling_layer = functools.partial( additive_coupling, name="additive", reverse=reverse, mid_channels=hparams.coupling_width, activation=hpa...
One step of glow generative flow. Actnorm + invertible 1X1 conv + affine_coupling. Args: name: used for variable scope. x: input hparams: coupling_width is the only hparam that is being used in this function. reverse: forward or reverse pass. Returns: z: Output of one step of re...
340,222
def get_mac_address_table_input_request_type_get_interface_based_request_mac_type(self, **kwargs): config = ET.Element("config") get_mac_address_table = ET.Element("get_mac_address_table") config = get_mac_address_table input = ET.SubElement(get_mac_address_table, "input") ...
Auto Generated Code
340,223
def post_process(self, dir_name, d): logger.info("Post-processing dir:{}".format(dir_name)) fullpath = os.path.abspath(dir_name) new_tags = other_parameters.pop("tags", None) new_author = other_parameters.pop("author", None) ...
Simple post-processing for various files other than the vasprun.xml. Called by generate_task_doc. Modify this if your runs have other kinds of processing requirements. Args: dir_name: The dir_name. d: Current doc generated.
340,224
def kullback_leibler(c1, c2): d = c2.log_det_sigma - c1.log_det_sigma d += np.trace(c2.inv_sigma.dot(c1.sigma)) mean_diff = c1.mu - c2.mu d += mean_diff.transpose().dot(c2.inv_sigma).dot(mean_diff) d -= len(c1.mu) return 0.5 * d
Kullback Leibler divergence of two Gaussians, :math:`KL(1||2)`
340,225
def put(self, key, value): self.cache_datastore.put(key, value) self.child_datastore.put(key, value)
Stores the object `value` named by `key`self. Writes to both ``cache_datastore`` and ``child_datastore``.
340,226
def set_namespace(namespace, attribute, namespace_splitter=NAMESPACE_SPLITTER): long_name = "{0}{1}{2}".format(namespace, namespace_splitter, attribute) LOGGER.debug("> Namespace: , attribute: , long name: .".format(namespace, attribute, long_name)) return long_name
Sets given namespace to given attribute. Usage:: >>> set_namespace("parent", "child") u'parent|child' :param namespace: Namespace. :type namespace: unicode :param attribute: Attribute. :type attribute: unicode :param namespace_splitter: Namespace splitter character. :type ...
340,227
def dependencies(self, images): for dep in self.commands.dependent_images: if not isinstance(dep, six.string_types): yield dep.name for image, _ in self.dependency_images(): yield image
Yield just the dependency images
340,228
def console_set_default_foreground( con: tcod.console.Console, col: Tuple[int, int, int] ) -> None: lib.TCOD_console_set_default_foreground(_console(con), col)
Change the default foreground color for a console. Args: con (Console): Any Console instance. col (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance. .. deprecated:: 8.5 Use :any:`Console.default_fg` instead.
340,229
def print_project_list_details(self, filter_auth_role, long_format): if filter_auth_role: projects_details = self.remote_store.get_projects_with_auth_role(auth_role=filter_auth_role) else: projects_details = self.remote_store.get_projects_details() if projects_de...
Prints project names to stdout for all projects or just those with the specified auth_role :param filter_auth_role: str: optional auth_role to filter project list
340,230
def unscale_samples(params, bounds): b = np.array(bounds) lower_bounds = b[:, 0] upper_bounds = b[:, 1] if np.any(lower_bounds >= upper_bounds): raise ValueError("Bounds are not legal") np.divide(np.subtract(params, lower_bounds, out=params), np....
Rescale samples from arbitrary bounds back to [0,1] range Arguments --------- bounds : list list of lists of dimensions num_params-by-2 params : numpy.ndarray numpy array of dimensions num_params-by-N, where N is the number of samples
340,231
def parse_py_tree(self, pytree): parsed_pytree = {} pypackages = set() for base, dirs, files in os.walk(pytree): if self._ignore_pydir(os.path.basename(base)): continue elif not in files: continue ...
Parse the given Python package tree. :param str pytree: The absolute path to the Python tree which is to be parsed. :rtype: dict :returns: A two-tuple. The first element is a dict where each key is the path of a parsed Python module (relative to the Python tree) and its value is the...
340,232
def _make_pretty_arguments(arguments): if arguments.startswith("\n Arguments:"): arguments = "\n".join(map(lambda u: u[6:], arguments.strip().split("\n")[1:])) return "**Arguments:**\n\n%s\n\n" % arguments
Makes the arguments description pretty and returns a formatted string if `arguments` starts with the argument prefix. Otherwise, returns None. Expected input: Arguments: * arg0 - ... ... * arg0 - ... ... Expected output: **Arguments:** * ar...
340,233
def disconnect_handler(remote, *args, **kwargs): if not current_user.is_authenticated: return current_app.login_manager.unauthorized() account = RemoteAccount.get(user_id=current_user.get_id(), client_id=remote.consumer_key) external_id = account.extra_data.get(...
Handle unlinking of remote account.
340,234
def svmachine(self, data: [, str] = None, autotune: str = None, code: str = None, id: str = None, input: [str, list, dict] = None, kernel: str = None, output: [str, bool, ] = None, partition: st...
Python method to call the SVMACHINE procedure Documentation link: https://go.documentation.sas.com/?docsetId=casml&docsetTarget=casml_svmachine_toc.htm&docsetVersion=8.3&locale=en :param data: SASdata object or string. This parameter is required. :parm autotune: The autotune variable c...
340,235
def create_and_update_from_json_data(d, user): page = None parent = None parent_required = True created = False messages = [] page_languages = set(lang[0] for lang in settings.PAGE_LANGUAGES) for lang, s in list(d[].items()): if lang not in page_languages: messages...
Create or update page based on python dict d loaded from JSON data. This applies all data except for redirect_to, which is done in a second pass after all pages have been imported, user is the User instance that will be used if the author can't be found in the DB. returns (page object, created, me...
340,236
def to_astropy_table(self, column_names=None, selection=None, strings=True, virtual=False, index=None): from astropy.table import Table, Column, MaskedColumn meta = dict() meta["name"] = self.name meta["description"] = self.description table = Table(meta=meta) f...
Returns a astropy table object containing the ndarrays corresponding to the evaluated data :param column_names: list of column names, to export, when None DataFrame.get_column_names(strings=strings, virtual=virtual) is used :param selection: {selection} :param strings: argument passed to DataFr...
340,237
def _get_nn_shell_info(self, structure, all_nn_info, site_idx, shell, _previous_steps=frozenset(), _cur_image=(0, 0, 0)): if shell <= 0: raise ValueError() _previous_steps = _previous_steps.union({(site_idx, _cur_image)}) possi...
Private method for computing the neighbor shell information Args: structure (Structure) - Structure being assessed all_nn_info ([[dict]]) - Results from `get_all_nn_info` site_idx (int) - index of site for which to determine neighbor information. ...
340,238
def contacted(self): try: contacted_span = self._contacted_xpb.one_(self.profile_tree) except: return False else: timestamp = contacted_span.replace(, ) return helpers.parse_date_updated(timestamp)
:retuns: A boolean indicating whether the logged in user has contacted the owner of this profile.
340,239
def get_parent(obj): names = obj.__qualname__.split()[:-1] if in names: raise ValueError() module = sys.modules[obj.__module__] parent = module while names: parent = getattr(parent, names.pop(0)) return parent
get parent from obj.
340,240
def get_relationship_admin_session_for_family(self, family_id=None): if not family_id: raise NullArgument if not self.supports_relationship_admin(): raise Unimplemented() try: from . import sessions except ImportErro...
Gets the ``OsidSession`` associated with the relationship administration service for the given family. arg: family_id (osid.id.Id): the ``Id`` of the ``Family`` return: (osid.relationship.RelationshipAdminSession) - a ``RelationshipAdminSession`` raise: NotFound - no family ...
340,241
def get_modules(self): plugins = [] for path in self.package.__path__: if os.path.isdir(path): plugins.extend(self._find_plugins_in_dir(path)) return plugins
Returns the list of importable modules in the configured python package.
340,242
def ping(self, data: bytes = b"") -> None: data = utf8(data) if self.protocol is None: raise WebSocketClosedError() self.protocol.write_ping(data)
Send ping frame to the remote end. The data argument allows a small amount of data (up to 125 bytes) to be sent as a part of the ping message. Note that not all websocket implementations expose this data to applications. Consider using the ``ping_interval`` argument to ...
340,243
def _search_key(self): if self.urls: self.search = True if self.compact is True: self.compact = False self.items, self.items_com = self.items_com, self.items else: return self.no_matches = False self.search_stri...
/
340,244
def del_device_notification(self, notification_handle, user_handle): if self._port is not None: adsSyncDelDeviceNotificationReqEx( self._port, self._adr, notification_handle, user_handle )
Remove a device notification. :param notification_handle: address of the variable that contains the handle of the notification :param user_handle: user handle
340,245
def _normalizeParseActionArgs( f ): STAR_ARGS = 4 try: restore = None if isinstance(f,type): restore = f f = f.__init__ if not _PY3K: codeObj = f.func_code else: codeObj = f.code ...
Internal method used to decorate parse actions that take fewer than 3 arguments, so that all parse actions can be called as f(s,l,t).
340,246
def from_text(cls, filename, **kwargs): s formated as in to_text() with identifiers, coordinates, magnitudes. Parameters ---------- filename : str The filename to read in. **kwargs are passed to astropy.io.ascii.read() i_coordinates = t.col...
Create a constellation by reading a catalog in from a text file, as long as it's formated as in to_text() with identifiers, coordinates, magnitudes. Parameters ---------- filename : str The filename to read in. **kwargs are passed to astropy.io.ascii.read()
340,247
def step_mode(self, state_machine_id=None): logger.debug("Activate step mode") if state_machine_id is not None: self.state_machine_manager.active_state_machine_id = state_machine_id self.run_to_states = [] if self.finished_or_stopped(): self.set_executi...
Set the execution mode to stepping mode. Transitions are only triggered if a new step is triggered
340,248
def get_adjacent_matrix(self): edges = self.edges num_edges = len(edges) + 1 adj = np.zeros([num_edges, num_edges]) for k in range(num_edges - 1): adj[edges[k].L, edges[k].R] = 1 adj[edges[k].R, edges[k].L] = 1 return adj
Get adjacency matrix. Returns: :param adj: adjacency matrix :type adj: np.ndarray
340,249
def visitExactRange(self, ctx: ShExDocParser.ExactRangeContext): self.expression.min = int(ctx.INTEGER().getText()) self.expression.max = self.expression.min
repeatRange: '{' INTEGER '}' #exactRange
340,250
def auto_complete_paths(current, completion_type): directory, filename = os.path.split(current) current_path = os.path.abspath(directory) if not os.access(current_path, os.R_OK): return filename = os.path.normcase(filename) file_list = (x for x in os.listdir(current_path) ...
If ``completion_type`` is ``file`` or ``path``, list all regular files and directories starting with ``current``; otherwise only list directories starting with ``current``. :param current: The word to be completed :param completion_type: path completion type(`file`, `path` or `dir`)i :return: A gen...
340,251
def disable_csrf_protection(): if not HAS_PLONE_PROTECT: logger.warn( "Can not disable CSRF protection – please install plone.protect" ) return False request = get_request() interface.alsoProvides(request, IDisableCSRFProtection) return True
disables the CSRF protection https://pypi.python.org/pypi/plone.protect
340,252
def _remove_complex_types(dictionary): for k, v in six.iteritems(dictionary): if isinstance(v, dict): dictionary[k] = _remove_complex_types(v) elif hasattr(v, ): dictionary[k] = v.to_eng_string() return dictionary
Linode-python is now returning some complex types that are not serializable by msgpack. Kill those.
340,253
def start(self, nb_threads: int) -> None: if self._active_threads: raise Exception() for _ in range(nb_threads): worker = threading.Thread( target=_work_function, args=(self._job_q, self._result_q, self._error_q)) wor...
Should only be called once all the jobs have been added using add_job().
340,254
def param(type): import ibis.expr.datatypes as dt import ibis.expr.operations as ops return ops.ScalarParameter(dt.dtype(type)).to_expr()
Create a parameter of a particular type to be defined just before execution. Parameters ---------- type : dt.DataType The type of the unbound parameter, e.g., double, int64, date, etc. Returns ------- ScalarExpr Examples -------- >>> import ibis >>> import ibis.exp...
340,255
def _teardown_features(self): features = self._features if not features: return if features & Feature.FocusTraversal: self.unhook_focus_traversal() if features & Feature.FocusEvents: self.unhook_focus_events() if features & Feature.Dra...
Teardowns the advanced widget feature handlers.
340,256
def append(self, *strings): close_tag_start = self.rfind() if self.tagname: close_tag_start = self.rfind(+self.tagname) if close_tag_start == -1: return self + "".join(strings) ending = self[close_tag_start:] beginning = self[:close_tag_start] ...
Adds any number of supplied *strings* to `self` (we're a subclass of `str` remember) just before the last closing tag and returns a new instance of `~htmltag.HTML` with the result. Example:: >>> from htmltag import span, b >>> html = span('Test:') >>> print(h...
340,257
def forwards(apps, schema_editor): Event = apps.get_model(, ) for ev in Event.objects.filter(kind=): ev.kind = ev.save()
Migrate all 'exhibition' Events to the new 'museum' Event kind.
340,258
def _get_scaled_f_score_from_counts(self, cat_word_counts, not_cat_word_counts, scaler_algo, beta=DEFAULT_BETA): return ScaledFScore.get_scores(cat_word_counts, not_cat_word_counts, scaler_algo, beta=beta)
scaler = self._get_scaler_function(scaler_algo) p_word_given_category = cat_word_counts.astype(np.float64) / cat_word_counts.sum() p_category_given_word = cat_word_counts.astype(np.float64) / (cat_word_counts + not_cat_word_counts) scores \ = self._computer_harmoic_mean_of_probabilit...
340,259
def get_jsonfacet_counts_as_dict(self, field, data=None): facetscounttestbucketscountprbucketscountuniquevalcountuniquevalpr_sumvalconsecteturcountprbucketscountuniquevalcountuniquevalcountuniquevalpr_sumvalauctorcountprbucketscountuniquevalcountuniquevalpr_sumvalnullatestauctorcountprcountuniquecountuniquecoun...
EXPERIMENTAL Takes facets and returns then as a dictionary that is easier to work with, for example, if you are getting something this:: {'facets': {'count': 50, 'test': {'buckets': [{'count': 10, 'pr': {'buckets': [{'count': 2, 'unique': 1, 'val': 79}, ...
340,260
def distancePointToLine(point, line_start, line_end, perpendicular=False): p1 = line_start p2 = line_end offset = lineOffsetWithMinimumDistanceToPoint( point, line_start, line_end, perpendicular) if offset == INVALID_DISTANCE: return INVALID_DISTANCE if offset == 0: retu...
Return the minimum distance between point and the line (line_start, line_end)
340,261
def wait(self, cmd, raise_on_error=True): _, stdout, stderr = self.exec_command(cmd) stdout.channel.recv_exit_status() output = stdout.read() if self.interactive: print(output) errors = stderr.read() if self.interactive: print(errors) ...
Execute command and wait for it to finish. Proceed with caution because if you run a command that causes a prompt this will hang
340,262
def SOAPUriToVersion(self, uri): value = self._soap_uri_mapping.get(uri) if value is not None: return value raise ValueError( % uri )
Return the SOAP version related to an envelope uri.
340,263
def _setup_tokenizer(self, tokenizer: object): language_punkt_vars = PunktLanguageVars language_punkt_vars.sent_end_chars = self.external_punctuation language_punkt_vars.internal_punctuation = self.internal_punctuation tokenizer.INCLUDE_ALL_COLLOCS = True tokenizer.INC...
Add tokenizer and punctuation variables. :type tokenizer: object :param tokenizer : Unpickled tokenizer object. :rtype : object
340,264
def registerAllHandlers(self, handlerDict): self.handlers.update(handlerDict) if hasattr(handlerDict, ): self.scheduler.register(handlerDict.keys(), self) else: self.scheduler.register(tuple(h[0] for h in handlerDict), self) self._setDaemon()
Register self to scheduler
340,265
def build(source, target, versions, current_name, is_root): log = logging.getLogger(__name__) argv = (, source, target) config = Config.from_context() log.debug(, current_name, str(argv)) child = multiprocessing.Process(target=_build, args=(argv, config, versions, current_name, is_root)) c...
Build Sphinx docs for one version. Includes Versions class instance with names/urls in the HTML context. :raise HandledError: If sphinx-build fails. Will be logged before raising. :param str source: Source directory to pass to sphinx-build. :param str target: Destination directory to write documentation t...
340,266
def compose_github(projects, data): for p in [project for project in data if len(data[project][]) > 0]: if not in projects[p]: projects[p][] = [] urls = [url[] for url in data[p][] if url[] not in projects[p][]] projects[p][] += urls return projects
Compose projects.json for github :param projects: projects.json :param data: eclipse JSON :return: projects.json with github
340,267
def _make_tonnetz_matrix(): pi = np.pi chroma = np.arange(12) fifth_x = r_fifth*(np.sin((7*pi/6) * chroma)) fifth_y = r_fifth*(np.cos((7*pi/6) * chroma)) minor_third_x = r_minor_thirds*(np.sin(3*pi/2 * chroma)) minor_third_y = r_minor_thirds*(np.cos(3*pi/2 * chroma)) major_third_x...
Return the tonnetz projection matrix.
340,268
def _setup_dtw(self): if self.dtw is not None: return if (self.real_wave_mfcc is None) or (self.real_wave_mfcc.middle_mfcc is None): self.log_exc(u"The real wave MFCCs are not initialized", None, True, DTWAlignerNotInitialized) if (self.synt_wa...
Set the DTW object up.
340,269
def get_thermostats(self): url = header = {: , : + self.access_token} params = {: ( ...
Set self.thermostats to a json list of thermostats from ecobee
340,270
def _define_jco_args(cmd_parser): jo_group = cmd_parser.add_argument_group(, ) jo_group.add_argument(, help=) jo_group.add_argument(, action=, help=) jo_group.add_argument(, choices=[, , , , ], help=) jo_group.add_argument(, , nargs=, action=_SubmitParamArg, help="Submission parameters as nam...
Define job configuration arguments. Returns groups defined, currently one.
340,271
def get_domain_listing(self, domain, sort=, period=None, *args, **kwargs): if sort not in (, , , , , ): raise TypeError() if period not in (None, , , , , , ): raise TypeError() if sort not in (, ) and pe...
Return a get_content generator for submissions by domain. Corresponds to the submissions provided by ``https://www.reddit.com/domain/{domain}``. :param domain: The domain to generate a submission listing for. :param sort: When provided must be one of 'hot', 'new', 'rising', ...
340,272
def xread(self, streams, timeout=0, count=None, latest_ids=None): args = self._xread(streams, timeout, count, latest_ids) fut = self.execute(b, *args) return wait_convert(fut, parse_messages_by_stream)
Perform a blocking read on the given stream :raises ValueError: if the length of streams and latest_ids do not match
340,273
def parse_config(config_file=None): * if config_file is None: config_file = _config_file() ret = {} if _check_config_exists(config_file): with salt.utils.files.fopen(config_file) as ifile: for line in ifile: key, val = salt.utils.stringutils.to_unicode(line).s...
Returns a dict of poudriere main configuration definitions CLI Example: .. code-block:: bash salt '*' poudriere.parse_config
340,274
def load(self): self.minimum_needs = self.settings.value() if not self.minimum_needs or self.minimum_needs == : profiles = self.get_profiles() if len(profiles) == 1: profile = self.get_profiles()[0] ...
Load the minimum needs. If the minimum needs defined in QSettings use it, if not, get the most relevant available minimum needs (based on QGIS locale). The last thing to do is to just use the default minimum needs.
340,275
def align(self,inputwords, outputwords): alignment = [] cursor = 0 for inputword in inputwords: if len(outputwords) > cursor and outputwords[cursor] == inputword: alignment.append(cursor) cursor += 1 elif len(outputwords) > cursor+...
For each inputword, provides the index of the outputword
340,276
def create(self, data, inlineparent = None): try: return self.struct.unpack(data)[0] except struct.error as exc: raise BadFormatError(exc)
Compatible to Parser.create()
340,277
def _multi_lgamma(self, a, p, name="multi_lgamma"): with self._name_scope(name): seq = self._multi_gamma_sequence(a, p) return (0.25 * p * (p - 1.) * math.log(math.pi) + tf.reduce_sum(input_tensor=tf.math.lgamma(seq), axis=[-1]))
Computes the log multivariate gamma function; log(Gamma_p(a)).
340,278
def wait(self, till=None): waiter = Signal() if self.waiting: DEBUG and _Log.note("waiting with {{num}} others on {{name|quote}}", num=len(self.waiting), name=self.name, stack_depth=1) self.waiting.insert(0, waiter) else: DEBUG and _Log.note("waiting ...
THE ASSUMPTION IS wait() WILL ALWAYS RETURN WITH THE LOCK ACQUIRED :param till: WHEN TO GIVE UP WAITING FOR ANOTHER THREAD TO SIGNAL :return: True IF SIGNALED TO GO, False IF till WAS SIGNALED
340,279
def replace_function_node(node, annotation): target, funcs = parse_nni_function(annotation) FuncReplacer(funcs, target).visit(node) return node
Replace a node annotated by `nni.function_choice`. node: the AST node to replace annotation: annotation string
340,280
def get_home_position(boatd=None): if boatd is None: boatd = Boatd() content = boatd.get() home = content.get(, None) if home is not None: lat, lon = home return Point(lat, lon) else: return None
Get the current home position from boatd. :returns: The configured home position :rtype: Points
340,281
def _mixup( self, ps ): for i in range(len(ps) - 1, 0, -1): j = int(numpy.random.random() * i) temp = ps[i] ps[i] = ps[j] ps[j] = temp return ps
Private method to mix up a list of values in-place using a Fisher-Yates shuffle (see https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). :param ps: the array :returns: the array, shuffled in-place
340,282
def change_view(self, request, object_id, extra_context=None, **kwargs): "The admin view for this model." model = self.model opts = model._meta obj = self.get_object(request, unquote(object_id)) if not self.has_change_permission(request, obj): raise PermissionDenied...
The 'change' admin view for this model.
340,283
def _is_data_from_today(self, data_point): today = datetime.date.today() raw_timestr = data_point[] dtime = datetime.datetime.strptime(raw_timestr, ) return today.day == dtime.day
Takes a DataPoint from SESConnection.get_send_statistics() and returns True if it is talking about the current date, False if not. :param dict data_point: The data point to consider. :rtype: bool :returns: True if this data_point is for today, False if not (probably ...
340,284
def run(self, group_x=1, group_y=1, group_z=1) -> None: return self.mglo.run(group_x, group_y, group_z)
Run the compute shader. Args: group_x (int): The number of work groups to be launched in the X dimension. group_y (int): The number of work groups to be launched in the Y dimension. group_z (int): The number of work groups to be launched in the Z dimension.
340,285
def build_url_parts (self): self.userinfo, host = urllib.splituser(self.urlparts[1]) port = urlutil.default_ports.get(self.scheme, 0) host, port = urlutil.splitport(host, port=port) if port is None: raise LinkCheckerError(_("URL host %(host)r has invalid por...
Set userinfo, host, port and anchor from self.urlparts. Also checks for obfuscated IP addresses.
340,286
def total_align_count(bam_filepath): count = 0 for line in idxstats(bam_filepath): if line: chrom, _, mapped, unmapped = line.strip().split() if chrom != : count += int(mapped) + int(unmapped) return count
Returns count of all mapped alignments in input BAM (based on index)
340,287
def _get_static_predicate(pred): if pred in {0, 1}: pred_value = bool(pred) elif isinstance(pred, bool): pred_value = pred elif isinstance(pred, tf.Tensor): pred_value = tf.get_static_value(pred) if pred_value is None: pred_value = c_api.TF_TryEvaluateConstant_wrapper(pred.gr...
Helper function for statically evaluating predicates in `cond`.
340,288
def XYZ_to_xyY(cobj, *args, **kwargs): xyz_sum = cobj.xyz_x + cobj.xyz_y + cobj.xyz_z if xyz_sum == 0.0: xyy_x = 0.0 xyy_y = 0.0 else: xyy_x = cobj.xyz_x / xyz_sum xyy_y = cobj.xyz_y / xyz_sum xyy_Y = cobj.xyz_y return xyYColor( xyy_x, xyy_y, xyy_Y,...
Convert from XYZ to xyY.
340,289
def pop(ol,index,**kwargs): list index = uniform_index(index,ol.__len__()) if( in kwargs): mode = kwargs["mode"] else: mode = "new" if(mode == "new"): new = copy.deepcopy(ol) popped = new.pop(index) return({:popped,:new}) else: popped = ol.pop(inde...
from elist.jprint import pobj from elist.elist import * ol = [1,2,3,4] id(ol) rslt = pop(ol,2) pobj(rslt) ol id(ol) id(rslt['list']) #### ol = [1,2,3,4] id(ol) rslt = pop(ol,2,mode="original") rslt ol ...
340,290
def iteritems(self, match=None, count=1): logger.debug(, match) if match is None: match = for key in self._redis.scan_iter(match=match, count=count): yield key, self.get(key)
Return an iterator over the db's (key, value) pairs. ``match`` allows for filtering the keys by pattern. ``count`` allows for hint the minimum number of returns. >>> dc = Dictator() >>> dc['1'] = 'abc' >>> dc['2'] = 'def' >>> dc['3'] = 'ghi' >>> itr = dc.iteritem...
340,291
def range_chain(ranges): endpoints = _make_endpoints(ranges) left_index = {} scores = [] for i, (seqid, pos, leftright, j, score) in enumerate(endpoints): cur_score = [0, -1, -1] if i == 0 else scores[-1][:] if leftright == LEFT: left_index[j] = i ...
Take list of weighted intervals, find non-overlapping set with max weight. We proceed with each end point (sorted by their relative positions). The input are a list of ranges of the form (start, stop, score), output is subset of the non-overlapping ranges that give the highest score, score >>> ranges ...
340,292
def decode_fetch_response(cls, data): ((correlation_id, num_topics), cur) = relative_unpack(, data, 0) for _ in range(num_topics): (topic, cur) = read_short_string(data, cur) ((num_partitions,), cur) = relative_unpack(, data, cur) for j in range(num_partiti...
Decode bytes to a FetchResponse Arguments: data: bytes to decode
340,293
def process_raw_data(cls, raw_data): raw_settings = raw_data.get("qosSettings", {}) qos_settings = QosSettings.from_raw_data(raw_settings) raw_data["qosSettings"] = qos_settings return super(PortSettings, cls).process_raw_data(raw_data)
Create a new model using raw API response.
340,294
def open(cls, path, jpeg_quality=75): "Open compressed data, without transcoding" filename = fspath(path) p_compdata = ffi.new() result = lept.l_generateCIDataForPdf( os.fsencode(filename), ffi.NULL, jpeg_quality, p_compdata ) if result != 0: rais...
Open compressed data, without transcoding
340,295
def _helper_for_model(self, model_type): if model_type is models.containers.Container: return self.containers if model_type is models.images.Image: return self.images if model_type is models.networks.Network: return self.networks if model_type...
Get the helper for a given type of Docker model. For use by resource definitions.
340,296
def getActualLineWidths0(self): assert hasattr(self, ), "Cannot call this method before wrap()" if self.blPara.kind: func = lambda frag, w=self.width: w - frag.extraSpace else: func = lambda frag, w=self.width: w - frag[0] return map(func, self.blPara.li...
Convenience function; tells you how wide each line actually is. For justified styles, this will be the same as the wrap width; for others it might be useful for seeing if paragraphs will fit in spaces.
340,297
def create_stream(self, stream_id, sandbox=None): if stream_id in self.streams: raise StreamAlreadyExistsError("Stream with id already exists".format(stream_id)) if sandbox is not None: raise ValueError("Cannot use sandboxes with memory streams") stream = Stre...
Must be overridden by deriving classes, must create the stream according to the tool and return its unique identifier stream_id
340,298
def revoke_refresh_token(self): if not self._refresh_token: return self.execute_post(, json=dict( token_type_hint=, token=self._refresh_token )) self._refresh_token = None
Revoke the refresh token currently active.
340,299
def draw(self): if sys.stdout.isatty(): from asciimatics.screen import Screen Screen.wrapper(self._do_draw) else: for line in self.canvas: print("".join(line))
Draws ASCII canvas on the screen.