Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
20,300
def _query_mysql(self): mysql = MySqlHook(mysql_conn_id=self.mysql_conn_id) conn = mysql.get_conn() cursor = conn.cursor() cursor.execute(self.sql) return cursor
Queries mysql and returns a cursor to the results.
20,301
def path(string): if not os.path.exists(string): msg = "Path %s not found!" % string raise ArgumentTypeError(msg) return string
Define the 'path' data type that can be used by apps.
20,302
def add_arc(self, src, dst, char): if src not in self.automaton.states(): self.add_state() arc = fst.Arc(self.isyms[char], self.osyms[char], fst.Weight.One(self.automaton.weight_type()), dst) self.automaton.add_arc(src, arc)
Adds a new Arc Args: src (int): The source state identifier dst (int): The destination state identifier char (str): The character for the transition Returns: None
20,303
def itertrain(self, train, valid=None, **kwargs): from . import feedforward original_layer_names = set(l.name for l in self.network.layers[:-1])
Train a model using a training and validation set. This method yields a series of monitor values to the caller. After every iteration, a pair of monitor dictionaries is generated: one evaluated on the training dataset, and another evaluated on the validation dataset. The validation moni...
20,304
def _resolve_dut_count(self): self._dut_count = len(self._dut_requirements) self._resolve_process_count() self._resolve_hardware_count() if self._dut_count != self._hardware_count + self._process_count: raise ValueError("Missing or invalid type fields in dut configur...
Calculates total amount of resources required and their types. :return: Nothing, modifies _dut_count, _hardware_count and _process_count :raises: ValueError if total count does not match counts of types separately.
20,305
def assign_reads_to_otus(original_fasta, filtered_fasta, output_filepath=None, log_name="assign_reads_to_otus.log", perc_id_blast=0.97, global_alignment=True, HALT_EXEC=F...
Uses original fasta file, blasts to assign reads to filtered fasta original_fasta = filepath to original query fasta filtered_fasta = filepath to enumerated, filtered fasta output_filepath = output path to clusters (uc) file log_name = string specifying output log name perc_id_blast = percent ID fo...
20,306
def reverse(cls, value, prop, visitor): return ( None if isinstance(value, (AttributeError, KeyError)) else value )
Like :py:meth:`normalize.visitor.VisitorPattern.apply` but called for ``cast`` operations. The default implementation passes through but squashes exceptions, just like apply.
20,307
def create(cls, currency, all_co_owner, description=None, daily_limit=None, overdraft_limit=None, alias=None, avatar_uuid=None, status=None, sub_status=None, reason=None, reason_description=None, notification_filters=None, setting=None, custom_headers=None): ...
:type user_id: int :param currency: The currency of the MonetaryAccountJoint as an ISO 4217 formatted currency code. :type currency: str :param all_co_owner: The users the account will be joint with. :type all_co_owner: list[object_.CoOwner] :param description: The descri...
20,308
def set_session_cache_mode(self, mode): if not isinstance(mode, integer_types): raise TypeError("mode must be an integer") return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Set the behavior of the session cache used by all connections using this Context. The previously set mode is returned. See :const:`SESS_CACHE_*` for details about particular modes. :param mode: One or more of the SESS_CACHE_* flags (combine using bitwise or) :returns: The ...
20,309
def create_manually(cls, validation_function_name, var_name, var_value, validation_outcome=None, help_msg=None, append_details=True, ...
Creates an instance without using a Validator. This method is not the primary way that errors are created - they should rather created by the validation entry points. However it can be handy in rare edge cases. :param validation_function_name: :param var_name: :param var_value:...
20,310
def start(self): if self._limit < 0: return succeed(None) elif self._limit == 0: return Deferred() d = self._make_waiter() self._check_concurrent() return d
Start a concurrent operation. If we are below the limit, we increment the concurrency count and fire the deferred we return. If not, we add the deferred to the waiters list and return it unfired.
20,311
def bytes2uuid(b): if b.strip(chr(0)) == : return None s = b.encode() return "%s-%s-%s-%s-%s" % (s[0:8], s[8:12], s[12:16], s[16:20], s[20:])
Return standard human-friendly UUID.
20,312
def _get_input(self, length): self._buffer_lock.acquire() try: if length == -1: actualLength = len(self._buffer) else: actualLength = min(length, len(self._buffer)) if actualLength: data = self._buffer[:actualLe...
! @brief Extract requested amount of data from the read buffer.
20,313
def get_asset_search_session(self, proxy): if not self.supports_asset_search(): raise Unimplemented() try: from . import sessions except ImportError: raise proxy = self._convert_proxy(proxy) try: session = sessions.AssetS...
Gets an asset search session. arg proxy (osid.proxy.Proxy): a proxy return: (osid.repository.AssetSearchSession) - an AssetSearchSession raise: OperationFailed - unable to complete request raise: Unimplemented - supports_asset_search() is false compliance: ...
20,314
def zip_response(request, filename, files): tmp_file = NamedTemporaryFile() try: with ZipFile(tmp_file, ) as zip_file: for zip_path, actual_path in files: zip_file.write(actual_path, zip_path) tmp_file.flush() response = FileResponse(tmp_file.name, requ...
Return a Response object that is a zipfile with name filename. :param request: The request object. :param filename: The filename the browser should save the file as. :param files: A list of mappings between filenames (path/.../file) to file objects.
20,315
def max_layout_dimensions(dimensions): min_ = max([d.min for d in dimensions if d.min is not None]) max_ = max([d.max for d in dimensions if d.max is not None]) preferred = max([d.preferred for d in dimensions]) return LayoutDimension(min=min_, max=max_, preferred=preferred)
Take the maximum of a list of :class:`.LayoutDimension` instances.
20,316
def update_model_params(self, **params): r for key, value in params.items(): if not hasattr(self, key): setattr(self, key, value) elif getattr(self, key) is None: setattr(self, key, value) elif value is not None: set...
r"""Update given model parameter if they are set to specific values
20,317
def is_tagged(required_tags, has_tags): if not required_tags and not has_tags: return True elif not required_tags: return False found_tags = [] for tag in required_tags: if tag in has_tags: found_tags.append(tag) return len(found_tags) == len(required_tags)
Checks if tags match
20,318
def from_json(value, **kwargs): if not value.startswith(PNG_PREAMBLE): raise ValueError() infile = BytesIO() rep = base64.b64decode(value[len(PNG_PREAMBLE):].encode()) infile.write(rep) infile.seek(0) return infile
Convert a PNG Image from base64-encoded JSON
20,319
def diamond_functions(xx, yy, y_x0, x_y0): npxx = np.array(xx) npyy = np.array(yy) if np.any(npxx == npyy): raise RuntimeError() if np.all(npxx < npyy) or np.all(npxx > npyy): if npxx[0] < npyy[0]: p1 = npxx p2 = npyy else: p1 = npyy ...
Method that creates two upper and lower functions based on points xx and yy as well as intercepts defined by y_x0 and x_y0. The resulting functions form kind of a distorted diamond-like structure aligned from point xx to point yy. Schematically : xx is symbolized by x, yy is symbolized by y, y_x0 ...
20,320
def idPlayerResults(cfg, rawResult): result = {} knownPlayers = [] dictResult = {plyrRes.player_id : plyrRes.result for plyrRes in rawResult} for p in cfg.players: if p.playerID and p.playerID in dictResult: knownPlayers.append(p) result[p.name] = dictResult[p.playe...
interpret standard rawResult for all players with known IDs
20,321
def PositionedPhoneme(phoneme, word_initial = False, word_final = False, syllable_initial = False, syllable_final = False, env_start = False, env_end = False): pos_phoneme = deepcopy(phoneme) pos_phoneme.word_initial = word_initial pos_phoneme.word_final = word_final pos_phoneme.syllable_initial =...
A decorator for phonemes, used in applying rules over words. Returns a copy of the input phoneme, with additional attributes, specifying whether the phoneme occurs at a word or syllable boundary, or its position in an environment.
20,322
def start(self) -> None: self._setup() if self._run_control_loop: asyncio.set_event_loop(asyncio.new_event_loop()) self._heartbeat_reciever.start() self._logger.info() return self.loop.start() else: self._logger.debug()
Start the internal control loop. Potentially blocking, depending on the value of `_run_control_loop` set by the initializer.
20,323
def region(self): region_item = [subtag for subtag in self.subtags if subtag.type == ] return region_item[0] if len(region_item) > 0 else None
Get the region :class:`language_tags.Subtag.Subtag` of the tag. :return: region :class:`language_tags.Subtag.Subtag` that is part of the tag. The return can be None.
20,324
def bluemix(cls, vcap_services, instance_name=None, service_name=None, **kwargs): service_name = service_name or try: service = CloudFoundryService(vcap_services, instance_name=instance_name, serv...
Create a Cloudant session using a VCAP_SERVICES environment variable. :param vcap_services: VCAP_SERVICES environment variable :type vcap_services: dict or str :param str instance_name: Optional Bluemix instance name. Only required if multiple Cloudant instances are available. ...
20,325
def main(argv=None): parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument( , help= ) parser.add_argument(, help=) if argv is None: args = parser.parse_args() else: args = parser.parse_args(argv) print( % (args.pipeline, args.out...
Generates documentation for signature generation pipeline
20,326
def mobile(self): if self._mobile is None: self._mobile = MobileList(self._version, account_sid=self._solution[], ) return self._mobile
Access the mobile :returns: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileList :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileList
20,327
def get_context_data(self, **kwargs): for key in self.get_form_class_keys(): kwargs[.format(key)] = self.get_form(key) return super(FormMixin, self).get_context_data(**kwargs)
Insert the form into the context dict.
20,328
def _get_dx_tree(xy, degree): x, y = xy one = numpy.array([numpy.ones(x.shape, dtype=int)]) tree = [one] for d in range(1, degree): tree.append( numpy.concatenate( [ [tree[-1][0] / d * (d + 1) * ...
0 1*(0, 0) 0 2*(1, 0) 1*(0, 1) 0 3*(2, 0) 2*(1, 1) 1*(0, 2) 0 ... ... ... ...
20,329
def update_annotations(self): start_time = self.parent.overview.start_time if self.parent.notes.annot is None: all_annot = [] else: bookmarks = self.parent.notes.annot.get_bookmarks() events = self.get_selected_events() all_annot = bookm...
Update annotations made by the user, including bookmarks and events. Depending on the settings, it might add the bookmarks to overview and traces.
20,330
def run(cmd, printOutput=False, exceptionOnError=False, warningOnError=True, parseForRegEx=None, regExFlags=0, printOutputIfParsed=False, printErrorsIfParsed=False, exceptionIfParsed=False, dryrun=None): if dryrun: debug( % cmd) return (0, , None) debug( % cm...
Run cmd and return (status,output,parsedOutput). Unless dryrun is set True, cmd is run using subprocess.Popen. It returns the exit status from cmd, its output, and any output found by searching for the regular expression parseForRegEx. cmd is logged at the debug level. The parameters are: cmd...
20,331
def is_fe_ready(self): with self.readout(fill_buffer=True, callback=None, errback=None): commands = [] commands.extend(self.register.get_commands("ConfMode")) commands.extend(self.register.get_commands("RdRegister", address=[1])) self.register_utils.send_commands(commands...
Get FEI4 status of module. If FEI4 is not ready, resetting service records is necessary to bring the FEI4 to a defined state. Returns ------- value : bool True if FEI4 is ready, False if the FEI4 was powered up recently and is not ready.
20,332
def to_yaml(cls, representer, node): return representer.represent_scalar(cls.yaml_tag, node.value)
How to serialize this class back to yaml.
20,333
def OnCut(self, event): entry_line = \ self.main_window.entry_line_panel.entry_line_panel.entry_line if wx.Window.FindFocus() != entry_line: selection = self.main_window.grid.selection with undo.group(_("Cut")): data = self.main_window.acti...
Clipboard cut event handler
20,334
def reset_caches(self, **kwargs): self._raw_cache = {} self._models_cache = {} self._modules_cache = {} self._objects_cache = {}
Called by ``__init__()`` to initialise the caches for a helper instance. It is also called by Django's ``setting_changed`` signal to clear the caches when changes to settings are made. Although it requires slightly more memory, separate dictionaries are used for raw values, models, modu...
20,335
def to_list(self): self.conn.set_encoding(ROW_ENCODING_LIST) self.processor = lambda x, y: Row(x, y) return self
Set the current encoder output to :class:`giraffez.Row` objects and returns the cursor. This is the default value so it is not necessary to select this unless the encoder settings have been changed already.
20,336
def gitrepo(cwd): repo = Repository(cwd) if not repo.valid(): return {} return { : { : repo.gitlog(), : repo.gitlog(), : repo.gitlog(), : repo.gitlog(), : repo.gitlog(), : repo.gitlog() }, : os.envi...
Return hash of Git data that can be used to display more information to users. Example: "git": { "head": { "id": "5e837ce92220be64821128a70f6093f836dd2c05", "author_name": "Wil Gieseler", "author_email": "wil@example.com", "com...
20,337
def patch_related_object_descriptor_caching(ro_descriptor): class NewSingleObjectDescriptor(LanguageCacheSingleObjectDescriptor, ro_descriptor.__class__): pass if django.VERSION[0] == 2: ro_descriptor.related.get_cache_name = partial( NewSingleObjectDescriptor.get_cache_name, ...
Patch SingleRelatedObjectDescriptor or ReverseSingleRelatedObjectDescriptor to use language-aware caching.
20,338
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): local_stream = utils.BytearrayStream() if self._major: self._major.write(local_stream, kmip_version=kmip_version) else: raise ValueError( "Invalid struct missing the major p...
Write the data encoding the ProtocolVersion struct to a stream. Args: output_stream (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining th...
20,339
def unpack_scalar(cls, dataset, data): if (len(data.data_vars) == 1 and len(data[dataset.vdims[0].name].shape) == 0): return data[dataset.vdims[0].name].item() return data
Given a dataset object and data in the appropriate format for the interface, return a simple scalar.
20,340
def show_minimum_needs(self): from safe.gui.tools.minimum_needs.needs_calculator_dialog import ( NeedsCalculatorDialog ) dialog = NeedsCalculatorDialog(self.iface.mainWindow()) dialog.exec_()
Show the minimum needs dialog.
20,341
def append_child_field(self, linenum, indent, field_name, field_value): frame = self.current_frame() assert isinstance(frame,RootFrame) or isinstance(frame,ContainerFrame) and frame.indent < indent if frame.container.contains(ROOT_PATH, field_name): raise KeyError("field {0}...
:param linenum: The line number of the frame. :type linenum: int :param indent: The indentation level of the frame. :type indent: int :param path: :type path: Path :param field_name: :type field_name: str :param field_value: :type field_value: str
20,342
def prsint(string): string = stypes.stringToCharP(string) intval = ctypes.c_int() libspice.prsint_c(string, ctypes.byref(intval)) return intval.value
Parse a string as an integer, encapsulating error handling. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/prsint_c.html :param string: String representing an integer. :type string: str :return: Integer value obtained by parsing string. :rtype: int
20,343
def expression(callable, rule_name, grammar): num_args = len(getargspec(callable).args) if num_args == 2: is_simple = True elif num_args == 5: is_simple = False else: raise RuntimeError("Custom rule functions must take either 2 or 5 " "arguments, n...
Turn a plain callable into an Expression. The callable can be of this simple form:: def foo(text, pos): '''If this custom expression matches starting at text[pos], return the index where it stops matching. Otherwise, return None.''' if the expression matched: ...
20,344
def taubin(script, iterations=10, t_lambda=0.5, t_mu=-0.53, selected=False): filter_xml = .join([ , , .format(t_lambda), , , , , .format(t_mu), , , , , .format(iterations), , , , ...
The lambda & mu Taubin smoothing, it make two steps of smoothing, forth and back, for each iteration. Based on: Gabriel Taubin "A signal processing approach to fair surface design" Siggraph 1995 Args: script: the FilterScript object or script filename to write the filte...
20,345
def main(args=None): parser = ArgumentParser( prog=, description=DESCRIPTION) parser.add_argument( , nargs=, help=) parser.add_argument( , help=) parser.add_argument( , , action=, help=) args = parser.parse_args(args) paths = args...
Command line interface. :param list args: command line options (defaults to sys.argv) :returns: exit code :rtype: int
20,346
def load_xml(self, filepath): from os import path import xml.etree.ElementTree as ET uxpath = path.expanduser(filepath) if path.isfile(uxpath): tree = ET.parse(uxpath) vms("Parsing global settings from {}.".format(uxpath)) root = tree...
Loads the values of the configuration variables from an XML path.
20,347
def _find_relations(self): extractions = \ list(self.tree.execute("$.extractions[(@.@type is )]")) relations = [] for e in extractions: label_set = set(e.get(, [])) if in label_set: self.relation_dict[e...
Find all relevant relation elements and return them in a list.
20,348
def from_credentials_db(client_secrets, storage, api_version="v3", readonly=False, http_client=None, ga_hook=None): credentials = storage.get() return Client(_build(credentials, api_version, http_client), ga_hook)
Create a client for a web or installed application. Create a client with a credentials stored in stagecraft db. Args: client_secrets: dict, client secrets (downloadable from Google API Console) storage: stagecraft.apps.collectors.libs.ga.CredentialStorage, ...
20,349
def tgt_vocab(self): if self._tgt_vocab is None: tgt_vocab_file_name, tgt_vocab_hash = \ self._data_file[self._pair_key][ + + self._tgt_lang] [tgt_vocab_path] = self._fetch_data_path([(tgt_vocab_file_name, tgt_vocab_hash)]) with io.open(tgt_vocab_pat...
Target Vocabulary of the Dataset. Returns ------- tgt_vocab : Vocab Target vocabulary.
20,350
def notifications(self): if self._notifications is None: self._notifications = NotificationList(self._version, service_sid=self._solution[], ) return self._notifications
Access the notifications :returns: twilio.rest.notify.v1.service.notification.NotificationList :rtype: twilio.rest.notify.v1.service.notification.NotificationList
20,351
def file_arg(arg): prefix = if arg.startswith(prefix): return os.path.abspath(arg[len(prefix):]) else: msg = raise argparse.ArgumentTypeError(msg.format(arg))
Parses a file argument, i.e. starts with file://
20,352
def serialize(self, data): gml_ns = nrml.SERIALIZE_NS_MAP[] with open(self.dest, ) as fh: root = et.Element() uh_spectra = et.SubElement(root, ) _set_metadata(uh_spectra, self.metadata, _ATTR_MAP) periods_elem = et.SubElement(uh_spectra, ) ...
Write a sequence of uniform hazard spectra to the specified file. :param data: Iterable of UHS data. Each datum must be an object with the following attributes: * imls: A sequence of Intensity Measure Levels * location: An object representing the location of the...
20,353
def add_hash(self, value): self.leaves.append(Node(codecs.decode(value, ), prehashed=True))
Add a Node based on a precomputed, hex encoded, hash value.
20,354
async def reply_voice(self, voice: typing.Union[base.InputFile, base.String], caption: typing.Union[base.String, None] = None, duration: typing.Union[base.Integer, None] = None, disable_notification: typing.Union[base.Boolean, None] = None, ...
Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document). Source: https://core.telegram.org/bots/api#sendvoi...
20,355
def send(self, data=None, headers=None, ttl=0, gcm_key=None, reg_id=None, content_encoding="aes128gcm", curl=False, timeout=None): if headers is None: headers = dict() encoded = {} headers = CaseInsensitiveDict(headers) if data: enco...
Encode and send the data to the Push Service. :param data: A serialized block of data (see encode() ). :type data: str :param headers: A dictionary containing any additional HTTP headers. :type headers: dict :param ttl: The Time To Live in seconds for this message if the ...
20,356
def complete_io(self, iocb, msg): if _debug: IOController._debug("complete_io %r %r", iocb, msg) if iocb.ioState == COMPLETED: pass elif iocb.ioState == ABORTED: pass else: iocb.ioState = COMPLETED ...
Called by a handler to return data to the client.
20,357
def validate_units(self): if (not isinstance(self.waveunits, units.WaveUnits)): raise TypeError("%s is not a valid WaveUnit" % self.waveunits)
Ensure that wavelenth unit belongs to the correct class. There is no check for throughput because it is unitless. Raises ------ TypeError Wavelength unit is not `~pysynphot.units.WaveUnits`.
20,358
def add_hook_sub(self, address, topics, callback): LOGGER.info("Subscriber adding SUB hook %s for topics %s", str(address), str(topics)) socket = get_context().socket(SUB) for t__ in self._magickfy_topics(topics): socket.setsockopt_string(SUBSCRIBE, six.t...
Specify a *callback* in the same stream (thread) as the main receive loop. The callback will be called with the received messages from the specified subscription. Good for operations, which is required to be done in the same thread as the main recieve loop (e.q operations on the underly...
20,359
def start(self): self._timer = Timer(self.time, self.handler) self._timer.daemon = True self._timer.start() return
Starts the watchdog timer.
20,360
def use_options(allowed): def update_docstring(f): _update_option_docstring(f, allowed) @functools.wraps(f) def check_options(*args, **kwargs): options = kwargs.get(, {}) not_allowed = [ option for option in options if option not in allowed ...
Decorator that logs warnings when unpermitted options are passed into its wrapped function. Requires that wrapped function has an keyword-only argument named `options`. If wrapped function has {options} in its docstring, fills in with the docs for allowed options. Args: allowed (list str):...
20,361
def record_manifest(self): data = super(RabbitMQSatchel, self).record_manifest() params = sorted(list(self.get_user_vhosts())) data[] = params data[] = list(self.genv.sites or []) return data
Returns a dictionary representing a serialized state of the service.
20,362
def metadata(self, exportFormat="default", output=None, saveFolder=None, fileName=None): url = "%s/info/metadata/metadata.xml" % self.root allowedFormats = ["fgdc", "inspire", "iso19139", "iso19139-3.2...
exports metadata to the various supported formats Inputs: exportFormats - export metadata to the following formats: fgdc, inspire, iso19139, iso19139-3.2, iso19115, arcgis, and default. default means the value will be ISO 19139 Metadata Implementation Specification GML...
20,363
def create(cls, datacenter, memory, cores, ip_version, bandwidth, login, password, hostname, image, run, background, sshkey, size, vlan, ip, script, script_args, ssh): from gandi.cli.modules.network import Ip, Iface if not background and not cls.intty(): ...
Create a new virtual machine.
20,364
def _get_core_keywords(skw_matches, ckw_matches, spires=False): output = {} category = {} def _get_value_kw(kw): i = 0 while kw[i].isdigit(): i += 1 if i > 0: return int(kw[:i]) else: return 0 for skw, info in skw_matche...
Return the output for the field codes. :var skw_matches: dict of {keyword: [info,...]} :var ckw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of formatted core keywords
20,365
def _stub_obj(obj): from .mock import Mock if isinstance(obj, Stub): return obj if isinstance(obj, Mock): return stub(obj.__call__) if getattr(obj, , None) is None: if hasattr(obj, ): if obj.__self__ is not Non...
Stub an object directly.
20,366
def replicate(ctx, args): slave = ClusterNode.from_uri(args.node) master = ClusterNode.from_uri(args.master) if not master.is_master(): ctx.abort("Node {!r} is not a master.".format(args.master)) try: slave.replicate(master.name) except redis.ResponseError as e: ctx.abo...
Make node to be the slave of a master.
20,367
def map_structprop_resnums_to_seqprop_resnums(self, resnums, structprop=None, chain_id=None, seqprop=None, use_representatives=False): resnums = ssbio.utils.force_list(resnums) if use_representatives: seqprop = self.representative_s...
Map a residue number in any StructProp + chain ID to any SeqProp's residue number. Args: resnums (int, list): Residue numbers in the structure structprop (StructProp): StructProp object chain_id (str): Chain ID to map from seqprop (SeqProp): SeqProp object ...
20,368
def zipWithIndex(self): starts = [0] if self.getNumPartitions() > 1: nums = self.mapPartitions(lambda it: [sum(1 for i in it)]).collect() for i in range(len(nums) - 1): starts.append(starts[-1] + nums[i]) def func(k, it): for i, v in ...
Zips this RDD with its element indices. The ordering is first based on the partition index and then the ordering of items within each partition. So the first item in the first partition gets index 0, and the last item in the last partition receives the largest index. This metho...
20,369
def infer_newX(self, Y_new, optimize=True): from ..inference.latent_function_inference.inferenceX import infer_newX return infer_newX(self, Y_new, optimize=optimize)
Infer X for the new observed data *Y_new*. :param Y_new: the new observed data for inference :type Y_new: numpy.ndarray :param optimize: whether to optimize the location of new X (True by default) :type optimize: boolean :return: a tuple containing the posterior estimation of X ...
20,370
def parse_meta(content, meta_name, source_descr, content_attr_name="content"): dom = dhtmlparser.parseString(content) meta_tags = dom.find( "meta", fn=lambda x: x.params.get("name", "").lower() == meta_name.lower() ) return [ SourceString(tag.params[content_attr_name], sou...
Return list of strings parsed from `content` attribute from ``<meta>`` tags with given `meta_name`.
20,371
def license_loader(lic_dir=LIC_DIR): lics = [] for ln in os.listdir(lic_dir): lp = os.path.join(lic_dir, ln) with open(lp) as lf: txt = lf.read() lic = License(txt) lics.append(lic) return lics
Loads licenses from the given directory.
20,372
def formatted_filters(self): if not self._formatted_filters: filters = deepcopy(self.filters) self._formatted_filters = self._format_filter(filters, self._and_props) return self._formatted_filters
Cache and return filters as a comprehensive WQL clause.
20,373
def to_json_file(graph: BELGraph, file: TextIO, **kwargs) -> None: graph_json_dict = to_json(graph) json.dump(graph_json_dict, file, ensure_ascii=False, **kwargs)
Write this graph as Node-Link JSON to a file.
20,374
def _headers(self): if not self.access_token or not self.access_token_expires: self._basic_login() elif datetime.now() > self.access_token_expires - timedelta(seconds=30): self._basic_login() return {: HEADER_ACCEPT, : + self.access_token}
Ensure the Authorization Header has a valid Access Token.
20,375
def nodeids(self, ivs=None, quantifier=None): if ivs is None: nids = list(self._nodeids) else: _vars = self._vars nids = [] for iv in ivs: if iv in _vars and IVARG_ROLE in _vars[iv][]: nids.extend(_vars[iv][][IV...
Return the list of nodeids given by *ivs*, or all nodeids. Args: ivs: the intrinsic variables of the predications to select; if `None`, return all nodeids (but see *quantifier*) quantifier: if `True`, only return nodeids of quantifiers; if `False`, only r...
20,376
def rados_df(self, host_list=None, remote_user=None, remote_pass=None): result, failed_hosts = self.runner.ansible_perform_operation( host_list=host_list, remote_user=remote_user, remote_pass=remote_pass, ...
Invoked the rados df command and return output to user
20,377
def validate(self, options): try: codecs.getencoder(options.char_encoding) except LookupError: self.parser.error("invalid %s" % options.char_encoding)
Validate the options or exit()
20,378
def _read_http_settings(self, size, kind, flag): if size % 5 != 0: raise ProtocolError(f, quiet=True) _flag = dict( ACK=False, ) for index, bit in enumerate(flag): if index == 0 and bit: _flag[] = True elif b...
Read HTTP/2 SETTINGS frames. Structure of HTTP/2 SETTINGS frame [RFC 7540]: +-----------------------------------------------+ | Length (24) | +---------------+---------------+---------------+ | Type (8) | Flags (8) | ...
20,379
def access_storage_list(**kwargs): ctx = Context(**kwargs) ctx.execute_action(, **{ : ctx.repo.create_secure_service(), })
Shows collections with ACL.
20,380
def get_current_thread_id(thread): try: tid = thread.__pydevd_id__ if tid is None: raise AttributeError() except AttributeError: tid = _get_or_compute_thread_id_with_lock(thread, is_current_thread=True) return tid
Note: the difference from get_current_thread_id to get_thread_id is that for the current thread we can get the thread id while the thread.ident is still not set in the Thread instance.
20,381
def metadata_and_cell_to_header(notebook, metadata, text_format, ext): header = [] lines_to_next_cell = None if notebook.cells: cell = notebook.cells[0] if cell.cell_type == : lines = cell.source.strip().splitlines() if len(lines) >= 2 \ and...
Return the text header corresponding to a notebook, and remove the first cell of the notebook if it contained the header
20,382
def destroy(self, request, pk=None, parent_lookup_organization=None): user = get_object_or_404(User, pk=pk) org = get_object_or_404( SeedOrganization, pk=parent_lookup_organization) self.check_object_permissions(request, org) org.users.remove(user) return Res...
Remove a user from an organization.
20,383
def frequency(self, mapping): return self.__matrix[:, self.hg.mappings[mapping]].mean()
Returns frequency of a given :class:`caspo.core.mapping.Mapping` Parameters ---------- mapping : :class:`caspo.core.mapping.Mapping` A logical conjuntion mapping Returns ------- float Frequency of the given mapping over all logical networks ...
20,384
def err(r): import sys rc=r[] re=r[] out(+re) sys.exit(rc)
Input: { return - return code error - error text } Output: Nothing; quits program
20,385
def _gen_form_data(self) -> multipart.MultipartWriter: for dispparams, headers, value in self._fields: try: if hdrs.CONTENT_TYPE in headers: part = payload.get_payload( value, content_type=headers[hdrs.CONTENT_TYPE], ...
Encode a list of fields using the multipart/form-data MIME format
20,386
def write_outro (self): self.stoptime = time.time() duration = self.stoptime - self.starttime self.comment(_("Stopped checking at %(time)s (%(duration)s)") % {"time": strformat.strtime(self.stoptime), "duration": strformat.strduration_long(duration)})
Write outro comments.
20,387
def member_ids(self): info = self.raw.get(ATTR_MEMBERS, {}) if not info or ROOT_DEVICES2 not in info: return [] return info[ROOT_DEVICES2].get(ATTR_ID, [])
Members of this group.
20,388
def guess_depth(self, root_dir): deepest = -1 for path, dirs, files in os.walk(root_dir): depth = self.path_depth(path) filtered_files = self._filter_files(files, path) if filtered_files: logger.info("Guessing depth of directory repository at ...
Try to guess the depth of a directory repository (i.e. whether it has sub-folders for multiple subjects or visits, depending on where files and/or derived label files are found in the hierarchy of sub-directories under the root dir. Parameters ---------- root_dir : str ...
20,389
def astype(self, dtype): dtype = np.dtype(dtype) filters = [] if self._filters: filters.extend(self._filters) filters.insert(0, AsType(encode_dtype=self._dtype, decode_dtype=dtype)) return self.view(filters=filters, dtype=dtype, read_only=True)
Returns a view that does on the fly type conversion of the underlying data. Parameters ---------- dtype : string or dtype NumPy dtype. Notes ----- This method returns a new Array object which is a view on the same underlying chunk data. Modifying any...
20,390
def _plot_connectivity_helper(self, ii, ji, mat_datai, data, lims=[1, 8]): from matplotlib.pyplot import quiver, colorbar, clim, matshow I = ~np.isnan(mat_datai) & (ji != -1) & (mat_datai >= 0) mat_data = mat_datai[I] j = ji[I] i = ii[I] x = i.astype(float) % da...
A debug function used to plot the adjacency/connectivity matrix.
20,391
def clone_g0_inputs_on_ngpus(self, inputs, outputs, g0_inputs): assert len(inputs) == len(outputs), ( ) inputs[0].update(g0_inputs) outputs[0].update(g0_inputs) for i in range(1, len(inputs)): for k, v in g0_inputs.iteritems(): if k not in inputs[i]: ...
Clone variables unused by the attack on all GPUs. Specifically, the ground-truth label, y, has to be preserved until the training step. :param inputs: A list of dictionaries as the inputs to each step. :param outputs: A list of dictionaries as the outputs of each step. :param g0_inputs: Initial variabl...
20,392
def bit_size(self): if self._bit_size is None: if self.algorithm == : prime = self[].parsed[].native elif self.algorithm == : prime = self[][][].native elif self.algorithm == : prime = self[].parsed[].native ...
:return: The bit size of the private key, as an integer
20,393
def destroy_list(self, list_id): return List(tweepy_list_to_json(self._client.destroy_list(list_id=list_id)))
Destroy a list :param list_id: list ID number :return: The destroyed list object :rtype: :class:`~responsebot.models.List`
20,394
def _compose_restart(services): def _restart_container(client, container): log_to_client(.format(get_canonical_container_name(container))) client.restart(container[], timeout=1) assembled_specs = get_assembled_specs() if services == []: services = [spec.name for spec in assemb...
Well, this is annoying. Compose 1.2 shipped with the restart functionality fucking broken, so we can't set a faster timeout than 10 seconds (which is way too long) using Compose. We are therefore resigned to trying to hack this together ourselves. Lame. Relevant fix which will make it into the next...
20,395
def pmbb(self,*args,**kwargs): out= self._orb.pmbb(*args,**kwargs) if len(out) == 1: return out[0] else: return out
NAME: pmbb PURPOSE: return proper motion in Galactic latitude (in mas/yr) INPUT: t - (optional) time at which to get pmbb (can be Quantity) obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer in the Galactocentri...
20,396
def _pull_and_tag_image(self, image, build_json, nonce): image = image.copy() first_library_exc = None for _ in range(20): return new_image except docker.errors.NotFound: ...
Docker pull the image and tag it uniquely for use by this build
20,397
def html2md(html_string): if os.path.isfile(html_string): file = open(html_string, , encoding=) lines = file.readlines() file.close() html_string = .join(lines) table_data, spans, use_headers = html2data(html_string) if table_data == : return return data2...
Convert a string or html file to a markdown table string. Parameters ---------- html_string : str Either the html string, or the filepath to the html Returns ------- str The html table converted to a Markdown table Notes ----- This function requires BeautifulSoup_ ...
20,398
def sizeof(s): if hasattr(s, ): return s._size_ elif isinstance(s, bytes): return len(s) raise ValueError(s)
Return the size of an object when packed
20,399
def isDirect(self): direct = (self._messageType == 0x00) if self.isDirectACK or self.isDirectNAK: direct = True return direct
Test if the message is a direct message type.