Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
375,700
def sasets(self) -> : if not self._loaded_macros: self._loadmacros() self._loaded_macros = True return SASets(self)
This methods creates a SASets object which you can use to run various analytics. See the sasets.py module. :return: sasets object
375,701
def configure_config(graph): ns = Namespace( subject=Config, ) convention = ConfigDiscoveryConvention( graph, ) convention.configure(ns, retrieve=tuple()) return convention.config_discovery
Configure the health endpoint. :returns: the current service configuration
375,702
def check(text): err = "strunk_white.composition" msg = "Try instead of ." bad_forms = [ ["dishonest", ["not honest"]], ["trifling", ["not important"]], ["forgot", ["did not remember"]], ["ignored", ...
Suggest the preferred forms.
375,703
def get(self, fields=[]): request = TOPRequest() if not fields: shopCat = ShopCat() fields = shopCat.fields request[] = fields self.create(self.execute(request)) return self.shop_cats
taobao.shopcats.list.get 获取前台展示的店铺类目 此API获取淘宝面向买家的浏览导航类目 跟后台卖家商品管理的类目有差异
375,704
def releases(self): return self._h._get_resources( resource=(, self.name, ), obj=Release, app=self )
The releases for this app.
375,705
def colors_no_palette(colors=None, **kwds): if isinstance(colors, str): colors = _split_colors(colors) else: colors = to_triplets(colors or ()) colors = (color(c) for c in colors or ()) return palette.Palette(colors, **kwds)
Return a Palette but don't take into account Pallete Names.
375,706
def remove(self, ref, cb=None): if self.is_api: return self._remove_api(ref, cb) else: return self._remove_fs(ref, cb)
Check in a bundle to the remote
375,707
def threshold(self, value): if isinstance(value, SpamThreshold): self._threshold = value else: self._threshold = SpamThreshold(value)
Threshold used to determine if your content qualifies as spam. On a scale from 1 to 10, with 10 being most strict, or most likely to be considered as spam. :param value: Threshold used to determine if your content qualifies as spam. On a scale from 1 ...
375,708
def eval_adiabatic_limit(YABFGN, Ytilde, P0): Y, A, B, F, G, N = YABFGN Klim = (P0 * (B - A * Ytilde * A) * P0).expand().simplify_scalar() Hlim = ((Klim - Klim.dag())/2/I).expand().simplify_scalar() Ldlim = (P0 * (G - A * Ytilde * F) * P0).expand().simplify_scalar() dN = identity_matrix(N.sh...
Compute the limiting SLH model for the adiabatic approximation Args: YABFGN: The tuple (Y, A, B, F, G, N) as returned by prepare_adiabatic_limit. Ytilde: The pseudo-inverse of Y, satisfying Y * Ytilde = P0. P0: The projector onto the null-space of Y. Returns: SLH: L...
375,709
def _setup_advanced_theme(self, theme_name, output_dir, advanced_name): output_theme_dir = os.path.join(output_dir, advanced_name) output_images_dir = os.path.join(output_theme_dir, advanced_name) input_theme_dir = os.path.join( utils.get_themes_directory(theme_name...
Setup all the files required to enable an advanced theme. Copies all the files over and creates the required directories if they do not exist. :param theme_name: theme to copy the files over from :param output_dir: output directory to place the files in
375,710
def read(self, size=sys.maxsize): blob_size = int(self.blob_properties.get()) if self._pointer < blob_size: chunk = self._download_chunk_with_retries( chunk_offset=self._pointer, chunk_size=size) self._pointer += size return chunk
Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes).
375,711
def field_from_django_field(cls, field_name, django_field, readonly): FieldWidget = cls.widget_from_django_field(django_field) widget_kwargs = cls.widget_kwargs_for_field(field_name) field = cls.DEFAULT_RESOURCE_FIELD( attribute=field_name, column_name=field_nam...
Returns a Resource Field instance for the given Django model field.
375,712
def close_session(self): if not self._session.closed: if self._session._connector_owner: self._session._connector.close() self._session._connector = None
Close current session.
375,713
def patch(self, id_or_uri, operation, path, value, timeout=-1, custom_headers=None): patch_request_body = [{: operation, : path, : value}] return self.patch_request(id_or_uri=id_or_uri, body=patch_request_body, timeout=timeout...
Uses the PATCH to update a resource. Only one operation can be performed in each PATCH call. Args: id_or_uri: Can be either the resource ID or the resource URI. operation: Patch operation path: Path value: Value timeout: Timeout in seconds. W...
375,714
def _update_partition_srvc_node_ip(self, tenant_name, srvc_ip, vrf_prof=None, part_name=None): self.dcnm_obj.update_project(tenant_name, part_name, service_node_ip=srvc_ip, vrf_prof=vrf_prof...
Function to update srvc_node address of partition.
375,715
def is_not_inf(self): self._validate_number() self._validate_real() if math.isinf(self.val): self._err() return self
Asserts that val is real number and not Inf (infinity).
375,716
def _run_cromwell(args): main_file, json_file, project_name = _get_main_and_json(args.directory) work_dir = utils.safe_makedir(os.path.join(os.getcwd(), "cromwell_work")) final_dir = utils.safe_makedir(os.path.join(work_dir, "final")) if args.no_container: _remove_bcbiovm_path() log_fil...
Run CWL with Cromwell.
375,717
def indent(text, n=4): _indent = * n return .join(_indent + line for line in text.split())
Indent each line of text by n spaces
375,718
def add(self, event, subscriber, append=True): subs = self._subscribers if event not in subs: subs[event] = deque([subscriber]) else: sq = subs[event] if append: sq.append(subscriber) else: sq.appendleft(sub...
Add a subscriber for an event. :param event: The name of an event. :param subscriber: The subscriber to be added (and called when the event is published). :param append: Whether to append or prepend the subscriber to an existing subscriber list ...
375,719
def make_doc(self): res = {} for column in self.columns: if isinstance(column[], ColumnProperty): key = column[] label = column[].columns[0].info.get( , {} ).get() if label is None: ...
Generate the doc for the current context in the form {'key': 'label'}
375,720
def add_text(self, text, cursor=None, justification=None): if cursor is None: cursor = self.page.cursor text = re.sub("\s\s+" , " ", text) if justification is None: justification = self.justification if in text: text_list = text...
Input text, short or long. Writes in order, within the defined page boundaries. Sequential add_text commands will print without additional whitespace.
375,721
def _get_config(): cfg = os.path.expanduser() try: fic = open(cfg) try: config = json.loads(fic.read()) finally: fic.close() except Exception: config = {: } if not in config: config[] = {} return config
Get user docker configuration Return: dict
375,722
def main_generate(table_names, stream): with stream.open() as fp: fp.write_line("from datetime import datetime, date") fp.write_line("from decimal import Decimal") fp.write_line("from prom import Orm, Field") fp.write_newlines() for table_name, inter, fields in get_tabl...
This will print out valid prom python code for given tables that already exist in a database. This is really handy when you want to bootstrap an existing database to work with prom and don't want to manually create Orm objects for the tables you want to use, let `generate` do it for you
375,723
def getpath(self, section, option): return os.path.expanduser(os.path.expandvars(self.get(section, option)))
Return option as an expanded path.
375,724
def _prepare_output(partitions, verbose): out = {} partitions_count = len(partitions) out[] = { : partitions_count, } if partitions_count == 0: out[] = else: out[] = "{count} offline partitions.".format(count=partitions_count) if verbose: lines ...
Returns dict with 'raw' and 'message' keys filled.
375,725
def remove_description(self, id, **kwargs): kwargs[] = True if kwargs.get(): return self.remove_description_with_http_info(id, **kwargs) else: (data) = self.remove_description_with_http_info(id, **kwargs) return data
Remove description from a specific source # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.remove_description(id, async_req=True) >>> result = thread.get() ...
375,726
def up(self, migration_id=None, fake=False): if not self.check_directory(): return for migration in self.get_migrations_to_up(migration_id): logger.info( % migration.filename) migration_module = self.load_migration_file(migration.filename) if no...
Executes migrations.
375,727
def increase_fcp_usage(self, fcp, assigner_id=None): connections = self.db.get_connections_from_assigner(assigner_id) new = False if connections == 0: self.db.assign(fcp, assigner_id) new = True else: self.db.increase_usage(fcp) ...
Incrase fcp usage of given fcp Returns True if it's a new fcp, otherwise return False
375,728
def fingers_needed(fingering): split = False indexfinger = False minimum = min(finger for finger in fingering if finger) result = ...
Return the number of fingers needed to play the given fingering.
375,729
def load_additional_data(self, valid_data, many, original_data): if many: for i, _ in enumerate(valid_data): additional_keys = set(original_data[i]) - set(valid_data[i]) for key in additional_keys: valid_data[i][key] = original_data[i][key...
Include unknown fields after load. Unknown fields are added with no processing at all. Args: valid_data (dict or list): validated data returned by ``load()``. many (bool): if True, data and original_data are a list. original_data (dict or list): data passed to ``loa...
375,730
def _salt_send_domain_event(opaque, conn, domain, event, event_data): prefixobjectevent data = { : { : domain.name(), : domain.ID(), : domain.UUIDString() }, : event } data.update(event_data) _salt_send_event(opaque, conn, data)
Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of...
375,731
def wait(self): self._done_event.wait(MAXINT) return self._status, self._exception
wait for the done event to be set - no timeout
375,732
def controlled(self, control_qubit): control_qubit = unpack_qubit(control_qubit) self.modifiers.insert(0, "CONTROLLED") self.qubits.insert(0, control_qubit) return self
Add the CONTROLLED modifier to the gate with the given control qubit.
375,733
def OnOpen(self, event): if undo.stack().haschanged(): save_choice = self.interfaces.get_save_request_from_user() if save_choice is None: return elif save_choice: post_command_event(self.ma...
File open event handler
375,734
def parse(self): delimiter = "|" csv_file = self.xlsx_to_csv(self.getInputFile(), delimiter=delimiter) reader = csv.DictReader(csv_file, delimiter=delimiter) for n, row in enumerate(reader): resid = row.get("SampleID", None) serial = row.get("S...
parse the data
375,735
def fromvars(cls, dataset, batch_size, train=None, **kwargs): batch = cls() batch.batch_size = batch_size batch.dataset = dataset batch.fields = dataset.fields.keys() for k, v in kwargs.items(): setattr(batch, k, v) return batch
Create a Batch directly from a number of Variables.
375,736
def flash_spi_attach(self, hspi_arg): arg = struct.pack(, hspi_arg) if not self.IS_STUB: self.check_command("configure SPI flash pins", ESP32ROM.ESP_SPI_ATTACH, arg)
Send SPI attach command to enable the SPI flash pins ESP8266 ROM does this when you send flash_begin, ESP32 ROM has it as a SPI command.
375,737
def key_value_contents(use_dict=None, as_class=dict, key_values=()): if _debug: key_value_contents._debug("key_value_contents use_dict=%r as_class=%r key_values=%r", use_dict, as_class, key_values) if use_dict is None: use_dict = as_class() for k, v in key_values: if v is no...
Return the contents of an object as a dict.
375,738
def set_device_id(self, dev, id): if id < 0 or id > 255: raise ValueError("ID must be an unsigned byte!") com, code, ok = io.send_packet( CMDTYPE.SETID, 1, dev, self.baudrate, 5, id) if not ok: raise_error(code)
Set device ID to new value. :param str dev: Serial device address/path :param id: Device ID to set
375,739
def has(self, block, name): try: return self._kvs.has(self._key(block, name)) except KeyError: return False
Return whether or not the field named `name` has a non-default value
375,740
def __decode_dictionary(self, message_type, dictionary): message = message_type() for key, value in six.iteritems(dictionary): if value is None: try: message.reset(key) except AttributeError: pass ...
Merge dictionary in to message. Args: message: Message to merge dictionary in to. dictionary: Dictionary to extract information from. Dictionary is as parsed from JSON. Nested objects will also be dictionaries.
375,741
def reset(self): self.quit() self.driver_args[] = self.default_service_args self.dcap = dict(webdriver.DesiredCapabilities.PHANTOMJS) self._create_session()
Kills old session and creates a new one with no proxies or headers
375,742
def make_2d(array, verbose=True): array = np.asarray(array) if array.ndim < 2: msg = \ .format(array.ndim) if verbose: warnings.warn(msg) array = np.atleast_1d(array)[:,None] return array
tiny tool to expand 1D arrays the way i want Parameters ---------- array : array-like verbose : bool, default: True whether to print warnings Returns ------- np.array of with ndim = 2
375,743
def propmerge(into, data_from): newprops = copy.deepcopy(into) for prop, propval in six.iteritems(data_from): if prop not in newprops: newprops[prop] = propval continue new_sp = newprops[prop] for subprop, spval in six.iteritems(propval): if sub...
Merge JSON schema requirements into a dictionary
375,744
def _read_from_cwlinput(in_file, work_dir, runtime, parallel, input_order, output_cwl_keys): with open(in_file) as in_handle: inputs = json.load(in_handle) items_by_key = {} input_files = [] passed_keys = set([]) for key, input_val in ((k, v) for (k, v) in inputs.items() if not k.starts...
Read data records from a JSON dump of inputs. Avoids command line flattening of records.
375,745
def searchForMessageIDs(self, query, offset=0, limit=5, thread_id=None): thread_id, thread_type = self._getThread(thread_id, None) data = { "query": query, "snippetOffset": offset, "snippetLimit": limit, "identifier": "thread_fbid", "...
Find and get message IDs by query :param query: Text to search for :param offset: Number of messages to skip :param limit: Max. number of messages to retrieve :param thread_id: User/Group ID to search in. See :ref:`intro_threads` :type offset: int :type limit: int ...
375,746
def reset_selective(self, regex=None): if regex is not None: try: m = re.compile(regex) except TypeError: raise TypeError() for ns in self.all_ns_refs: for var in ns: if m.s...
Clear selective variables from internal namespaces based on a specified regular expression. Parameters ---------- regex : string or compiled pattern, optional A regular expression pattern that will be used in searching variable names in the users namespaces.
375,747
def blacklist_token(): req = flask.request.get_json(force=True) data = guard.extract_jwt_token(req[]) blacklist.add(data[]) return flask.jsonify(message=.format(req[]))
Blacklists an existing JWT by registering its jti claim in the blacklist. .. example:: $ curl http://localhost:5000/blacklist_token -X POST \ -d '{"token":"<your_token>"}'
375,748
def predict(self, a, b): a = np.array(a).reshape((-1, 1)) b = np.array(b).reshape((-1, 1)) return (mutual_info_regression(a, b.reshape((-1,))) + mutual_info_regression(b, a.reshape((-1,))))/2
Compute the test statistic Args: a (array-like): Variable 1 b (array-like): Variable 2 Returns: float: test statistic
375,749
def send(self, stream, msg_or_type, content=None, parent=None, ident=None, buffers=None, subheader=None, track=False, header=None): if not isinstance(stream, (zmq.Socket, ZMQStream)): raise TypeError("stream must be Socket or ZMQStream, not %r"%type(stream)) elif track...
Build and send a message via stream or socket. The message format used by this function internally is as follows: [ident1,ident2,...,DELIM,HMAC,p_header,p_parent,p_content, buffer1,buffer2,...] The serialize/unserialize methods convert the nested message dict into this format...
375,750
def solve_potts_approx(y, w, gamma=None, min_size=1, **kw): n = len(y) if n == 0: return [], [], [] mu_dist = kw.get() if mu_dist is None: mu_dist = get_mu_dist(y, w) kw[] = mu_dist if gamma is None: mu, dist = mu_dist.mu, mu_dist.dist gamma = 3 * dist...
Fit penalized stepwise constant function (Potts model) to data approximatively, in linear time. Do this by running the exact solver using a small maximum interval size, and then combining consecutive intervals together if it decreases the cost function.
375,751
def inside_polygon(x, y, coordinates): contained = False i = -1 y1 = coordinates[1][-1] y_gt_y1 = y > y1 for y2 in coordinates[1]: y_gt_y2 = y > y2 if y_gt_y1: if not y_gt_y2: x1 = coordinates[0][i] x2 = coordinates[0][i + 1] ...
Implementing the ray casting point in polygon test algorithm cf. https://en.wikipedia.org/wiki/Point_in_polygon#Ray_casting_algorithm :param x: :param y: :param coordinates: a polygon represented by a list containing two lists (x and y coordinates): [ [x1,x2,x3...], [y1,y2,y3...]] those ...
375,752
def set_custom_serializer(self, _type, serializer): validate_type(_type) validate_serializer(serializer, StreamSerializer) self._custom_serializers[_type] = serializer
Assign a serializer for the type. :param _type: (Type), the target type of the serializer :param serializer: (Serializer), Custom Serializer constructor function
375,753
def get_time(self) -> float: if self.pause_time is not None: curr_time = self.pause_time - self.offset - self.start_time return curr_time curr_time = time.time() return curr_time - self.start_time - self.offset
Get the current time in seconds Returns: The current time in seconds
375,754
def memory_zones(self): count = self.num_memory_zones() if count == 0: return list() buf = (structs.JLinkMemoryZone * count)() res = self._dll.JLINK_GetMemZones(buf, count) if res < 0: raise errors.JLinkException(res) return list(buf)
Gets all memory zones supported by the current target. Some targets support multiple memory zones. This function provides the ability to get a list of all the memory zones to facilate using the memory zone routing functions. Args: self (JLink): the ``JLink`` instance ...
375,755
def get_messages(self): uri = .format(self.data["uri"]) return self._helper.do_get(uri)
Retrieves the error or status messages associated with the specified profile. Returns: dict: Server Profile Health.
375,756
def set_children(self, value, defined): self.children = value self.children_defined = defined return self
Set the children of the object.
375,757
def get_bibliography(lsst_bib_names=None, bibtex=None): bibtex_data = get_lsst_bibtex(bibtex_filenames=lsst_bib_names) pybtex_data = [pybtex.database.parse_string(_bibtex, ) for _bibtex in bibtex_data.values()] if bibtex is not None: pybtex_data.append(pybtex.data...
Make a pybtex BibliographyData instance from standard lsst-texmf bibliography files and user-supplied bibtex content. Parameters ---------- lsst_bib_names : sequence of `str`, optional Names of lsst-texmf BibTeX files to include. For example: .. code-block:: python ['lsst',...
375,758
def splay(vec): N2 = 2 ** int(numpy.log2( len(vec) ) / 2) N1 = len(vec) / N2 return N1, N2
Determine two lengths to split stride the input vector by
375,759
def extract_notification_payload(process_output): data = [] for element in process_output.splitlines()[1:]: parts = element.split(": ") if len(parts) == 2: data.append(parts[1]) return data
Processes the raw output from Gatttool stripping the first line and the 'Notification handle = 0x000e value: ' from each line @param: process_output - the raw output from a listen commad of GattTool which may look like this: Characteristic value was written successfully ...
375,760
def fill_subparser(subparser): sets = [, , ] urls = [ + .format(s) for s in sets] filenames = [.format(s) for s in sets] subparser.set_defaults(urls=urls, filenames=filenames) return default_downloader
Sets up a subparser to download the binarized MNIST dataset files. The binarized MNIST dataset files (`binarized_mnist_{train,valid,test}.amat`) are downloaded from Hugo Larochelle's website [HUGO]. .. [HUGO] http://www.cs.toronto.edu/~larocheh/public/datasets/ binarized_mnist/binarized_mnist_{...
375,761
def _CheckPacketSize(cursor): cur_packet_size = int(_ReadVariable("max_allowed_packet", cursor)) if cur_packet_size < MAX_PACKET_SIZE: raise Error( "MySQL max_allowed_packet of {0} is required, got {1}. " "Please set max_allowed_packet={0} in your MySQL config.".format( MAX_PACKET...
Checks that MySQL packet size is big enough for expected query size.
375,762
def get_media_list_by_selector( self, media_selector, media_attribute="src" ): page_url = urlparse.urlparse(self.uri) return [ mediafile.get_instance( urlparse.urljoin( "%s://%s" % ( page_url.scheme, ...
Return a list of media.
375,763
def _expected_condition_find_first_element(self, elements): from toolium.pageelements.page_element import PageElement element_found = None for element in elements: try: if isinstance(element, PageElement): element._web_element = None ...
Try to find sequentially the elements of the list and return the first element found :param elements: list of PageElements or element locators as a tuple (locator_type, locator_value) to be found sequentially :returns: first element found or None :rtype: toolium.pageele...
375,764
def decrypt(private, ciphertext, output): privatekeydata = json.load(private) assert in privatekeydata pub = load_public_key(privatekeydata[]) log("Loading private key") private_key_error = "Invalid private key" assert in privatekeydata, private_key_error assert "decrypt" in privatek...
Decrypt ciphertext with private key. Requires PRIVATE key file and the CIPHERTEXT encrypted with the corresponding public key.
375,765
async def fetch_message(self, id): channel = await self._get_channel() data = await self._state.http.get_message(channel.id, id) return self._state.create_message(channel=channel, data=data)
|coro| Retrieves a single :class:`.Message` from the destination. This can only be used by bot accounts. Parameters ------------ id: :class:`int` The message ID to look for. Raises -------- :exc:`.NotFound` The specified message...
375,766
def _is_gitted(self): from os import waitpid from subprocess import Popen, PIPE premote = Popen("cd {}; git remote -v".format(self.repodir), shell=True, executable="/bin/bash", stdout=PIPE, stderr=PIPE) waitpid(premote.pid, 0) remote = premot...
Returns true if the current repodir has been initialized in git *and* had a remote origin added *and* has a 'testing' branch.
375,767
def select(self, selections): atomsbonds if in selections: self.selection_state[] = selections[] self.on_atom_selection_changed() if in selections: self.selection_state[] = selections[] self.on_bond_selection_changed() if in selections...
Make a selection in this representation. BallAndStickRenderer support selections of atoms and bonds. To select the first atom and the first bond you can use the following code:: from chemlab.mviewer.state import Selection representation.s...
375,768
def _deserialize_class(cls, input_cls_name, trusted, strict): if not input_cls_name or input_cls_name == cls.__name__: return cls if trusted and input_cls_name in cls._REGISTRY: return cls._REGISTRY[input_cls_name] if strict: raise ValueError( ...
Returns the HasProperties class to use for deserialization
375,769
def get_version(dunder_file): path = abspath(expanduser(dirname(dunder_file))) try: return _get_version_from_version_file(path) or _get_version_from_git_tag(path) except CalledProcessError as e: log.warn(repr(e)) return None except Exception as e: log.exception(e) ...
Returns a version string for the current package, derived either from git or from a .version file. This function is expected to run in two contexts. In a development context, where .git/ exists, the version is pulled from git tags. Using the BuildPyCommand and SDistCommand classes for cmdclass in s...
375,770
def int_to_varbyte(self, value): length = int(log(max(value, 1), 0x80)) + 1 bytes = [value >> i * 7 & 0x7F for i in range(length)] bytes.reverse() for i in range(len(bytes) - 1): bytes[i] = bytes[i] | 0x80 return pack( % len(bytes...
Convert an integer into a variable length byte. How it works: the bytes are stored in big-endian (significant bit first), the highest bit of the byte (mask 0x80) is set when there are more bytes following. The remaining 7 bits (mask 0x7F) are used to store the value.
375,771
def load_edited_source(self, source, good_cb=None, bad_cb=None, filename=None): with LiveExecution.lock: self.good_cb = good_cb self.bad_cb = bad_cb try: compile(source + , filename or self.filename, "exec") self.edite...
Load changed code into the execution environment. Until the code is executed correctly, it will be in the 'tenuous' state.
375,772
def ctype_class(self): def struct_factory(field_types): class Struct(Structure): _fields_ = [(str(i), t.ctype_class) for i, t in enumerate(field_types)] return Struct if frozenset(self.field_types...
Summary Returns: TYPE: Description
375,773
def get_raw(config, backend_section, arthur): if arthur: task = TaskRawDataArthurCollection(config, backend_section=backend_section) else: task = TaskRawDataCollection(config, backend_section=backend_section) TaskProjects(config).execute() try: task.execute() loggi...
Execute the raw phase for a given backend section, optionally using Arthur :param config: a Mordred config object :param backend_section: the backend section where the raw phase is executed :param arthur: if true, it enables Arthur to collect the raw data
375,774
def scale_in(self, blocks=None, block_ids=[]): if block_ids: block_ids_to_kill = block_ids else: block_ids_to_kill = list(self.blocks.keys())[:blocks] for block_id in block_ids_to_kill: self._hold_block(block_id) to_kill =...
Scale in the number of active blocks by specified amount. The scale in method here is very rude. It doesn't give the workers the opportunity to finish current tasks or cleanup. This is tracked in issue #530 Parameters ---------- blocks : int Number of bloc...
375,775
def get_threads(session, query): response = make_get_request(session, , params_data=query) json_data = response.json() if response.status_code == 200: return json_data[] else: raise ThreadsNotFoundException( message=json_data[], error_code=json_data[], ...
Get one or more threads
375,776
def new_fills_report(self, start_date, end_date, account_id=None, product_id=, format=None, email=None): return self._new_report(start_date, , ...
`<https://docs.exchange.coinbase.com/#create-a-new-report>`_
375,777
def check_array(array, accept_sparse=None, dtype="numeric", order=None, copy=False, force_all_finite=True, ensure_2d=True, allow_nd=False, ensure_min_samples=1, ensure_min_features=1): if isinstance(accept_sparse, str): accept_sparse = [accept_sparse] dtype_num...
Input validation on an array, list, sparse matrix or similar. By default, the input is converted to an at least 2nd numpy array. If the dtype of the array is object, attempt converting to float, raising on failure. Parameters ---------- array : object Input object to check / convert. ...
375,778
def stdev(requestContext, seriesList, points, windowTolerance=0.1): for seriesIndex, series in enumerate(seriesList): stdevSeries = TimeSeries("stdev(%s,%d)" % (series.name, int(points)), series.start, series.end, series.step, []) stdevSeries.pathExpr...
Takes one metric or a wildcard seriesList followed by an integer N. Draw the Standard Deviation of all metrics passed for the past N datapoints. If the ratio of null points in the window is greater than windowTolerance, skip the calculation. The default for windowTolerance is 0.1 (up to 10% of points in...
375,779
def compileSass(sassPath): cssPath = os.path.splitext(sassPath)[0] + ".css" print("Compiling Sass") process = subprocess.Popen(["sass", sassPath, cssPath]) process.wait()
Compile a sass file (and dependencies) into a single css file.
375,780
def get_overlapping_ranges(self, collection_link, partition_key_ranges): cl = self._documentClient collection_id = base.GetResourceIdOrFullNameFromLink(collection_link) collection_routing_map = self._collection_routing_map_by_item.get(collection_id) if collecti...
Given a partition key range and a collection, returns the list of overlapping partition key ranges :param str collection_link: The name of the collection. :param list partition_key_range: List of partition key range. :return: List o...
375,781
def _friendlyAuthError(fn): @functools.wraps(fn) def wrapped(*args, **kwargs): try: return fn(*args, **kwargs) except requests.exceptions.HTTPError as e: if e.response.status_code == requests.codes.unauthorized: logger.error() elif e.resp...
Decorator to print a friendly you-are-not-authorised message. Use **outside** the _handleAuth decorator to only print the message after the user has been given a chance to login.
375,782
def extract_kwargs(names:Collection[str], kwargs:KWArgs): "Extract the keys in `names` from the `kwargs`." new_kwargs = {} for arg_name in names: if arg_name in kwargs: arg_val = kwargs.pop(arg_name) new_kwargs[arg_name] = arg_val return new_kwargs, kwargs
Extract the keys in `names` from the `kwargs`.
375,783
def unregister_counter_nonzero(network): if not hasattr(network, "__counter_nonzero_handles__"): raise ValueError("register_counter_nonzero was not called for this network") for h in network.__counter_nonzero_handles__: h.remove() delattr(network, "__counter_nonzero_handles__") for module in networ...
Unregister nonzero counter hooks :param network: The network previously registered via `register_nonzero_counter`
375,784
def cli(ctx, feature_id, organism="", sequence=""): return ctx.gi.annotations.get_feature_sequence(feature_id, organism=organism, sequence=sequence)
[CURRENTLY BROKEN] Get the sequence of a feature Output: A standard apollo feature dictionary ({"features": [{...}]})
375,785
def ParseOptions(self, options): helpers_manager.ArgumentHelperManager.ParseOptions( options, self, names=[]) self._ReadParserPresetsFromFile() argument_helper_names = [, , ] helpers_manager.ArgumentHelperManager.ParseOptions( options, self, names=argument_helper_names) ...
Parses the options. Args: options (argparse.Namespace): command line arguments. Raises: BadConfigOption: if the options are invalid.
375,786
def get_documents_in_database(self, with_id=True): documents = [] for coll in self.get_collection_names(): documents += self.get_documents_in_collection( coll, with_id=with_id ) return documents
Gets all documents in database :param with_id: True iff each document should also come with its id :return: List of documents in collection in database
375,787
def default_if_empty(self, default): if self.closed(): raise ValueError("Attempt to call default_if_empty() on a " "closed Queryable.") return self._create(self._generate_default_if_empty_result(default))
If the source sequence is empty return a single element sequence containing the supplied default value, otherwise return the source sequence unchanged. Note: This method uses deferred execution. Args: default: The element to be returned if the source sequence is empty. ...
375,788
def from_poppy_creature(cls, poppy, motors, passiv, tip, reversed_motors=[]): chain_elements = get_chain_from_joints(poppy.urdf_file, [m.name for m in motors]) activ = [False] + [m not in passiv for m in motors] + [True...
Creates an kinematic chain from motors of a Poppy Creature. :param poppy: PoppyCreature used :param list motors: list of all motors that composed the kinematic chain :param list passiv: list of motors which are passiv in the chain (they will not move) :param list tip: [x...
375,789
def get_field_from_args_or_session(config, args, field_name): rez = getattr(args, field_name, None) if (rez != None): return rez rez = config.get_session_field("default_%s"%field_name, exception_if_not_found=False) if (rez): return rez raise Exception("Fail to get default_%...
We try to get field_name from diffent sources: The order of priorioty is following: - command line argument (--<field_name>) - current session configuration (default_<filed_name>)
375,790
def validate(self, expectations_config=None, evaluation_parameters=None, catch_exceptions=True, result_format=None, only_return_failures=False): results = [] if expectations_config is None: expectations_config = self.get_expectations_config( discard_failed_expectat...
Generates a JSON-formatted report describing the outcome of all expectations. Use the default expectations_config=None to validate the expectations config associated with the DataAsset. Args: expectations_config (json or None): \ If None, uses the expectatio...
375,791
def parse_dash(string, width): "parse dash pattern specified with string" w = max(1, int(width + 0.5)) n = len(string) result = [] for i, c in enumerate(string): if c == " " and len(result): result[-1] += w + 1 elif c == "_": result.append(8*w) result.append(4*w) elif c == "-": result.append...
parse dash pattern specified with string
375,792
def put(self, item): if isinstance(item, self._item_class): self._put_one(item) elif isinstance(item, (list, tuple)): self._put_many(item) else: raise RuntimeError( % type(item))
store item in sqlite database
375,793
def get_run_as_identifiers_stack(self): session = self.get_session(False) try: return session.get_internal_attribute(self.run_as_identifiers_session_key) except AttributeError: return None
:returns: an IdentifierCollection
375,794
def colored(text, color=None, on_color=None, attrs=None): if __ISON and os.getenv() is None: fmt_str = if color is not None: text = fmt_str % (COLORS[color], text) if on_color is not None: text = fmt_str % (HIGHLIGHTS[on_color], text) if attrs is not ...
Colorize text. Available text colors: red, green, yellow, blue, magenta, cyan, white. Available text highlights: on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white. Available attributes: bold, dark, underline, blink, reverse, concealed. Example: color...
375,795
def DEBUG_ON_RESPONSE(self, statusCode, responseHeader, data): if self.DEBUG_FLAG: self._frameBuffer[self._frameCount][1:4] = [statusCode, responseHeader, data] responseHeader[self.DEBUG_HEADER_KEY] = self._frameCount
Update current frame with response Current frame index will be attached to responseHeader
375,796
def __to_plain_containers(self, container: Union[CommentedSeq, CommentedMap] ) -> Union[OrderedDict, list]: if isinstance(container, CommentedMap): new_container = OrderedDict() for key, value_obj in container.items()...
Converts any sequence or mapping to list or OrderedDict Stops at anything that isn't a sequence or a mapping. One day, we'll extract the comments and formatting and store \ them out-of-band. Args: mapping: The mapping of constructed subobjects to edit
375,797
def p_expr_div_expr(p): p[0] = Expr.makenode(Container(p[2], p.lineno(2)), p[1], p[3])
expr : expr BAND expr | expr BOR expr | expr BXOR expr | expr PLUS expr | expr MINUS expr | expr MUL expr | expr DIV expr | expr MOD expr | expr POW expr | expr LSHIFT expr | expr RSHIFT exp...
375,798
def channel_in_frame(channel, framefile): channel = str(channel) for name in iter_channel_names(framefile): if channel == name: return True return False
Determine whether a channel is stored in this framefile **Requires:** |LDAStools.frameCPP|_ Parameters ---------- channel : `str` name of channel to find framefile : `str` path of GWF file to test Returns ------- inframe : `bool` whether this channel is includ...
375,799
def run_cell_magic(self, magic_name, line, cell): fn = self.find_cell_magic(magic_name) if fn is None: lm = self.find_line_magic(magic_name) etpl = "Cell magic function `%%%%%s` not found%s." extra = if lm is None else ( ...
Execute the given cell magic. Parameters ---------- magic_name : str Name of the desired magic function, without '%' prefix. line : str The rest of the first input line as a single string. cell : str The body of the cell as a (possibly mul...