Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
351,800
def build_classes(self,strict=False, named_only=False, standardize_names=True): kw = {"strict": strict} builder = classbuilder.ClassBuilder(self.resolver) for nm, defn in iteritems(self.schema.get(, {})): uri = python_jsonschema_objects.util.resolve_ref_uri( ...
Build all of the classes named in the JSONSchema. Class names will be transformed using inflection by default, so names with spaces in the schema will be camelcased, while names without spaces will have internal capitalization dropped. Thus "Home Address" becomes "HomeAddress", while "H...
351,801
def ConsultarCTGActivosPorPatente(self, patente="ZZZ999"): "Consulta de CTGs activos por patente" ret = self.client.consultarCTGActivosPorPatente(request=dict( auth={ : self.Token, : self.Sign, : self.Cuit, }, ...
Consulta de CTGs activos por patente
351,802
def nodes_gcp(c_obj): gcp_nodes = [] try: gcp_nodes = c_obj.list_nodes(ex_use_disk_cache=True) except BaseHTTPError as e: abort_err("\r HTTP Error with GCP: {}".format(e)) gcp_nodes = adj_nodes_gcp(gcp_nodes) return gcp_nodes
Get node objects from GCP.
351,803
def split_sql(sql): bookends = ("\n", ";", "--", "/*", "*/") last_bookend_found = None start = 0 while start <= len(sql): results = get_next_occurence(sql, start, bookends) if results is None: yield (last_bookend_found, None, sql[start:]) start = len(sql) + ...
generate hunks of SQL that are between the bookends return: tuple of beginning bookend, closing bookend, and contents note: beginning & end of string are returned as None
351,804
def shutdown(self, exitcode=0): logger.info("shutting down system stats and metadata service") self._system_stats.shutdown() self._meta.shutdown() if self._cloud: logger.info("stopping streaming files and file change observer") self._stop_file_observer()...
Stops system stats, streaming handlers, and uploads files without output, used by wandb.monitor
351,805
def FitRadius(z, SampleFreq, Damping, HistBins=100): dt = 1/SampleFreq boltzmann=scipy.constants.Boltzmann temp=300 density=1800 SteadyStatePotnl = list(steady_state_potential(z, HistBins=HistBins)) yoffset=min(SteadyStatePotnl[1]) SteadyStatePotnl[1] -= yoffset SpringPotnlFunc = ...
Fits the dynamical potential to the Steady State Potential by varying the Radius. z : ndarray Position data SampleFreq : float frequency at which the position data was sampled Damping : float value of damping (in radians/second) HistBins : int number of...
351,806
def fit_kmeans(self, data, n_clusters, **kwargs): km = cl.KMeans(n_clusters=n_clusters, **kwargs) km.fit(data) return km
Fit KMeans clustering algorithm to data. Parameters ---------- data : array-like A dataset formatted by `classifier.fitting_data`. n_clusters : int The number of clusters in the data. **kwargs passed to `sklearn.cluster.KMeans`. Retur...
351,807
def calculable(self): self._mode = "" if self.kwargs["T"] and self.kwargs["P"]: self._mode = "TP" elif self.kwargs["T"] and self.kwargs["rho"]: self._mode = "Trho" elif self.kwargs["T"] and self.kwargs["h"] is not None: self._mode = "Th" ...
Check if inputs are enough to define state
351,808
def getCalculationDependencies(self, flat=False, deps=None): if deps is None: deps = [] if flat is True else {} for service in self.getDependentServices(): calc = service.getCalculation() if calc: calc.getCalculationDependencies(flat, deps) ...
Recursively calculates all dependencies of this calculation. The return value is dictionary of dictionaries (of dictionaries...) {service_UID1: {service_UID2: {service_UID3: {}, service_UID4: {}, }, }, ...
351,809
def at_match(self, match, predicate=None, index=None): return self.at_span(match.span, predicate, index)
Retrieves a list of matches from given match.
351,810
def info(self): backend_cls = self.backend_cls or "amqplib" port = self.port or self.create_backend().default_port return {"hostname": self.hostname, "userid": self.userid, "password": self.password, "virtual_host": self.virtual_host, ...
Get connection info.
351,811
def _send_ping(self, dest_addr, payload): pkt_id = self._last_used_id is_ipv6 = in dest_addr if is_ipv6: self._ipv6_address_present = True icmp_echo_request = _ICMPV6_ECHO_REQUEST else: icmp_echo_request = _ICMP_ECHO_REQUEST ...
Send a single ICMPecho (ping) packet to the specified address. The payload must be specified as a packed byte string. Note that its length has to be divisible by 2 for this to work correctly.
351,812
def data(self, value): self.loader.save_image(self.category, self.image, value)
Saves a new image to disk
351,813
async def create_cred( self, cred_offer_json, cred_req_json: str, cred_attrs: dict, rr_size: int = None) -> (str, str, int): LOGGER.debug( , cred_offer_json, cred_req_json, cred_attrs, ...
Create credential as Issuer out of credential request and dict of key:value (raw, unencoded) entries for attributes. Return credential json, and if cred def supports revocation, credential revocation identifier and revocation registry delta ledger timestamp (epoch seconds). If the cred...
351,814
def columnCount(self, index=QModelIndex()): if self.axis == 0: if self.total_cols <= self.cols_loaded: return self.total_cols else: return self.cols_loaded else: return max(1, self._shape[1])
DataFrame column number
351,815
def set_config(self, payload): self.config[][payload[]] = str(payload[]) if payload[] == : self.process_handler.set_max(payload[]) if payload[] == : path = payload[] if os.path.isfile(path) and os.access(path, os.X_OK): self.process_h...
Update the current config depending on the payload and save it.
351,816
def adjust_for_flatpak(self): if self.user_params.flatpak.value: remove_plugins = [ ("prebuild_plugins", "resolve_composes"), ("postbuild_plugins", "pulp_push"), ("postbuild_plugins", "pulp_tag"), ("postbuild_p...
Remove plugins that don't work when building Flatpaks
351,817
def _get_contents_between(string, opener, closer): opener_location = string.index(opener) closer_location = string.index(closer) content = string[opener_location + 1:closer_location] return content
Get the contents of a string between two characters
351,818
def _get_definitions(source): max_len = 0 descs = collections.OrderedDict() lines = (s.strip() for s in source.splitlines()) non_empty_lines = (s for s in lines if s) for line in non_empty_lines: if line: arg, desc = re.split(r, line.strip()) arg_len = len...
Extract a dictionary of arguments and definitions. Args: source: The source for a section of a usage string that contains definitions. Returns: A two-tuple containing a dictionary of all arguments and definitions as well as the length of the longest argument.
351,819
def _iter_step_func_decorators(self): func_defs = [func for func in self.py_tree.iter_funcdefs()] + [func for cls in self.py_tree.iter_classdefs() for func in cls.iter_funcdefs()] for func in func_defs: for decorator in func.get_decorators(): if decorator.children[1]...
Find functions with step decorator in parsed file
351,820
def fire(obj, name, *args, **kwargs): signals = vars(obj).get(, {}) for func in signals.get(name, ()): func(*args, **kwargs)
Arrange for `func(*args, **kwargs)` to be invoked for every function registered for the named signal on `obj`.
351,821
def get_token( user=None, password=None, url=, verify=False, ssl_options=None, version="7.0.3", debug=False): use_user = os.getenv( "SPLUNK_ADMIN_USER", user) use_password = os.getenv( "SPLUNK_ADMIN_PASSWORD", password)...
get_token This will get a user token and throw for any errors :param user: username - defaults to env var: SPLUNK_ADMIN_USER :param password: password - defaults to env var: SPLUNK_ADMIN_PASSWORD :param url: splunk auth url :param verify: verify cert :para...
351,822
def _show_or_save(self, save, show, animate, draw_sidebars=True, draw_title=True, tight_layout=False, subplot_grid=None, **kwargs): if animate and not show and not save: logger.warn...
Draw/animate and show and/or save a autofig plot
351,823
def setText( self, text ): super(XNavigationEdit, self).setText(text) self.scrollWidget().show() if ( text == or self._originalText != text ): self.rebuild()
Sets the text for this edit to the inputed text. :param text | <str>
351,824
def get_calculation_info(self, obj): info = self.get_base_info(obj) info.update({}) return info
Returns the info for a Calculation
351,825
def tile(self, z, x, y): logger.debug(_("Render tile %s") % ((z, x, y),)) proj = GoogleProjection(self.tilesize, [z]) return self.render(proj.tile_bbox((z, x, y)))
Render the specified tile with Mapnik
351,826
def serialize_rules(self, rules): if rule.get("remote_ip_prefix"): prefix = rule["remote_ip_prefix"] if direction == "ingress": source = self._convert_remote_network(prefix) els...
Creates a payload for the redis server.
351,827
def get_options(self, gradebook_id): end_point = .format( gradebookId=gradebook_id or self.gradebook_id) options = self.get(end_point) return options[]
Get options for gradebook. Get options dictionary for a gradebook. Options include gradebook attributes. Args: gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` Returns: An example return value is: .. code-block:: python ...
351,828
def dumps(trees): if isinstance(trees, Node): trees = [trees] return .join([tree.newick for tree in trees]) +
Serialize a list of trees in Newick format. :param trees: List of Node objects or a single Node object. :return: Newick formatted string.
351,829
def user_can_edit_newsitem(user, NewsItem): for perm in format_perms(NewsItem, [, , ]): if user.has_perm(perm): return True return False
Check if the user has permission to edit a particular NewsItem type.
351,830
def word(self): try: output = ensure_unicode(self.git.diff( , , , , ).stdout) except sh.ErrorReturnCode_128: result = ensure_unicode(self.git.show( "HEAD:content" ).st...
Return last changes with word diff
351,831
def links(self): links = super(OffsetLimitPaginatedList, self).links if self._page.offset + self._page.limit < self.count: links["next"] = Link.for_( self._operation, self._ns, qs=self._page.next_page.to_items(), **self...
Include previous and next links.
351,832
def get_one(self, criteria): try: items = [item for item in self._get_with_criteria(criteria, limit=1)] return items[0] except: return None
return one item
351,833
def get_resources_by_bin(self, bin_id): mgr = self._get_provider_manager(, local=True) lookup_session = mgr.get_resource_lookup_session_for_bin(bin_id, proxy=self._proxy) lookup_session.use_isolated_bin_view() return lookup_session.get_resources()
Gets the list of ``Resources`` associated with a ``Bin``. arg: bin_id (osid.id.Id): ``Id`` of a ``Bin`` return: (osid.resource.ResourceList) - list of related resources raise: NotFound - ``bin_id`` is not found raise: NullArgument - ``bin_id`` is ``null`` raise: OperationF...
351,834
def connectionMade(self): self.endpoint = self.transport.getPeer() tmp_addr = Address(f"{self.endpoint.host}:{self.endpoint.port}") try: known_idx = self.leader.KNOWN_ADDRS.index(tmp_addr) self.address = self.leader.KNOWN_ADDRS[known_idx] except ...
Callback handler from twisted when establishing a new connection.
351,835
def update(self, json_state): if self._type in CONST.BINARY_SENSOR_TYPES: self._json_state[] = json_state[] else: self._json_state.update( {k: json_state[k] for k in json_state if self._json_state.get(k)})
Update the json data from a dictionary. Only updates if it already exists in the device.
351,836
def GetMessages(self, formatter_mediator, event): if self.DATA_TYPE != event.data_type: raise errors.WrongFormatter(.format( event.data_type)) event_values = event.CopyToDict() regvalue = event_values.get(, {}) string_parts = [] for key, value in sorted(regvalue.items()): ...
Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. event (EventObject): event. Returns: tuple(str, s...
351,837
def compose(*funcs: Callable) -> Callable: def _compose(*args, **kw): ret = reduce(lambda acc, x: lambda f: f(acc(x)), funcs[::-1], lambda f: f(*args, **kw)) return ret(lambda x: x) return _compose
Compose multiple functions right to left. Composes zero or more functions into a functional composition. The functions are composed right to left. A composition of zero functions gives back the identity function. compose()(x) == x compose(f)(x) == f(x) compose(g, f)(x) == g(f(x)) compose(h...
351,838
def start_output (self): super(TextLogger, self).start_output() if self.has_part(): self.write_intro() self.flush()
Write generic start checking info.
351,839
def itemData(self, treeItem, column, role=Qt.DisplayRole): if role == Qt.DisplayRole: if column == self.COL_NODE_NAME: return treeItem.nodeName elif column == self.COL_NODE_PATH: return treeItem.nodePath elif column == self.COL_VALUE: ...
Returns the data stored under the given role for the item.
351,840
def data_received(self, data): try: self.responders[-1].on_data(data) except Exception as error: self.handle_error(error)
(asyncio.Protocol member) Called upon when there is new data to be passed to the protocol. The data is forwarded to the top of the responder stack (via the on_data method). If an excpetion occurs while this is going on, the Exception is forwarded to the protocol's handle...
351,841
def any_field_choices(function): def wrapper(field, **kwargs): if field.choices: return random.choice(list(valid_choices(field.choices))) return function(field, **kwargs) return wrapper
Selection from field.choices >>> CHOICES = [('YNG', 'Child'), ('OLD', 'Parent')] >>> result = any_field(models.CharField(max_length=3, choices=CHOICES)) >>> result in ['YNG', 'OLD'] True
351,842
def _normalise(self): if not self.is_unit(): n = self.norm if n > 0: self.q = self.q / n
Object is guaranteed to be a unit quaternion after calling this operation UNLESS the object is equivalent to Quaternion(0)
351,843
def ERROR(self): logger.debug() self.current_state = STATE_ERROR if self.script is not None: self.script.script_init(self.client.lease, self.current_state) self.script.script_go() set_net(self.client.lease) raise self.INIT()
ERROR state.
351,844
def file_hash(content): h = hashlib.sha256() if isinstance(content, bytes_type): h.update(content) else: data = True while data: data = content.read(1024 * 1024) h.update(data) h_digest = h.digest() result = base64.b64enco...
Generate hash for file or string and avoid strings starting with "ad" to workaround ad blocks being over aggressiv. The current implementation is based on sha256. :param str|FileIO content: The content to hash, either as string or as file-like object
351,845
def _fix_orig_vcf_refs(data): variantcaller = tz.get_in(("config", "algorithm", "variantcaller"), data) if variantcaller: data["vrn_file_orig"] = data["vrn_file"] for i, sub in enumerate(data.get("group_orig", [])): sub_vrn = sub.pop("vrn_file", None) if sub_vrn: sub...
Supply references to initial variantcalls if run in addition to batching.
351,846
def normalize_filename(filename): filename = re.sub("/|\\|;|:|\?|=", "_", filename) if len(filename) > 150: prefix = hashlib.md5(filename).hexdigest() filename = prefix + filename[-140:] return filename
Remove special characters and shorten if name is too long
351,847
def _setupCache(self): personalCacheDir = .join([os.path.dirname(self.localCacheDir), , str(uuid.uuid4())]) os.mkdir(personalCacheDir, 0o755) self._createCacheLockFile(personalCacheDir) try: ...
Setup the cache based on the provided values for localCacheDir.
351,848
def cleanup(self): self.parser = None self.request = None self.url = None self.headers = None self._request_handler_task = None self._request_stream_task = None self._total_request_size = 0 self._is_stream_handler = False
This is called when KeepAlive feature is used, it resets the connection in order for it to be able to handle receiving another request on the same connection.
351,849
def _dd_to_dms(num: float, _type: str) -> str: degrees = int(num) minutes = int((num - degrees) * 60) seconds = (num - degrees - minutes / 60) * 3600.00 seconds = round(seconds, 3) result = [abs(i) for i in (degrees, minutes, seconds)] direction = if _t...
Convert decimal number to DMS format. :param num: Decimal number. :param _type: Type of number. :return: Number in DMS format.
351,850
def _waitfor(self, mode, mask, may_block, timeout=2): finished = False sleep = 0.01 while not finished: time.sleep(sleep) this = self._read() flags = yubico_util.ord_byte(this[7]) if flags & yubikey_defs.RESP_TIMEOUT_WAIT_FLAG: ...
Wait for the YubiKey to either turn ON or OFF certain bits in the status byte. mode is either 'and' or 'nand' timeout is a number of seconds (precision about ~0.5 seconds)
351,851
def circular_pores(target, pore_diameter=, throat_diameter=, throat_centroid=): r return spherical_pores(target=target, pore_diameter=pore_diameter, throat_diameter=throat_diameter)
r""" Calculate the coordinates of throat endpoints, assuming circular pores. This model accounts for the overlapping lens between pores and throats. Parameters ---------- target : OpenPNM Object The object which this model is associated with. This controls the length of the calculat...
351,852
def log_response(_, _request, response, *_args, **kwargs): if not _LOGGER.isEnabledFor(logging.DEBUG): return None try: _LOGGER.debug("Response status: %r", response.status_code) _LOGGER.debug("Response headers:") for res_header, value in response.headers.items(): ...
Log a server response. :param _: Unused in current version (will be None) :param requests.Request request: The request object. :param requests.Response response: The response object.
351,853
def _validate(self): probably_good_to_go = True sheet = self.table identity = self.db_sheet_cols.id id_col = sheet.loc[:, identity] if any(id_col.duplicated()): warnings.warn( "your database is corrupt: duplicates" " ...
Checks that the db-file is ok Returns: True if OK, False if not.
351,854
def _create_scope(self): res = Scope(self._log) for func_name,native_func in six.iteritems(self._natives): res.add_local(func_name, native_func) return res
TODO: Docstring for _create_scope. :returns: TODO
351,855
def set_file(self, asset_data=None, asset_type=None, asset_content_type=None, asset_name=, asset_description=): if asset_data is None: raise NullArgument() if not isinstance(asset_data, DataInputStr...
stub
351,856
def last_metric_eval(multiplexer, session_name, metric_name): try: run, tag = run_tag_from_session_and_metric(session_name, metric_name) tensor_events = multiplexer.Tensors(run=run, tag=tag) except KeyError as e: raise KeyError( t find metric %s for session: %s. Underlying error message: %s' ...
Returns the last evaluations of the given metric at the given session. Args: multiplexer: The EventMultiplexer instance allowing access to the exported summary data. session_name: String. The session name for which to get the metric evaluations. metric_name: api_pb2.MetricName proto. The ...
351,857
def copy(self, contents=True): cp = connection(collection=self._db_coll, baseiri=self._baseiri) if contents: cp.add_many(self._relationships) return cp
Create a copy of this model, optionally without contents (i.e. just configuration)
351,858
def AddPmf(self, other): pmf = Pmf() for v1, p1 in self.Items(): for v2, p2 in other.Items(): pmf.Incr(v1 + v2, p1 * p2) return pmf
Computes the Pmf of the sum of values drawn from self and other. other: another Pmf returns: new Pmf
351,859
def findspan(self, *words): for span in self.select(AbstractSpanAnnotation,None,True): if tuple(span.wrefs()) == words: return span raise NoSuchAnnotation
Returns the span element which spans over the specified words or morphemes. See also: :meth:`Word.findspans`
351,860
def to_string(self, other): arg = "%s/%s,%s" % ( self.ttl, self.get_remaining_ttl(current_time_millis()), other) return DNSEntry.to_string(self, "record", arg)
String representation with addtional information
351,861
def build(surname, name, birthday, sex, municipality): output = __surname_triplet(surname) + __name_triplet(name) output += str(birthday.year)[2:] output += MONTHSCODE[birthday.month - 1] output += "%02d" % (sex.upper() == and birthday.day or 40 + birthday.day) ou...
``build(surname, name, birthday, sex, municipality) -> string`` Computes the fiscal code for the given person data. eg: build('Rocca', 'Emanuele', datetime.datetime(1983, 11, 18), 'M', 'D969') -> RCCMNL83S18D969H
351,862
def rubberstamp(rest): "Approve something" parts = ["Bad credit? No credit? Slow credit?"] rest = rest.strip() if rest: parts.append("%s is" % rest) karma.Karma.store.change(rest, 1) parts.append("APPROVED!") return " ".join(parts)
Approve something
351,863
def addAction(self, action): super(XDockToolbar, self).addAction(action) label = XDockActionLabel(action, self.minimumPixmapSize(), self) label.setPosition(self.position()) layout = self.layout() layout.insertWidget(layout.count() - 1, label)
Adds the inputed action to this toolbar. :param action | <QAction>
351,864
def cancel(self, msg=, exc_type=CancelledError): with self._lock: if not self.done(): should_announce_done = False logger.debug(, self, msg) self._exception = exc_type(msg) if self._status == : should_announ...
Cancels the TransferFuture :param msg: The message to attach to the cancellation :param exc_type: The type of exception to set for the cancellation
351,865
def _with_retries(self, pool, fn): skip_nodes = [] def _skip_bad_nodes(transport): return transport._node not in skip_nodes retry_count = self.retries - 1 first_try = True current_try = 0 while True: try: with pool.transa...
Performs the passed function with retries against the given pool. :param pool: the connection pool to use :type pool: Pool :param fn: the function to pass a transport :type fn: function
351,866
def AddDischargingBattery(self, device_name, model_name, percentage, seconds_to_empty): path = + device_name self.AddObject(path, DEVICE_IFACE, { : dbus.Boolean(True, variant_level=1), : dbus.Boolean(True, variant_level=1)...
Convenience method to add a discharging battery object You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac", an arbitrary model name, the charge percentage, and the seconds until the battery is empty. Please note that this does not set any global properties s...
351,867
def get_mvgd_lvla_lvgd_obj_from_id(self): mv_grid_districts_dict = {} lv_load_areas_dict = {} lv_grid_districts_dict = {} lv_stations_dict = {} for mv_grid_district in self.mv_grid_districts(): mv_grid_districts_dict[mv_grid_district.id_db] = mv_grid_distri...
Build dict with mapping from LVLoadAreaDing0 id to LVLoadAreaDing0 object, MVGridDistrictDing0 id to MVGridDistrictDing0 object, LVGridDistrictDing0 id to LVGridDistrictDing0 object and LVStationDi...
351,868
def rts_smooth(kalman_filter, state_count=None): if state_count is None: state_count = kalman_filter.state_count state_count = int(state_count) if state_count < 0 or state_count > kalman_filter.state_count: raise ValueError("Invalid state count: {}".format(state_count)) if st...
Compute the Rauch-Tung-Striebel smoothed state estimates and estimate covariances for a Kalman filter. Args: kalman_filter (KalmanFilter): Filter whose smoothed states should be returned state_count (int or None): Number of smoothed states to return. If None, use ``kalma...
351,869
def run(self): self._stop = False while not self._stop: have_sources = self._timers or self._readers or self._writers if not self._processor.pending and not have_sources: break events = QEventLoop.AllEvents if not self._processor.p...
Run until there are no more events. This only looks at events scheduled through the event loop.
351,870
def get_default_session_filename(username: str) -> str: dirname = tempfile.gettempdir() + "/" + ".instaloader-" + getpass.getuser() filename = dirname + "/" + "session-" + username return filename.lower()
Returns default session filename for given username.
351,871
def timeout_request_renewing(self): logger.debug("C5.2:T In %s, timeout receiving response to request.", self.current_state) if self.request_attempts >= MAX_ATTEMPTS_REQUEST: logger.debug( , MAX_ATTEMPTS_REQUEST,...
Timeout of renewing on RENEWING state. Same comments as in :func:`dhcpcapfsm.DHCPCAPFSM.timeout_requesting`.
351,872
def remove_study(self, first_arg, sec_arg, third_arg, fourth_arg=None, commit_msg=None): if fourth_arg is None: study_id, branch_name, author = first_arg, sec_arg, third_arg gh_user = branch_name.split()[0] parent_sha = self.get_master_sha() else: ...
Remove a study Given a study_id, branch and optionally an author, remove a study on the given branch and attribute the commit to author. Returns the SHA of the commit on branch.
351,873
def put(self, key): self.client.put_object( Body=json.dumps(key), Bucket=self.db_path, Key=key[]) return key[]
Insert the key :return: Key name
351,874
def convert_table(self, table_name, cls_att=None): import Orange cols = self.db.cols[table_name] attributes, metas, class_var = [], [], None for col in cols: att_type = self.orng_type(table_name, col) if att_type == : att_vals = self.db.c...
Returns the specified table as an orange example table. :param table_name: table name to convert :cls_att: class attribute name :rtype: orange.ExampleTable
351,875
def parse_string_to_constructor(ctor_string): orig_ctor_string = ctor_string if "." not in ctor_string: ctor_string = "sonnet." + ctor_string if ctor_string.startswith("snt."): ctor_string = "sonnet." + ctor_string[len("snt."):] package_name, rest = ctor_string.split(".", 1) ...
Returns a callable which corresponds to the constructor string. Various modules (eg, ConvNet2D) take constructor arguments which are callables, indicating a submodule to build. These can be passed as actual constructors, eg `snt.LayerNorm`, however that makes the config for that module not trivially serializab...
351,876
def _learner_interpret(learn:Learner, ds_type:DatasetType=DatasetType.Valid): "Create a `ClassificationInterpretation` object from `learner` on `ds_type` with `tta`." return ClassificationInterpretation.from_learner(learn, ds_type=ds_type)
Create a `ClassificationInterpretation` object from `learner` on `ds_type` with `tta`.
351,877
def _build_gadgets(self, gadget_tree_root): node_list = self._build_gadgets_rec(gadget_tree_root) return [RawGadget(n) for n in node_list]
Return a gadgets list.
351,878
def get_linter_config(self, name): prefix = name + return {k[len(prefix):]: v for k, v in self._config.items() if k.startswith(prefix)}
Return linter options without linter name prefix.
351,879
def _append_node(self, child): self.body.append(child) child.parent = self
append a child, linking it in the tree
351,880
def view_fullreport(token, dstore): from openquake.calculators.reportwriter import ReportWriter return ReportWriter(dstore).make_report()
Display an .rst report about the computation
351,881
def save_lost(self, service_name): self._load_ready_file() self._ready.discard(service_name) self._save_ready_file()
Save an indicator that the given service is no longer data_ready.
351,882
def fastcc(model, flux_threshold=1.0, zero_cutoff=None): r zero_cutoff = normalize_cutoff(model, zero_cutoff) with model: obj_vars = [] vars_and_cons = [] prob = model.problem for rxn in model.reactions: var = prob.Variable("auxiliary_{}".format(rxn.id), ...
r""" Check consistency of a metabolic network using FASTCC [1]_. FASTCC (Fast Consistency Check) is an algorithm for rapid and efficient consistency check in metabolic networks. FASTCC is a pure LP implementation and is low on computation resource demand. FASTCC also circumvents the problem associa...
351,883
def namedb_account_debit(cur, account_addr, token_type, amount, block_id, vtxindex, txid): account = namedb_get_account(cur, account_addr, token_type) if account is None: traceback.print_stack() log.fatal(.format(account_addr)) os.abort() new_credit_value = account[] new_de...
Debit an account at a particular point in time by the given amount. Insert a new history entry for the account into the accounts table. The account must exist Abort the program if the account balance goes negative, or the count does not exist
351,884
def binarize_rdp(netin, level, sign=, axis=): netin, netinfo = process_input(netin, [, , ]) trajectory = rdp(netin, level) contacts = [] for n in range(trajectory[].shape[0]): if sign == : sel = trajectory[][n][trajectory[] ...
Binarizes a network based on RDP compression. Parameters ---------- netin : array or dict Network (graphlet or contact representation), level : float Delta parameter which is the tolorated error in RDP compression. sign : str, default='pos' States the sign of the thresholdi...
351,885
def announceManagementEvent(self, action, varBind, **context): name, val = varBind cbFun = context[] if not self._augmentingRows: cbFun(varBind, **context) return instId = name[len(self.name) + 1:] baseIndices = [] indices = []...
Announce mass operation on parent table's row. SNMP SMI provides a way to extend already existing SMI table with another table. Whenever a mass operation on parent table's column is performed (e.g. row creation or destruction), this operation has to be propagated over all the extending ...
351,886
def refund_payment(self, payment_psp_object: Model, amount: Money, client_ref: str) -> Tuple[bool, Model]: pass
:param payment_psp_object: an instance representing the original payment in the psp :param amount: the amount to refund :param client_ref: a reference that will appear on the customer's credit card statement :return: a tuple (success, refund_psp_object)
351,887
def randomString(length, chrs=None): if chrs is None: return getBytes(length) else: n = len(chrs) return .join([chrs[randrange(n)] for _ in xrange(length)])
Produce a string of length random bytes, chosen from chrs.
351,888
def _execShowCmd(self, showcmd): result = None lines = self._execCmd("show", showcmd) if lines and len(lines) >= 2 and lines[0] != and lines[0][0] != : result = {} result[] = lines[0].split() items = [] for line in lines[1:]: ...
Execute 'show' command and return result dictionary. @param cmd: Command string. @return: Result dictionary.
351,889
def get_hash(self, ireq, ireq_hashes=None): if not self._should_include_hash(ireq): return set() elif self._should_include_hash(ireq) and ( not ireq_hashes or ireq.link.scheme == "file" ): if not ...
Retrieve hashes for a specific ``InstallRequirement`` instance. :param ireq: An ``InstallRequirement`` to retrieve hashes for :type ireq: :class:`~pip_shims.InstallRequirement` :return: A set of hashes. :rtype: Set
351,890
def get_tr(self): cell_above = CellBorders(self.cell_attributes, *self.cell.get_above_key_rect()) return cell_above.get_r()
Returns the top right border of the cell
351,891
def as_ul(self, current_linkable=False, class_current="active_link", before_1="", after_1="", before_all="", after_all=""): return self.__do_menu("as_ul", current_linkable, class_current, before_1=before_1, after_1=after_1, before_all=before_all, after_all=af...
It returns menu as ul
351,892
def compute_payload_block_hash(this): return hmac.new( hashlib.sha512( struct.pack(, this._index) + hashlib.sha512( this._._.header.value.dynamic_header.master_seed.data + this._.transformed_key + b ).digest() ).digest(), ...
Compute hash of each payload block. Used to prevent payload corruption and tampering.
351,893
def script_load(self, script): sha_digest = sha1(script.encode("utf-8")).hexdigest() self.shas[sha_digest] = script return sha_digest
Emulate script_load
351,894
def iterexpand(arry, extra): for d in range(arry.ndim, arry.ndim+extra): arry = expand_dims(arry, axis=d) return arry
Expand dimensions by iteratively append empty axes. Parameters ---------- arry : ndarray The original array extra : int The number of empty axes to append
351,895
def uploadFileToIM (self, directory, filename, title): self.logger.debug("uploadFileToIM(" + "{},{},{})".format(directory, filename, title)) parameters = {:, :str(filename), :str(filename), :, :, ...
Parameters as they look in the form for uploading packages to IM
351,896
def default(self, obj): if isinstance(obj, BioCDocument): return encode_document(obj) if isinstance(obj, BioCCollection): return encode_collection(obj) raise TypeError(f)
Implement this method in a subclass such that it returns a tree for ``o``.
351,897
def setfd(self, time): _runshell([brctlexe, , self.name, str(time)], "Could not set forward delay in %s." % self.name)
Set bridge forward delay time value.
351,898
def remove_many(ol,values,seqs,**kwargs): abaabbababaabbab if( in kwargs): mode = kwargs["mode"] else: mode = "new" values = copy.deepcopy(values) seqs = copy.deepcopy(seqs) cursors = [-1] * values.__len__() new = [] length = ol.__len__() cpol = copy.deepcopy(ol) ...
from elist.elist import * ol = [1,'a',3,'b',5,'a',6,'a',7,'b',8,'b',9] id(ol) new = remove_many(ol,['a','b'],[1,2]) ol new id(ol) id(new) #### ol = [1,'a',3,'b',5,'a',6,'a',7,'b',8,'b',9] id(ol) rslt = remove_many(ol,['a','b'],[1,2]...
351,899
def _message_symbol(self, msgid): try: return [md.symbol for md in self.msgs_store.get_message_definitions(msgid)] except UnknownMessageError: return msgid
Get the message symbol of the given message id Return the original message id if the message does not exist.