Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
353,600
def get_declared_fields(bases, attrs, cls_filter, with_base_fields=True, extra_attr_name=): fields = [(field_name, attrs.pop(field_name))\ for field_name, obj in attrs.items()\ if isinstance(obj, cls_filter)] fields.sort(key=lambda x: x[1].creation_counter) ...
Create a list of form field instances from the passed in 'attrs', plus any similar fields on the base classes (in 'bases'). This is used by both the Form and ModelForm metclasses. If 'with_base_fields' is True, all fields from the bases are used. Otherwise, only fields in the 'declared_fields' attribut...
353,601
def values(self): if self.cache.cache is None: backend = self.read_backend return backend.execute(backend.structure(self).values(), self.load_values) else: return self.cache.cache.values()
Iteratir over values of :class:`PairMixin`.
353,602
def out_deque(self): self.expire() expired = {k: v for (k, v) in self._tracking.items() if self.get(k) is None} for k, v in expired.items(): del self._tracking[k] self._out_deque.append(v) return self._out_deque
The :class:`collections.deque` to which expired items are added.
353,603
def beat(ref, est, **kwargs): rreference.jamsestimated.jamsbeatbeat namespace = ref = coerce_annotation(ref, namespace) est = coerce_annotation(est, namespace) ref_times, _ = ref.to_event_values() est_times, _ = est.to_event_values() return mir_eval.beat.evaluate(ref_times, est_times, **...
r'''Beat tracking evaluation Parameters ---------- ref : jams.Annotation Reference annotation object est : jams.Annotation Estimated annotation object kwargs Additional keyword arguments Returns ------- scores : dict Dictionary of scores, where the key i...
353,604
def modules(self): resource = self.RMODULES params = { self.PLIMIT: self.max_items, self.PSORT_BY: self.VLATEST_RELEASE } for page in self._fetch(resource, params): yield page
Fetch modules pages.
353,605
def _emit_warning(cls, message): sys.stderr.write(.format(message=message)) sys.stderr.flush()
Print an warning message to STDERR.
353,606
def content_negotiation(ids = None, format = "bibtex", style = , locale = "en-US", url = None, **kwargs): s a style that CrossRef doesnll get a `(500) Internal Server Error` :param locale: [str] Language locale. See `locale.locale_alias` :param url: [str] Base URL for the content negotiation request. De...
Get citations in various formats from CrossRef :param ids: [str] Search by a single DOI or many DOIs, each a string. If many passed in, do so in a list :param format: [str] Name of the format. One of "rdf-xml", "turtle", "citeproc-json", "citeproc-json-ish", "text", "ris", "bibtex" (Default), "...
353,607
def sde(self): import scipy.linalg as la F = None L = None Qc = None H = None Pinf = None P0 = None dF = None dQc = None dPinf = None dP0 = None n = 0 nq = 0 nd = 0 ...
Support adding kernels for sde representation
353,608
def activate_api_deployment(restApiId, stageName, deploymentId, region=None, key=None, keyid=None, profile=None): try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = conn.update_stage(restApiId=restApiId, stageName=stageName, ...
Activates previously deployed deployment for a given stage CLI Example: .. code-block:: bash salt myminion boto_apigateway.activate_api_deployent restApiId stagename deploymentId
353,609
def getExtensions(self): extensions = [] if isinstance(self.supportedExtensions, list): for ext in self.supportedExtensions: extensionURL = self._url + "/exts/%s" % ext if ext == "SchematicsServer": extensions.append(SchematicsServ...
returns objects for all map service extensions
353,610
def _get_keycachelike(self, keycache, keys, get_adds_dels, parentity, branch, turn, tick, *, forward): keycache_key = parentity + (branch,) keycache2 = keycache3 = None if keycache_key in keycache: keycache2 = keycache[keycache_key] if turn in keycache2: ...
Try to retrieve a frozenset representing extant keys. If I can't, generate one, store it, and return it.
353,611
def delete_state_by_id(cls, state_id, **kwargs): kwargs[] = True if kwargs.get(): return cls._delete_state_by_id_with_http_info(state_id, **kwargs) else: (data) = cls._delete_state_by_id_with_http_info(state_id, **kwargs) return data
Delete State Delete an instance of State by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_state_by_id(state_id, async=True) >>> result = thread.get() :param async boo...
353,612
def append_data(self, data_buffer): if len(data_buffer) % (self.sample_width * self.channels) != 0: raise ValueError("length of data_buffer must be a multiple of (sample_width * channels)") self._buffer += data_buffer self._left += len(data_buffer)
Append data to this audio stream :Parameters: `data_buffer` : str, basestring, Bytes a buffer with a length multiple of (sample_width * channels)
353,613
def deleteuser(self, user_id): deleted = self.delete_user(user_id) if deleted is False: return False else: return True
Deletes a user. Available only for administrators. This is an idempotent function, calling this function for a non-existent user id still returns a status code 200 OK. The JSON response differs if the user was actually deleted or not. In the former the user is returned and in the latter ...
353,614
def parse_move(self, move_msg): type_idx = move_msg.index(":") move_type = move_msg[:type_idx] pos_idx = move_msg.index(",") move_x = int(move_msg[type_idx+1:pos_idx]) move_y = int(move_msg[pos_idx+1:]) return move_type, move_x, move_y
Parse a move from a string. Parameters ---------- move_msg : string a valid message should be in: "[move type]: [X], [Y]" Returns -------
353,615
def _estimate(self, buffer): m = self._bucket_number raw_e = self._alpha * pow(m, 2) / sum([pow(2, -x) for x in buffer]) if raw_e <= 5 / 2.0 * m: v = buffer.count(0) if v != 0: return m * log(m / float(v), 2) else: retu...
Return the estimate of the cardinality :return: esitimate of the cardinality
353,616
def from_json(cls, json): if json["name"] in _KEYRANGES_CLASSES: return _KEYRANGES_CLASSES[json["name"]].from_json(json) raise ValueError("Invalid json %s", json)
Deserialize from json. Args: json: a dict of json compatible fields. Returns: a KeyRanges object. Raises: ValueError: if the json is invalid.
353,617
def build_response_card(title, subtitle, options): buttons = None if options is not None: buttons = [] for i in range(min(5, len(options))): buttons.append(options[i]) return { : , : 1, : [{ : title, : subtitle, : ...
Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons.
353,618
async def activate_module(channel, module_name, activate): data = datatools.get_data() server_id = channel.server.id _dir = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) _dir_modules = "{}/../".format(_dir) if not os.path.isfile("{}/{}/_data.py".format(_dir_modules, m...
Changes a modules activated/deactivated state for a server Args: channel: The channel to send the message to module_name: The name of the module to change state for activate: The activated/deactivated state of the module
353,619
def subscribe(self, peer_jid): self.client.enqueue( stanza.Presence(type_=structs.PresenceType.SUBSCRIBE, to=peer_jid) )
Request presence subscription with the given `peer_jid`. This is deliberately not a coroutine; we don’t know whether the peer is online (usually) and they may defer the confirmation very long, if they confirm at all. Use :meth:`on_subscribed` to get notified when a peer accepted a subsc...
353,620
def validate(self, body, signature): gen_signature = hmac.new( self.channel_secret, body.encode(), hashlib.sha256 ).digest() return compare_digest( signature.encode(), base64.b64encode(gen_signature) )
Check signature. https://devdocs.line.me/en/#webhook-authentication :param str body: Request body (as text) :param str signature: X-Line-Signature value (as text) :rtype: bool :return: result
353,621
def set_volumes_tags(tag_maps, authoritative=False, dry_run=False, region=None, key=None, keyid=None, profile=None): filtersfilterstagspendingrebootingrunningstoppingstoppedt change anything, just return a dictionary describing any changes which would have been applied. returns (dic...
.. versionadded:: 2016.11.0 tag_maps (list) List of dicts of filters and tags, where 'filters' is a dict suitable for passing to the 'filters' argument of get_all_volumes() above, and 'tags' is a dict of tags to be set on volumes (via create_tags/delete_tags) as matched by the given filters...
353,622
def make_ndx_captured(**kwargs): kwargs[]=False user_input = kwargs.pop(,[]) user_input = [cmd for cmd in user_input if cmd != ] kwargs[] = user_input + [, ] return gromacs.make_ndx(**kwargs)
make_ndx that captures all output Standard :func:`~gromacs.make_ndx` command with the input and output pre-set in such a way that it can be conveniently used for :func:`parse_ndxlist`. Example:: ndx_groups = parse_ndxlist(make_ndx_captured(n=ndx)[0]) Note that the convenient :func:`get_ndx_...
353,623
def motioncheck(ref_file, end_file, out_path=None, thres=5.0): ref = nib.load(ref_file) end = nib.load(end_file) ref_data = ref.get_data() end_data = end.get_data() ref_aff=ref.get_affine() end_aff=end.get_affine() if np.array_equal(ref_aff, end_aff): pr...
Checks motion between structural scans of the same modality. Ideally obtained at the beginning and end of a scanning session. Parameters ---------- ref_file: nifti file Nifti file of first localizer acquired at the beginning of the session end_file: nifti nifti file of the locali...
353,624
def _django_to_es_field(self, field): from django.db import models prefix = "" if field.startswith("-"): prefix = "-" field = field.lstrip("-") if field in ["id", "pk"]: return "_id", models.AutoField try: dj_field, _, _...
We use this function in value_list and ordering to get the correct fields name
353,625
def get_event_of_type(op, event_type): events = get_events(op) if not events: return None return [e for e in events if e.get(, {}).get() == event_type]
Return all events of a particular type.
353,626
def create_api_pool_deploy(self): return ApiPoolDeploy( self.networkapi_url, self.user, self.password, self.user_ldap)
Get an instance of Api Pool Deploy services facade.
353,627
def get_gnupg_components(sp=subprocess): args = [util.which(), ] output = check_output(args=args, sp=sp) components = dict(re.findall(, output.decode())) log.debug(, components) return components
Parse GnuPG components' paths.
353,628
def show_seq(clus_obj, index): current = clus_obj.clus clus_seqt = clus_obj.seq clus_locit = clus_obj.loci itern = 0 for idc in current.keys(): itern += 1 timestamp = str(idc) seqListTemp = () f = open("/tmp/"+timestamp+".fa","w") for idl in current[idc]...
Get the precursor and map sequences to it. this way we create a positional map.
353,629
def frameclass(cls): assert issubclass(cls, Frames.Frame) if len(cls.__name__) == 3: base = cls.__bases__[0] if issubclass(base, Frames.Frame) and base._in_version(3, 4): assert not hasattr(base, "_v2_frame") base._v2_frame = cls if bas...
Register cls as a class representing an ID3 frame. Sets cls.frameid and cls._version if not present, and registers the new frame in Tag's known_frames dictionary. To be used as a decorator on the class definition: @frameclass class UFID(Frame): _framespec = (NullTerminatedStringSpec("owne...
353,630
def advance(self, dt_msec): try: self.v += 0.5 * dt_msec * (0.04 * self.v ** 2 + 5 * self.v + 140 - self.u + self.current) self.v += 0.5 * dt_msec * (0.04 * self.v ** 2 + 5 * self.v + 140 - self.u + self.current) self.u += dt_msec ...
Advances simulation time by the given time step in milliseconds. v' = 0.04 * v^2 + 5v + 140 - u + I u' = a * (b * v - u) if v >= 30 then v <- c, u <- u + d
353,631
def sort(self): if self.single_interval is None or self.single_interval != 0: return self.mid_sorted_by_start.sort(key = lambda x: x[0]) self.mid_sorted_by_end.sort(key = lambda x: x[1], reverse=True) if self.left_subtree is not None: self.left_subtree.s...
Must be invoked after all intevals have been added to sort mid_** arrays.
353,632
def _assert_explicit_vr(dicom_input): if settings.validate_multiframe_implicit: header = dicom_input[0] if header.file_meta[0x0002, 0x0010].value == : raise ConversionError()
Assert that explicit vr is used
353,633
def GetNewSessionID(self, **_): return rdfvalue.SessionID(base="aff4:/hunts", queue=self.runner_args.queue)
Returns a random integer session ID for this hunt. All hunts are created under the aff4:/hunts namespace. Returns: a formatted session id string.
353,634
def adam_convert(job, master_ip, inputs, in_file, in_snps, adam_file, adam_snps, spark_on_toil): log.info("Converting input BAM to ADAM.") call_adam(job, master_ip, ["transform", in_file, adam_file], memory=inputs.memory, run_local=inputs.run_local, ...
Convert input sam/bam file and known SNPs file into ADAM format
353,635
def download_version(version, url=None, verbose=False, binary=False): assert_jdk_valid_for_cassandra_version(version) archive_url = ARCHIVE if CCM_CONFIG.has_option(, ): archive_url = CCM_CONFIG.get(, ) if binary: archive_url = "%s/%s/apache-cassandra-%s-bin.tar.gz" % (archive_url...
Download, extract, and build Cassandra tarball. if binary == True, download precompiled tarball, otherwise build from source tarball.
353,636
def _heavyQuery(variantSetId, callSetIds): request = protocol.SearchVariantsRequest() request.reference_name = request.variant_set_id = variantSetId for callSetId in callSetIds: request.call_set_ids.add(callSetId) request.page_size = 100 request.end = 100000 return request
Very heavy query: calls for the specified list of callSetIds on chromosome 2 (11 pages, 90 seconds to fetch the entire thing on a high-end desktop machine)
353,637
async def list(self, *args, **kwargs): limit = int(kwargs.pop(, self.limit)) limit = 1000 if limit == 0 else limit offset = int(kwargs.pop(, self.offset)) projection = None if self._meta.fts_operator in kwargs.keys(): filters = { : ...
Corresponds to GET request without a resource identifier, fetching documents from the database
353,638
def filter_genes(self, gene_names : Iterable[str], inplace=False): return self.drop(set(self.genes) - set(gene_names), inplace=inplace)
Filter the expression matrix against a _genome (set of genes). Parameters ---------- gene_names: list of str The genome to filter the genes against. inplace: bool, optional Whether to perform the operation in-place. Returns ------- ExpMat...
353,639
def override_ssh_auth_env(): ssh_auth_sock = "SSH_AUTH_SOCK" old_ssh_auth_sock = os.environ.get(ssh_auth_sock) del os.environ[ssh_auth_sock] yield if old_ssh_auth_sock: os.environ[ssh_auth_sock] = old_ssh_auth_sock
Override the `$SSH_AUTH_SOCK `env variable to mock the absence of an SSH agent.
353,640
def enter(self, n=1, interval=0, pre_dl=None, post_dl=None): self.delay(pre_dl) self.k.tap_key(self.k.enter_key, n, interval) self.delay(post_dl)
Press enter key n times. **中文文档** 按回车键/换行键 n 次。
353,641
def validate_mandatory_str_fields(self, messages): FIELDS = [, , , ] messages = self.validate_str_fields(FIELDS, False, messages) return messages
Fields marked as Mandatory and of type string in class docstring must be of a type that provides __str__ method.
353,642
def read(file, frames=-1, start=0, stop=None, dtype=, always_2d=False, fill_value=None, out=None, samplerate=None, channels=None, format=None, subtype=None, endian=None, closefd=True): with SoundFile(file, , samplerate, channels, subtype, endian, format, closefd) as f: ...
Provide audio data from a sound file as NumPy array. By default, the whole file is read from the beginning, but the position to start reading can be specified with `start` and the number of frames to read can be specified with `frames`. Alternatively, a range can be specified with `start` and `stop`. ...
353,643
def do_filter(config, config_dir): if not os.path.exists(config_dir): print "Configuration does not exist.".format(config) exit(1) editor = os.environ["EDITOR"] config_filter = os.path.join(config_dir, ) call([editor, config_filter]) print "Filter configuration has been u...
CLI action "run editor for filters list".
353,644
async def _request_io(self, h11_request, h11_body, h11_connection): s been built, and calls a couple of cleanup functions to check for redirects / store cookies and the likes. Args: h11_request (h11.Request): A h11.Request object h11_body (h11.Data): A h11.Data o...
Takes care of the i/o side of the request once it's been built, and calls a couple of cleanup functions to check for redirects / store cookies and the likes. Args: h11_request (h11.Request): A h11.Request object h11_body (h11.Data): A h11.Data object, representing the re...
353,645
def run_game(load_file, selfplay_dir=None, holdout_dir=None, sgf_dir=None, holdout_pct=0.05): if sgf_dir is not None: minimal_sgf_dir = os.path.join(sgf_dir, ) full_sgf_dir = os.path.join(sgf_dir, ) utils.ensure_dir_exists(minimal_sgf_dir) utils.ensure_dir_exists(fu...
Takes a played game and record results and game data.
353,646
def perform_check(self, env: env_tools.PreparedEnv, verbose: bool) -> Tuple[bool, str]:
Evaluates the status check and returns a pass/fail with message. Args: env: Describes a prepared python 3 environment in which to run. verbose: When set, more progress output is produced. Returns: A tuple containing a pass/fail boolean and then a details message.
353,647
def _split_vlines_hlines(lines): vlines, hlines = [], [] for line in lines: (vlines if line.x1 - line.x0 < 0.1 else hlines).append(line) return vlines, hlines
Separates lines into horizontal and vertical ones
353,648
def printFromHTML(self, sr_html): debug_mode = App.config.getConfiguration().debug_mode if debug_mode: tmp_fn = tempfile.mktemp(suffix=".html") open(tmp_fn, "wb").write(sr_html) pdf_fn = tempfile.mktemp(suffix=".pdf") pdf_repor...
Tis function generates a pdf file from the html :sr_html: the html to use to generate the pdf
353,649
def mutual_information(corpus, featureset_name, min_weight=0.9, filter=lambda f, v, c, dc: True): graph = feature_cooccurrence(corpus, featureset_name, min_weight=1, filter=filter) mgraph = type(graph)() keep_nodes = set() fset = corpus.feat...
Generates a graph of features in ``featureset`` based on normalized `pointwise mutual information (nPMI) <http://en.wikipedia.org/wiki/Pointwise_mutual_information>`_. .. math:: nPMI(i,j)=\\frac{log(\\frac{p_{ij}}{p_i*p_j})}{-1*log(p_{ij})} ...where :math:`p_i` and :math:`p_j` are the probabil...
353,650
def move_arc(x, y, r, speed = 1, orientation = True): _x, _y = win32api.GetCursorPos() c_len = (r**2 - (((x - _x)/2)**2 + ((y - _y)/2)**2))**0.5 t = (c_len**2/((y - _y)**2 + (x - _x)**2))**0.5 t = t if orientation else -t centre = ((_x + x)/2 + t*(_x - x), (_y + y)/2 + t*(y - _y)) if ...
Moves the cursor in an arc of radius r to (x, y) at a certain speed :param x: target x-ordinate :param y: target y-ordinate :param r: radius :param speed: pixel traversal rate :param orientation: direction of arc :return: None
353,651
def zip(self, *args): args = list(args) args.insert(0, self.obj) maxLen = _(args).chain().collect(lambda x, *args: len(x)).max().value() for i, v in enumerate(args): l = len(args[i]) if l < maxLen: args[i] for x in range(maxLen...
Zip together multiple lists into a single array -- elements that share an index go together.
353,652
def synchronize (lock, func, log_duration_secs=0): def newfunc (*args, **kwargs): t = time.time() with lock: duration = time.time() - t if duration > log_duration_secs > 0: print("WARN:", func.__name__, "locking took %0.2f seconds" % duration, fi...
Return synchronized function acquiring the given lock.
353,653
def sample(self, samples=[], **kwargs): kwargs = {k: v for k, v in kwargs.items() if k != } if kwargs and samples: raise Exception() elif kwargs: sample = [slice(None) for _ in range(self.ndims)] for dim, val in kwargs.items(): sample[...
Allows sampling of an Image as an iterator of coordinates matching the key dimensions, returning a new object containing just the selected samples. Alternatively may supply kwargs to sample a coordinate on an object. On an Image the coordinates are continuously indexed and will always sn...
353,654
def run_command(self, scan_id, host, cmd): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) options = self.get_scan_options(scan_id) port = int(options[]) timeout = int(options[]) ...
Run a single command via SSH and return the content of stdout or None in case of an Error. A scan error is issued in the latter case. For logging into 'host', the scan options 'port', 'username', 'password' and 'ssh_timeout' are used.
353,655
def get_nics(vm_, **kwargs): * conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics
Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: pa...
353,656
def include_file_cb(include_path, line_ranges, symbol): lang = if include_path.endswith((".md", ".markdown")): lang = else: split = os.path.splitext(include_path) if len(split) == 2: ext = split[1].strip() lang = LANG...
Banana banana
353,657
def hide_stevedore_logs(): stevedore_logger = logging.getLogger() stevedore_logger.propagate = False stevedore_logger.setLevel(logging.ERROR) stevedore_logger.addHandler(logging.NullHandler())
Hides the logs of stevedore, this function was added in order to support older versions of stevedore We are using the NullHandler in order to get rid from 'No handlers could be found for logger...' msg Returns: None
353,658
def show_default_popup(self, pos): state = self.state if state.default_popup.popup is not None: wx_menu = state.default_popup.popup.wx_menu() state.frame.PopupMenu(wx_menu, pos)
show default popup menu
353,659
def t_RELID(self, t): r t.endlexpos = t.lexpos + len(t.value) return t
r'R[0-9]+
353,660
def _get_connection_info(): info = % CONN.url if CONN.creds is not None: info += % CONN.creds[0] else: info += info += % ( if CONN.ca_certs is None else CONN.ca_certs) info += % ( if CONN.no_verification else ) info += % CONN.default_n...
Return a string with the connection info.
353,661
def buffer(self, data): if not hasattr(self, ): return None if len(self._buffer): self._buffer.extend(data) else: self._buffer = bytearray(data)
Buffer unused bytes from the input stream.
353,662
def get_qualifier_dict(vocabularies, qualifier_vocab): % (qualifier_vocab) ) else: return vocabularies.get(qualifier_vocab)
Get the qualifier dictionary based on the element's qualifier vocabulary.
353,663
def _make_access_from_stat(self, stat_result): access = {} access[] = Permissions(mode=stat_result.st_mode).dump() access[] = stat_result.st_gid access[] = stat_result.st_uid if self.platform in ("linux", "darwin", "freebsd"): def entry_name(db, _id): ...
Make an *access* dictionnary from a stat result.
353,664
def get_firmware_image(self, image_id): api = self._get_api(update_service.DefaultApi) return FirmwareImage(api.firmware_image_retrieve(image_id))
Get a firmware image with provided image_id. :param str image_id: The firmware ID for the image to retrieve (Required) :return: FirmwareImage
353,665
def _inject_patched_examples(self, existing_item, patched_item): for key, _ in patched_item.examples.items(): patched_example = patched_item.examples[key] existing_examples = existing_item.examples if key in existing_examples: existing_examples[key].f...
Injects patched examples into original examples.
353,666
def _create_producer(self): if not self.closed: try: self.logger.debug("Creating new kafka producer using brokers: " + str(self.settings[])) return KafkaProducer(bootstrap_servers=self.settings[], ...
Tries to establish a Kafka consumer connection
353,667
def render_django_response(self, **kwargs): from django.http import HttpResponse return HttpResponse( self.render(**kwargs), content_type= )
Render the graph, and return a Django response
353,668
async def scalar(self, query, *multiparams, **params): res = await self.execute(query, *multiparams, **params) return (await res.scalar())
Executes a SQL query and returns a scalar value.
353,669
def upload_batterystats(filename, username, password, bucket_name=BUCKET_NAME, bucket_desc=BUCKET_DESC): zapi = pyzenobase.ZenobaseAPI(username, password) bucket = zapi.create_or_get_bucket(bucket_name, description=bucket_desc) bucket_id = bucket["@id"] events = [] with open(filename, newline...
Works with CSVs generated by the Android app 'Battery Log' (https://play.google.com/store/apps/details?id=kr.hwangti.batterylog)
353,670
def get_font_face(self): return FontFace._from_pointer( cairo.cairo_get_font_face(self._pointer), incref=True)
Return the current font face. :param font_face: A new :class:`FontFace` object wrapping an existing cairo object.
353,671
def in6_getRandomizedIfaceId(ifaceid, previous=None): s = b"" if previous is None: d = b"".join(chb(x) for x in range(256)) for _ in range(8): s += chb(random.choice(d)) previous = s s = inet_pton(socket.AF_INET6, "::" + ifaceid)[8:] + previous import hashlib ...
Implements the interface ID generation algorithm described in RFC 3041. The function takes the Modified EUI-64 interface identifier generated as described in RFC 4291 and an optional previous history value (the first element of the output of this function). If no previous interface identifier is provide...
353,672
def MapSizer(field_descriptor, is_message_map): entry_msg = message_type._concrete_class(key=key, value=value) total += message_sizer(entry_msg) if is_message_map: value.ByteSize() return total return FieldSize
Returns a sizer for a map field.
353,673
def all_build_jobs(self): from db.models.build_jobs import BuildJob return BuildJob.all.filter(project=self)
Similar to build_jobs, but uses the default manager to return archived experiments as well.
353,674
def delete(self, model, commit=True): self.is_instance(model) db.session.delete(model) if commit: db.session.commit() return model
Delete Puts model for deletion into unit of work and optionall commits transaction :param model: object, model to delete :param commit: bool, commit? :return: object, deleted model
353,675
def is_installed(self, bug: Bug) -> bool: r = self.__api.get(.format(bug.name)) if r.status_code == 200: answer = r.json() assert isinstance(answer, bool) return answer if r.status_code == 404: raise KeyError("no bug found with ...
Determines whether the Docker image for a given bug has been installed on the server.
353,676
def startswith_field(field, prefix): if prefix.startswith("."): return True if field.startswith(prefix): if len(field) == len(prefix) or field[len(prefix)] == ".": return True return False
RETURN True IF field PATH STRING STARTS WITH prefix PATH STRING
353,677
def list(self, from_=values.unset, to=values.unset, date_created_on_or_before=values.unset, date_created_after=values.unset, limit=None, page_size=None): return list(self.stream( from_=from_, to=to, date_created_on_or_before=date_created_on_...
Lists FaxInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param unicode from_: Retrieve only those faxes sent from this phone number :param unicode to: Retrieve only those faxes sent to this ph...
353,678
def fBrown(H,T,N,M,dW = None,cholesky = False): alpha = 0.5-H times = np.linspace(0, T, N) dt = T/(N-1) if cholesky: if dW is not None: raise ValueError() times = times[1:] tdt = times/np.reshape(times,(-1,1)) tdt[np.tril_indices(N-1,-1)]=0 cov = ...
Sample fractional Brownian motion with differentiability index H on interval [0,T] (H=1/2 yields standard Brownian motion) :param H: Differentiability, larger than 0 :param T: Final time :param N: Number of time steps :param M: Number of samples :param dW: Driving noise, optional
353,679
def compose(*fs): rs = tuple(reversed(fs)) def composed(n): return reduce(lambda a, b: b(a), rs, n) try: composed.__doc__ = + _composed_doc(fs) except AttributeError: pass else: composed.__name__ = .join(f.__name__ for f i...
Compose functions together in order: compose(f, g, h) = lambda n: f(g(h(n)))
353,680
def get_piece(self, piece_type, input_color): for loc in self: piece = self.piece_at_square(loc) if not self.is_square_empty(loc) and \ isinstance(piece, piece_type) and \ piece.color == input_color: return loc ra...
Gets location of a piece on the board given the type and color. :type: piece_type: Piece :type: input_color: Color :rtype: Location
353,681
def new_rsa_key(key_size=2048, kid=, use=, public_exponent=65537): _key = rsa.generate_private_key(public_exponent=public_exponent, key_size=key_size, backend=default_backend()) _rk = RSAKey(priv_key=_key, use=use, kid=kid) if no...
Creates a new RSA key pair and wraps it in a :py:class:`cryptojwt.jwk.rsa.RSAKey` instance :param key_size: The size of the key :param kid: The key ID :param use: What the is supposed to be used for. 2 choices 'sig'/'enc' :param public_exponent: The value of the public exponent. :return: A :py:...
353,682
def register_callback(self, sensorid, callback, user_data=None): if sensorid not in self._registry: self._registry[sensorid] = list() self._registry[sensorid].append((callback, user_data))
Register a callback for the specified sensor id.
353,683
def get_channel(self): c = pygame.mixer.find_channel(not self.dynamic) while c is None: self.channels += 1 pygame.mixer.set_num_channels(self.channels) c = pygame.mixer.find_channel() return c
Used internally when playing sounds.
353,684
def _distance_last_evaluations(self): if self.X.shape[0] < 2: return np.inf return np.sqrt(np.sum((self.X[-1, :] - self.X[-2, :]) ** 2))
Computes the distance between the last two evaluations.
353,685
def AddFilesWithUnknownHashes( client_path_blob_refs, use_external_stores = True ): hash_id_blob_refs = dict() client_path_hash_id = dict() metadatas = dict() all_client_path_blob_refs = list() for client_path, blob_refs in iteritems(client_path_blob_refs): if len(blob_refs...
Adds new files consisting of given blob references. Args: client_path_blob_refs: A dictionary mapping `db.ClientPath` instances to lists of blob references. use_external_stores: A flag indicating if the files should also be added to external file stores. Returns: A dictionary mapping `db.C...
353,686
def _verify_config_dict(self, valid, config, dev_os, key_path=None): if not key_path: key_path = [] for key, value in valid.items(): self._verify_config_key(key, value, valid, config, dev_os, key_path)
Verify if the config dict is valid.
353,687
def tmdb_movies(api_key, id_tmdb, language="en-US", cache=True): try: url = "https://api.themoviedb.org/3/movie/%d" % int(id_tmdb) except ValueError: raise MapiProviderException("id_tmdb must be numeric") parameters = {"api_key": api_key, "language": language} status, content = _req...
Lookup a movie item using The Movie Database Online docs: developers.themoviedb.org/3/movies
353,688
def get_lambda_function(self, function_name): response = self.lambda_client.get_function( FunctionName=function_name) return response[][]
Returns the lambda function ARN, given a name This requires the "lambda:GetFunction" role.
353,689
def update(self, byte_arr): if byte_arr: self.value = self.calculate(byte_arr, self.value)
Read bytes and update the CRC computed.
353,690
def suggestions(self, word): suggestions = set(self._misspelling_dict.get(word, [])).union( set(self._misspelling_dict.get(word.lower(), []))) return sorted([same_case(source=word, destination=w) for w in suggestions])
Returns a list of suggestions for a misspelled word. Args: word: The word to check. Returns: List of zero or more suggested replacements for word.
353,691
def command_help_long(self): indent = " " * 2 help = "Command must be one of:\n" for action_name in self.parser.valid_commands: help += "%s%-10s %-70s\n" % (indent, action_name, self.parser.commands[action_name].desc_short.capitalize()) help += %s help COMMAND\ % self.parser.prog return ...
Return command help for use in global parser usage string @TODO update to support self.current_indent from formatter
353,692
def agp(args): p = OptionParser(agp.__doc__) p.set_outfile() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) odir, contigsfasta = args fwagp = must_open(opts.outfile, ) orderingfiles = natsorted(iglob(odir, "*.ordering")) sizes = Sizes(conti...
%prog agp main_results/ contigs.fasta Generate AGP file based on LACHESIS output.
353,693
def srotate(self): heavy = self.balance > 0 light = not heavy save = self[heavy] self[heavy] = save[light] save[light] = self.rotate() prom...
Single rotation. Assumes that balance is +-2.
353,694
def _set_active_on(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=active_on.active_on, is_container=, presence=False, yang_name="active-on", rest_name="active-on", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_path...
Setter method for active_on, mapped from YANG variable /overlay_policy_map_state/active_on (container) If this variable is read-only (config: false) in the source YANG file, then _set_active_on is considered as a private method. Backends looking to populate this variable should do so via calling thisObj...
353,695
def upload_media(self, media_type, media_file, extension=): if six.PY2: return self._upload_media_py2(media_type, media_file, extension) else: return self._upload_media_py3(media_type, media_file, extension)
上传多媒体文件 详情请参考 http://mp.weixin.qq.com/wiki/10/78b15308b053286e2a66b33f0f0f5fb6.html :param media_type: 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb) :param media_file: 要上传的文件,一个 File object 或 StringIO object :param extension: 如果 media_file 传入的为 StringIO object,那么必须传入 extension 显示指明该...
353,696
def fetch_backpressure(self, cluster, metric, topology, component, instance, \ timerange, is_max, environ=None): pass
:param cluster: :param metric: :param topology: :param component: :param instance: :param timerange: :param is_max: :param environ: :return:
353,697
def add_ignore(self, depend): try: self._add_child(self.ignore, self.ignore_set, depend) except TypeError as e: e = e.args[0] if SCons.Util.is_List(e): s = list(map(str, e)) else: s = str(e) raise SCons....
Adds dependencies to ignore.
353,698
def last_date_in_output_for_sid(self, sid): sizes_path = "{0}/close/meta/sizes".format(self.sidpath(sid)) if not os.path.exists(sizes_path): return pd.NaT with open(sizes_path, mode=) as f: sizes = f.read() data = json.loads(sizes) ...
Parameters ---------- sid : int Asset identifier. Returns ------- out : pd.Timestamp The midnight of the last date written in to the output for the given sid.
353,699
def add_time_event(self, time_event): if isinstance(time_event, time_event_module.TimeEvent): self.time_events.append(time_event) else: raise TypeError("Type Error: received {}, but requires TimeEvent.". format(type(time_event).__name__))
Add a TimeEvent. :type time_event: :class: `~opencensus.trace.time_event.TimeEvent` :param time_event: A TimeEvent object.