Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
364,800
async def _async_request_soup(url): from bs4 import BeautifulSoup import aiohttp _LOGGER.debug(, url) async with aiohttp.ClientSession() as session: resp = await session.get(url) text = await resp.text() return BeautifulSoup(text, )
Perform a GET web request and return a bs4 parser
364,801
def add_data_point(self, x, y, number_format=None): data_point = XyDataPoint(self, x, y, number_format) self.append(data_point) return data_point
Return an XyDataPoint object newly created with values *x* and *y*, and appended to this sequence.
364,802
def name(cls): name = cls.__name__.replace("_", "-").lower() name = name[4:] if name.startswith("cmd-") else name return name
Return the preferred name as which this command will be known.
364,803
def decode(self, packet): self.encoded = packet lenLen = 1 while packet[lenLen] & 0x80: lenLen += 1 packet_remaining = packet[lenLen+1:] self.msgId = decode16Int(packet_remaining[0:2]) self.topics = [] packet_remaining = packet_remaining[2:]...
Decode a UNSUBACK control packet.
364,804
def fromfile(fname): fig = SVGFigure() with open(fname) as fid: svg_file = etree.parse(fid) fig.root = svg_file.getroot() return fig
Open SVG figure from file. Parameters ---------- fname : str name of the SVG file Returns ------- SVGFigure newly created :py:class:`SVGFigure` initialised with the file content
364,805
def iter_used_addresses( adapter, seed, start, security_level=None, ): if security_level is None: security_level = AddressGenerator.DEFAULT_SECURITY_LEVEL ft_command = FindTransactionsCommand(adapter) for addy in AddressGenerator(seed, security_lev...
Scans the Tangle for used addresses. This is basically the opposite of invoking ``getNewAddresses`` with ``stop=None``.
364,806
def instantiate_labels(instructions): label_i = 1 result = [] label_mapping = dict() for instr in instructions: if isinstance(instr, Jump) and isinstance(instr.target, LabelPlaceholder): new_target, label_mapping, label_i = _get_label(instr.target, label_mapping, label_i) ...
Takes an iterable of instructions which may contain label placeholders and assigns them all defined values. :return: list of instructions with all label placeholders assigned to real labels.
364,807
def captures(self, uuid, withTitles=False): picker = lambda x: x.get(, []) return self._get((uuid,), picker, withTitles= if withTitles else )
Return the captures for a given uuid optional value withTitles=yes
364,808
def get_version(filename, version=): with open(filename) as infile: for line in infile: if line.startswith(): try: version = line.split("'")[1] except IndexError: pass break return version
Read version as text to avoid machinations at import time.
364,809
def delete(self, config_file=None): path_to_remove = config_file or _DEFAULT_PATH try: os.remove(path_to_remove) print(.format( path_to_remove)) except OSError as err: warnings.warn(.format( path_to_remove))
Deletes the credentials file specified in `config_file`. If no file is specified, it deletes the default user credential file. Args: config_file (str): Path to configuration file. Defaults to delete the user default location if `None`. .. Tip:: To see i...
364,810
def visit_starred(self, node, parent): context = self._get_context(node) newnode = nodes.Starred( ctx=context, lineno=node.lineno, col_offset=node.col_offset, parent=parent ) newnode.postinit(self.visit(node.value, newnode)) return newnode
visit a Starred node and return a new instance of it
364,811
def get_features_from_equation_file(filename): features = [] for line in open(filename): line = line.split()[0].strip() if line: features.append(line) return features
returns list of feature names read from equation file given by ``filename``. format: one feature per line; comments start with ``#`` Example:: #this is a comment basefeature #empty lines are ignored myfeature anotherfeature :param filename: :return:
364,812
def assign_indent_numbers(lst, inum, dic=collections.defaultdict(int)): for i in lst: dic[i] = inum return dic
Associate keywords with their respective indentation numbers
364,813
def plain(self, markup): if self.full_strip: markup = markup.replace("([^", "<b>\\1</b>", markup) markup = re.sub("([^ll strip the ending ]] later. if self.full_strip: markup = re.sub(r"\[\[[^\]]*?\|", "", markup) else: ...
Strips Wikipedia markup from given text. This creates a "plain" version of the markup, stripping images and references and the like. Does some commonsense maintenance as well, like collapsing multiple spaces. If you specified full_strip=False for WikipediaPage instance, ...
364,814
def get_std_xy_dataset_statistics(x_values, y_values, expect_negative_correlation = False, STDev_cutoff = 1.0): assert(len(x_values) == len(y_values)) csv_lines = [] + [.join(map(str, [c + 1, x_values[c], y_values[c]])) for c in xrange(len(x_values))] data = parse_csv(csv_lines, expect_negative_correla...
Calls parse_csv and returns the analysis in a format similar to get_xy_dataset_statistics in klab.stats.misc.
364,815
def __parse_entry(entry_line): if entry_line.startswith("!"): entry_line = sub(r"!\w*?_", , entry_line) else: entry_line = entry_line.strip()[1:] try: entry_type, entry_name = [i.strip() for i in entry_line.split("=", 1)] except ValueError: entry_type = [i.strip() fo...
Parse the SOFT file entry name line that starts with '^', '!' or '#'. Args: entry_line (:obj:`str`): Line from SOFT to be parsed. Returns: :obj:`2-tuple`: Type of entry, value of entry.
364,816
def create_application(self, description=None): out("Creating application " + str(self.app_name)) self.ebs.create_application(self.app_name, description=description)
Creats an application and sets the helpers current app_name to the created application
364,817
def getJSMinimumVolume(self, **kw): default = self.Schema()[].get(self) try: mgdefault = default.split(, 1) mgdefault = mg(float(mgdefault[0]), mgdefault[1]) except: mgdefault = mg(0, ) try: return str(mgdefault.ounit()) ex...
Try convert the MinimumVolume to 'ml' or 'g' so that JS has an easier time working with it. If conversion fails, return raw value.
364,818
def whitelist(ctx, whitelist_account, account): account = Account(account, blockchain_instance=ctx.blockchain) print_tx(account.whitelist(whitelist_account))
Add an account to a whitelist
364,819
def resume_job(job_id): try: current_app.apscheduler.resume_job(job_id) job = current_app.apscheduler.get_job(job_id) return jsonify(job) except JobLookupError: return jsonify(dict(error_message= % job_id), status=404) except Exception as e: return jsonify(dict(...
Resumes a job.
364,820
def watch(self, limit=None, timeout=None): start_time = time.time() count = 0 while not timeout or time.time() - start_time < timeout: new = self.read() if new != self.temp: count += 1 self.callback(new) if count ==...
Block method to watch the clipboard changing.
364,821
def trySwitchStatement(self, block): if not re.match(r, block.text()): return None for block in self.iterateBlocksBackFrom(block.previous()): text = block.text() if re.match(r"^\s*(default\s*|case\b.*):", text): dbg("trySwitchStatement: succe...
Check for default and case keywords and assume we are in a switch statement. Try to find a previous default, case or switch and return its indentation or None if not found.
364,822
def dumpJSON(self): numexp = self.number.get() expTime, _, _, _, _ = self.timing() if numexp == 0: numexp = -1 data = dict( numexp=self.number.value(), app=self.app.value(), led_flsh=self.led(), dummy_out=self.dummy(),...
Encodes current parameters to JSON compatible dictionary
364,823
def load_module_from_file_object(fp, filename=, code_objects=None, fast_load=False, get_code=True): if code_objects is None: code_objects = {} timestamp = 0 try: magic = fp.read(4) magic_int = magics.magic2int(magic) ...
load a module from a file object without importing it. See :func:load_module for a list of return values.
364,824
def age(self): if self.rounds == 1: self.do_run = False elif self.rounds > 1: self.rounds -= 1
Get closer to your EOL
364,825
def proton_hydroxide_free_energy(temperature, pressure, pH): H2 = GasMolecule() H2O = GasMolecule() G_H2 = H2.get_free_energy(temperature = temperature, pressure = pressure) G_H2O = H2O.get_free_energy(temperature = temperature) G_H = (0.5*G_H2) - ((R*temperature)/(z*F))*ln10*pH G_OH = G_H2...
Returns the Gibbs free energy of proton in bulk solution. Parameters ---------- pH : pH of bulk solution temperature : numeric temperature in K pressure : numeric pressure in mbar Returns ------- G_H, G_OH : Gibbs free energy of proton and hydroxide.
364,826
def get_state_data(cls, entity): attrs = get_domain_class_attribute_iterator(type(entity)) return dict([(attr, get_nested_attribute(entity, attr.entity_attr)) for attr in attrs if not attr.entity_attr is None])
Returns the state data for the given entity. This also works for unmanaged entities.
364,827
def parse(self, text, **kwargs): if text is None: logger.error(self._ERROR_EMPTY_STR) raise MeCabError(self._ERROR_EMPTY_STR) elif not isinstance(text, str): logger.error(self._ERROR_NOTSTR) raise MeCabError(self._ERROR_NOTSTR) elif in se...
Parse the given text and return result from MeCab. :param text: the text to parse. :type text: str :param as_nodes: return generator of MeCabNodes if True; or string if False. :type as_nodes: bool, defaults to False :param boundary_constraints: regular expression for...
364,828
def stat( self, *args ): self.pipe.poll() if not self.pipe.returncode is None: if not self.expiration is None: self.ioloop.remove_timeout(self.expiration) for fd, dest in self.streams: self.ioloop.remove_handler(fd) ...
Check process completion and consume pending I/O data
364,829
def first(self, callback=None, default=None): if callback is not None: for val in self.items: if callback(val): return val return value(default) if len(self.items) > 0: return self.items[0] else: retur...
Get the first item of the collection. :param default: The default value :type default: mixed
364,830
def unzip(zipped_file, output_directory=None, prefix="harvestingkit_unzip_", suffix=""): if not output_directory: try: output_directory = mkdtemp(suffix=suffix, prefix=prefix) except Exception, e: try: ...
Uncompress a zipped file from given filepath to an (optional) location. If no location is given, a temporary folder will be generated inside CFG_TMPDIR, prefixed with "apsharvest_unzip_".
364,831
def pair(self): sock = self.__sock(zmq.PAIR) return self.__send_function(sock), self.__recv_generator(sock)
Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were sent by a pair socket. Note that the iterable returns as many parts as sent by a pair. Also, the sender function has a ``print`` like signature, ...
364,832
def _adjust_router_list_for_global_router(self, routers): for r in routers: if r[ROUTER_ROLE_ATTR] == c_constants.ROUTER_ROLE_GLOBAL: LOG.debug("Global router:%s found. Moved to the end of list " "for processing", r[]) route...
Pushes 'Global' routers to the end of the router list, so that deleting default route occurs before deletion of external nw subintf
364,833
def _run_eos_cmds(self, commands, switch): LOG.info(_LI(), commands) try: ret = switch.execute(commands) LOG.info(_LI(), ret) return ret except Exception: msg = (_( ) % {: ...
Execute/sends a CAPI (Command API) command to EOS. This method is useful for running show commands that require no prefix or postfix commands. :param commands : List of commands to be executed on EOS. :param switch: Endpoint on the Arista switch to be configured
364,834
def save(self, **kwargs): if self.id: for f_photo in self.formatedphoto_set.all(): f_photo.delete() super(Format, self).save(**kwargs)
Overrides models.Model.save. - Delete formatted photos if format save and not now created (because of possible changes)
364,835
def _ParseFSMVariables(self, template): self.values = [] for line in template: self._line_num += 1 line = line.rstrip() if not line: return if self.comment_regex.match(line): continue if line.startswith(): try: value = TextF...
Extracts Variables from start of template file. Values are expected as a contiguous block at the head of the file. These will be line separated from the State definitions that follow. Args: template: Valid template file, with Value definitions at the top. Raises: TextFSMTemplateError: If ...
364,836
def instruction_RTI(self, opcode): cc = self.pull_byte(self.system_stack_pointer) self.set_cc(cc) if self.E: self.accu_a.set( self.pull_byte(self.system_stack_pointer) ) self.accu_b.set( self.pull_byte(self.system_sta...
The saved machine state is recovered from the hardware stack and control is returned to the interrupted program. If the recovered E (entire) bit is clear, it indicates that only a subset of the machine state was saved (return address and condition codes) and only that subset is recovered. ...
364,837
def make_python_identifier(string, namespace=None, reserved_words=None, convert=, handle=): if namespace is None: namespace = dict() if reserved_words is None: reserved_words = list() if string in namespace: return namespace[string], namespace ...
Takes an arbitrary string and creates a valid Python identifier. If the input string is in the namespace, return its value. If the python identifier created is already in the namespace, but the input string is not (ie, two similar strings resolve to the same python identifier) or if the identifie...
364,838
def create_repository(self, repository_form=None): if repository_form is None: raise NullArgument() if not isinstance(repository_form, abc_repository_objects.RepositoryForm): raise InvalidArgument() if repository_form.is_for_update(): raise InvalidArg...
Creates a new ``Repository``. :param repository_form: the form for this ``Repository`` :type repository_form: ``osid.repository.RepositoryForm`` :return: the new ``Repository`` :rtype: ``osid.repository.Repository`` :raise: ``IllegalState`` -- ``repository_form`` already used in...
364,839
def print_file(self, f=sys.stdout, file_format="cif", tw=0): if file_format == "cif": for key in self.keys(): if key == u"data": print(u"{}_{}".format(key, self[key]), file=f) elif key.startswith(u"comment"): print(u"{}...
Print :class:`~nmrstarlib.nmrstarlib.CIFFile` into a file or stdout. :param io.StringIO f: writable file-like stream. :param str file_format: Format to use: `cif` or `json`. :param int tw: Tab width. :return: None :rtype: :py:obj:`None`
364,840
def intersperse(e, iterable, n=1): if n == 0: raise ValueError() elif n == 1: return islice(interleave(repeat(e), iterable), 1, None) else: filler = repeat([e]) chunks = chunked(iterable, n) return flatten(islice(inter...
Intersperse filler element *e* among the items in *iterable*, leaving *n* items between each filler element. >>> list(intersperse('!', [1, 2, 3, 4, 5])) [1, '!', 2, '!', 3, '!', 4, '!', 5] >>> list(intersperse(None, [1, 2, 3, 4, 5], n=2)) [1, 2, None, 3, 4, None, 5]
364,841
def can_use_cached_output(self, contentitem): plugin = contentitem.plugin return appsettings.FLUENT_CONTENTS_CACHE_OUTPUT and plugin.cache_output and contentitem.pk
Tell whether the code should try reading cached output
364,842
def unsafe(self): (scheme, netloc, path, params, query, frag) = urlparse(self.src_uri) if (scheme != ): return(False) s = os.path.normpath(self.src_uri) d = os.path.normpath(self.dst_path) lcp = os.path.commonprefix([s, d]) return(s == lcp or d == lcp...
True if the mapping is unsafe for an update. Applies only to local source. Returns True if the paths for source and destination are the same, or if one is a component of the other path.
364,843
def authenticate(self, request): for backend in self.authentication: client = backend().authenticate(request) if client is not None: return client return None
Authenticate a client against all the backends configured in :attr:`authentication`.
364,844
def augment_initial_layout(self, base_response, initial_arguments=None): if self.use_dash_layout() and not initial_arguments and False: return base_response.data, base_response.mimetype baseDataInBytes = base_response.data baseData = json.loads(baseDataInBytes.deco...
Add application state to initial values
364,845
def parse_non_selinux(parts): links, owner, group, last = parts result = { "links": int(links), "owner": owner, "group": group, } if "," in last[:4]: major, minor, rest = last.split(None, 2) result["major"] = int(major.rstrip(",")) res...
Parse part of an ls output line that isn't selinux. Args: parts (list): A four element list of strings representing the initial parts of an ls line after the permission bits. The parts are link count, owner, group, and everything else. Returns: A dict containing links, ...
364,846
def _vis_calibrate(self, data): solar_irradiance = self[] esd = self["earth_sun_distance_anomaly_in_AU"].astype(float) factor = np.pi * esd * esd / solar_irradiance res = data * factor res.attrs = data.attrs res.attrs[] = res.attrs[] = return ...
Calibrate visible channels to reflectance.
364,847
def WriteEventBody(self, event): for field_name in self._fields: if field_name == : output_value = self._FormatDateTime(event) else: output_value = self._dynamic_fields_helper.GetFormattedField( event, field_name) output_value = self._RemoveIllegalXMLCharacters(ou...
Writes the body of an event object to the spreadsheet. Args: event (EventObject): event.
364,848
def _handle_watch_message(self, message): if self.log_protocol_level is not None: logger.log(self.log_protocol_level, "<- %s", hexlify(message).decode()) message = self.pending_bytes + message while len(message) >= 4: try: packet, length = Pebble...
Processes a binary message received from the watch and broadcasts the relevant events. :param message: A raw message from the watch, without any transport framing. :type message: bytes
364,849
def check_for_maintenance(self): numrevs = self.conn.get_one("SELECT count(revnum) FROM csetLog")[0] if numrevs >= SIGNAL_MAINTENACE_CSETS: return True return False
Returns True if the maintenance worker should be run now, and False otherwise. :return:
364,850
def df_quantile(df, nb=100): quantiles = np.linspace(0, 1., nb) res = pd.DataFrame() for q in quantiles: res = res.append(df.quantile(q), ignore_index=True) return res
Returns the nb quantiles for datas in a dataframe
364,851
def _get_base_class_names(frame): co, lasti = frame.f_code, frame.f_lasti code = co.co_code extends = [] for (op, oparg) in op_stream(code, lasti): if op in dis.hasconst: if type(co.co_consts[oparg]) == str: extends = [] elif op in dis.hasname: ...
Get baseclass names from the code object
364,852
def palettize(self, colormap): if self.mode not in ("L", "LA"): raise ValueError("Image should be grayscale to colorize") l_data = self.data.sel(bands=[]) def _palettize(data): return colormap.palettize(data)[0] new_data = l_data.data.map...
Palettize the current image using `colormap`. .. note:: Works only on "L" or "LA" images.
364,853
def off_policy_train_batch(self, batch_info: BatchInfo): self.model.train() rollout = self.env_roller.sample(batch_info, self.model, self.settings.number_of_steps).to_device(self.device) batch_result = self.algo.optimizer_step( batch_info=batch_info, device=sel...
Perform an 'off-policy' training step of sampling the replay buffer and gradient descent
364,854
def POST(self, id): id = int(id) model.del_todo(id) raise web.seeother()
Delete based on ID
364,855
def main(): args = docopt(__doc__, version=__version__, options_first=True) s = Schema({ six.text_type: bool, : Or(None, str), : list, : Or(str, lambda _: ), }) try: args = s.validate(args) except SchemaError as exc: print(.format(str(exc), ...
This is the CLI driver for ia-wrapper.
364,856
def get_default_config(self): config = super(ElasticSearchCollector, self).get_default_config() config.update({ : , : 9200, : , : , : [], : , : , ...
Returns the default collector settings
364,857
def unmarshal( compoundSignature, data, offset = 0, lendian = True ): values = list() start_offset = offset for ct in genCompleteTypes( compoundSignature ): tcode = ct[0] offset += len(pad[tcode]( offset )) nbytes, value = unmarshallers[ tcode ]( ct, da...
Unmarshals DBus encoded data. @type compoundSignature: C{string} @param compoundSignature: DBus signature specifying the encoded value types @type data: C{string} @param data: Binary data @type offset: C{int} @param offset: Offset within data at which data for compoundSignature ...
364,858
def aq_esc_telemetry_encode(self, time_boot_ms, seq, num_motors, num_in_seq, escid, status_age, data_version, data0, data1): return MAVLink_aq_esc_telemetry_message(time_boot_ms, seq, num_motors, num_in_seq, escid, status_age, data_version, data0, data1)
Sends ESC32 telemetry data for up to 4 motors. Multiple messages may be sent in sequence when system has > 4 motors. Data is described as follows: // unsigned int state : 3; // unsigned int vin : 12; // x 100 // unsigned int amps...
364,859
def _parse_msg(client, command, actor, args): recipient, _, message = args.partition() chantypes = client.server.features.get("CHANTYPES", " if recipient[0] in chantypes: recipient = client.server.get_channel(recipient) or recipient.lower() else: recipient = User(recipient) clie...
Parse a PRIVMSG or NOTICE and dispatch the corresponding event.
364,860
def subscribe(self, queue=None, *levels): args = { : queue, : list(levels), } self._subscribe_chk.check(args) return self._client.json(, args)
Subscribe to the aggregated log stream. On subscribe a ledis queue will be fed with all running processes logs. Always use the returned queue name from this method, even if u specified the queue name to use Note: it is legal to subscribe to the same queue, but would be a bad logic if two processes are ...
364,861
def _add_observation(self, x_to_add, y_to_add): self._add_observation_to_means(x_to_add, y_to_add) self._add_observation_to_variances(x_to_add, y_to_add) self.window_size += 1
Add observation to window, updating means/variance efficiently.
364,862
def lyricsmode(song): translate = { URLESCAPE: , : } artist = song.artist.lower() artist = normalize(artist, translate) title = song.title.lower() title = normalize(title, translate) artist = re.sub(r, , artist) title = re.sub(r, , title) if artist[0:4].lower(...
Returns the lyrics found in lyricsmode.com for the specified mp3 file or an empty string if not found.
364,863
def SendKeys(keys, pause=0.05, with_spaces=False, with_tabs=False, with_newlines=False, turn_off_numlock=True): "Parse the keys and type them" keys = parse_keys(keys, with_spaces, with_tabs, with_newlines) for k in keys: k.Run() ...
Parse the keys and type them
364,864
def _detach_dim_scale(self, name): for var in self.variables.values(): for n, dim in enumerate(var.dimensions): if dim == name: var._h5ds.dims[n].detach_scale(self._all_h5groups[dim]) for subgroup in self.groups.values(): if dim not i...
Detach the dimension scale corresponding to a dimension name.
364,865
def options(self): if self._option_view is None: self._option_view = Option.View(self) return self._option_view
Returns the options specified as argument to this command.
364,866
def all_points_mutual_reachability(X, labels, cluster_id, metric=, d=None, **kwd_args): if metric == : if d is None: raise ValueError( ) distance_matrix = X[labels == cluster_id, :][:, labels == cluster_id] else: ...
Compute the all-points-mutual-reachability distances for all the points of a cluster. If metric is 'precomputed' then assume X is a distance matrix for the full dataset. Note that in this case you must pass in 'd' the dimension of the dataset. Parameters ---------- X : array (n_samples, n_...
364,867
def get_node(self, index): index = self.mapToSource(index) if not index.isValid(): return self.sourceModel().root_node return index.internalPointer() or self.sourceModel().root_node
Returns the Node at given index. :param index: Index. :type index: QModelIndex :return: Node. :rtype: AbstractCompositeNode
364,868
def __calculate_radius(self, number_neighbors, radius): if (number_neighbors >= len(self._osc_loc)): return radius * self.__increase_persent + radius; return average_neighbor_distance(self._osc_loc, number_neighbors);
! @brief Calculate new connectivity radius. @param[in] number_neighbors (uint): Average amount of neighbors that should be connected by new radius. @param[in] radius (double): Current connectivity radius. @return New connectivity radius.
364,869
def prepare_boxlist(self, boxes, scores, image_shape): boxes = boxes.reshape(-1, 4) scores = scores.reshape(-1) boxlist = BoxList(boxes, image_shape, mode="xyxy") boxlist.add_field("scores", scores) return boxlist
Returns BoxList from `boxes` and adds probability scores information as an extra field `boxes` has shape (#detections, 4 * #classes), where each row represents a list of predicted bounding boxes for each of the object classes in the dataset (including the background class). The detection...
364,870
async def load_cache_for_proof(self, archive: bool = False) -> int: LOGGER.debug(, archive) rv = int(time()) box_ids = json.loads(await self.get_box_ids_held()) for s_id in box_ids[]: with SCHEMA_CACHE.lock: await self.get_schema(s_id) for c...
Load schema, cred def, revocation caches; optionally archive enough to go offline and be able to generate proof on all credentials in wallet. Return timestamp (epoch seconds) of cache load event, also used as subdirectory for cache archives. :param archive: True to archive now or False...
364,871
def uri_query(self): value = [] for option in self.options: if option.number == defines.OptionRegistry.URI_QUERY.number: value.append(str(option.value)) return "&".join(value)
Get the Uri-Query of a request. :return: the Uri-Query :rtype : String :return: the Uri-Query string
364,872
def _post(self, path, **kwargs): clean_kwargs = clean_dict(kwargs) data = bytes(json.dumps(clean_kwargs), encoding=) self._headers[] = api = self._api( % path) req = request.Request( api, headers=self._headers, data=data, method=) ...
return a dict.
364,873
def __get_stpd_filename(self): if self.use_caching: sep = "|" hasher = hashlib.md5() hashed_str = "cache version 6" + sep + \ .join(self.load_profile.schedule) + sep + str(self.loop_limit) hashed_str += sep + str(self.ammo_limit) + sep + ....
Choose the name for stepped data file
364,874
def prepare_project(project, project_dir, binaries, ips, urls): lists = get_lists.GetLists() file_audit_list, file_audit_project_list = lists.file_audit_list(project) flag_list, ignore_list = lists.file_content_list(project) file_ignore = lists.file_ignore() ignore_dire...
Generates blacklists / whitelists
364,875
def generate_acyclic_graph(self): self.n = 3 * len(self.words) max_tries = len(self.words) ** 2 for trial in range(max_tries): try: self.generate_or_fail() except forest.InvariantError: ...
Generates an acyclic graph for the given words. Adds the graph, and a list of edge-word associations to the object.
364,876
def await_reservations(self, sc, status={}, timeout=600): timespent = 0 while not self.reservations.done(): logging.info("waiting for {0} reservations".format(self.reservations.remaining())) if in status: sc.cancelAllJobs() sc.stop() sys.exit(1) time.sleep(...
Block until all reservations are received.
364,877
def priority_sort(list_, priority): r priority_ = setintersect_ordered(priority, list_) reordered_list = unique_ordered(priority_ + list_) return reordered_list
r""" Args: list_ (list): priority (list): desired order of items Returns: list: reordered_list CommandLine: python -m utool.util_list --test-priority_argsort Example: >>> # ENABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> list_ = [2,...
364,878
def get_or_create(cls, subscriber, livemode=djstripe_settings.STRIPE_LIVE_MODE): try: return Customer.objects.get(subscriber=subscriber, livemode=livemode), False except Customer.DoesNotExist: action = "create:{}".format(subscriber.pk) idempotency_key = djstripe_settings.get_idempotency_key("customer",...
Get or create a dj-stripe customer. :param subscriber: The subscriber model instance for which to get or create a customer. :type subscriber: User :param livemode: Whether to get the subscriber in live or test mode. :type livemode: bool
364,879
def _outlierDetection_threaded(inputs): [samples_idx, samples_x, samples_y_aggregation] = inputs sys.stderr.write("[%s] DEBUG: Evaluating %dth of %d samples\n"\ % (os.path.basename(__file__), samples_idx + 1, len(samples_x))) outlier = None diagnostic_regressor_gp = gp...
Detect the outlier
364,880
def deploy_sandbox_shared_setup(log, verbose=True, app=None, exp_config=None): if verbose: out = None else: out = open(os.devnull, "w") config = get_config() if not config.ready: config.load() heroku.sanity_check(config) (id, tmp) = setup_experiment(log, debug=Fals...
Set up Git, push to Heroku, and launch the app.
364,881
def mime_type(instance): mime_pattern = re.compile(r ) for key, obj in instance[].items(): if ( in obj and obj[] == and in obj): if enums.media_types(): if obj[] not in enums.media_types(): yield JSONError("The propert...
Ensure the 'mime_type' property of file objects comes from the Template column in the IANA media type registry.
364,882
def _norm(self, x): return float(np.sqrt(self.inner(x, x).real))
Return the norm of ``x``. This method is intended to be private. Public callers should resort to `norm` which is type-checked.
364,883
def create_required_directories(self): required = (self.CACHE_DIR, self.LOG_DIR, self.OUTPUT_DIR, self.ENGINEER.JINJA_CACHE_DIR,) for folder in required: ensure_exists(folder, assume_dirs=True)
Creates any directories required for Engineer to function if they don't already exist.
364,884
def delete(self, params, args, data): ctx = self._create_context(params, args, data) row_id = ctx.get_row_id() if row_id is not None: return self._delete_one(row_id, ctx) else: return self._delete_collection(ctx)
DELETE /resource/model_cls/[params]?[args] delete resource/s
364,885
def searchPhotos(self, title, **kwargs): return self.search(libtype=, title=title, **kwargs)
Search for a photo. See :func:`~plexapi.library.LibrarySection.search()` for usage.
364,886
def destroy(self): if self.session_type == : self.logout() elif self.session_type == : self.logout()
Finish up a session.
364,887
def get_variables(scope=None, suffix=None): candidates = tf.get_collection(MODEL_VARIABLES, scope)[:] if suffix is not None: candidates = [var for var in candidates if var.op.name.endswith(suffix)] return candidates
Gets the list of variables, filtered by scope and/or suffix. Args: scope: an optional scope for filtering the variables to return. suffix: an optional suffix for filtering the variables to return. Returns: a copied list of variables with scope and suffix.
364,888
def get_kafka_ssl_context(): with NamedTemporaryFile(suffix=) as cert_file, \ NamedTemporaryFile(suffix=) as key_file, \ NamedTemporaryFile(suffix=) as trust_file: cert_file.write(os.environ[].encode()) ...
Returns an SSL context based on the certificate information in the Kafka config vars.
364,889
def url(self): if self.id: url = "%s%s%s" % (self._url, self.id_url, self.id) else: url = None return url
Return the path subcomponent of the url to this object. For example: "/computers/id/451"
364,890
def grab_focus(self): scene = self.get_scene() if scene and scene._focus_sprite != self: scene._focus_sprite = self
grab window's focus. Keyboard and scroll events will be forwarded to the sprite who has the focus. Check the 'focused' property of sprite in the on-render event to decide how to render it (say, add an outline when focused=true)
364,891
def write_template(data, results_dir, parent): print("Generating html report...") partial = time.time() j_env = Environment(loader=FileSystemLoader(os.path.join(results_dir, parent, ))) template = j_env.get_template() report_writer = ReportWriter(results_dir, parent) report_writer.write_re...
Write the html template :param dict data: the dict containing all data for output :param str results_dir: the ouput directory for results :param str parent: the parent directory
364,892
def expected(self, dynamizer): if self._expect_kwargs: return encode_query_kwargs(dynamizer, self._expect_kwargs) if self._expected is not NO_ARG: ret = {} if is_null(self._expected): ret[] = False else: ret[] = dyn...
Get the expected values for the update
364,893
def summary(args): from jcvi.utils.natsort import natsort_key p = OptionParser(summary.__doc__) p.add_option("--suffix", default="Mb", help="make the base pair counts human readable [default: %default]") p.add_option("--ids", help="write the ids that have >= 50% Ns Total %_...
%prog summary *.fasta Report real bases and N's in fastafiles in a tabular report
364,894
def _process_params(self, params): processed_params = {} for key, value in params.items(): processed_params[key] = self._process_param_value(value) return processed_params
Converts Unicode/lists/booleans inside HTTP parameters
364,895
def percentiles(self, percentiles): try: scores = [0.0]*len(percentiles) if self.count > 0: values = self.samples() values.sort() for i in range(len(percentiles)): p = percentiles[i] pos = p * (len(values) + 1) if pos < 1: scores[i...
Given a list of percentiles (floats between 0 and 1), return a list of the values at those percentiles, interpolating if necessary.
364,896
def pluck(self, key): return self._wrap([x.get(key) for x in self.obj])
Convenience version of a common use case of `map`: fetching a property.
364,897
def console_script(): opensubmit-exec if len(sys.argv) == 1: print("opensubmit-exec [configcreate <server_url>|configtest|run|test <dir>|unlock|help] [-c config_file]") return 0 if "help" in sys.argv[1]: print("configcreate <server_url>: Create initial config file for the OpenSubmi...
The main entry point for the production administration script 'opensubmit-exec', installed by setuptools.
364,898
def registerTzinfo(obj, tzinfo): tzid = obj.pickTzid(tzinfo) if tzid and not getTzid(tzid, False): registerTzid(tzid, tzinfo) return tzid
Register tzinfo if it's not already registered, return its tzid.
364,899
def diff(s1, s2): return levenshtein(s1, s2) / max(len(s1), len(s2))
Return a normalised Levenshtein distance between two strings. Distance is normalised by dividing the Levenshtein distance of the two strings by the max(len(s1), len(s2)). Examples: >>> text.diff("foo", "foo") 0 >>> text.diff("foo", "fooo") 1 >>> text.diff("foo", ...