code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def patternVector(self, vector): if not self.patterned: return vector if type(vector) == int: if self.getWord(vector) != '': return self.getWord(vector) else: return vector elif type(vector) == float: if self.getWord(vector) != ...
Replaces vector with patterns. Used for loading inputs or targets from a file and still preserving patterns.
def _server_property(self, attr_name): server = self._topology.select_server( writable_server_selector) return getattr(server.description, attr_name)
An attribute of the current server's description. If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available. Not threadsafe if used multiple times in a single method, since the server may cha...
def _parse_response(self, respond): mobj = self._max_qubit_error_re.match(respond.text) if mobj: raise RegisterSizeError( 'device register size must be <= {}'.format(mobj.group(1))) return True
parse text of response for HTTP errors This parses the text of the response to decide whether to retry request or raise exception. At the moment this only detects an exception condition. Args: respond (Response): requests.Response object Returns: bool: ...
def resetScale(self): self.img.scale(1./self.imgScale[0], 1./self.imgScale[1]) self.imgScale = (1.,1.)
Resets the scale on this image. Correctly aligns time scale, undoes manual scaling
def find(self, start_address, end_address, byte_depth=20, instrs_depth=2): self._max_bytes = byte_depth self._instrs_depth = instrs_depth if self._architecture == ARCH_X86: candidates = self._find_x86_candidates(start_address, end_address) elif self._architecture == ARCH_ARM:...
Find gadgets.
def _default_headers(self): headers = { "Authorization": 'Bearer {}'.format(self.api_key), "User-agent": self.useragent, "Accept": 'application/json' } if self.impersonate_subuser: headers['On-Behalf-Of'] = self.impersonate_subuser ...
Set the default header for a Twilio SendGrid v3 API call
def ordc(item, inset): assert isinstance(inset, stypes.SpiceCell) assert inset.is_char() assert isinstance(item, str) item = stypes.stringToCharP(item) return libspice.ordc_c(item, ctypes.byref(inset))
The function returns the ordinal position of any given item in a character set. If the item does not appear in the set, the function returns -1. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ordc_c.html :param item: An item to locate within a set. :type item: str :param inset: A set...
def escape_query(query): return query.replace("\\", r"\5C").replace("*", r"\2A").replace("(", r"\28").replace(")", r"\29")
Escapes certain filter characters from an LDAP query.
def _lxml_el_to_data(lxml_el, ns, nsmap, snake=True): tag_name = _to_colon_ns(lxml_el.tag, default_ns=ns, nsmap=nsmap) ret = [tag_name] attributes = _get_el_attributes(lxml_el, ns=ns, nsmap=nsmap) if attributes: ret.append(attributes) for sub_el in lxml_el: ret.append(_lxml_el_to_dat...
Convert an ``lxml._Element`` instance to a Python tuple.
def register_id(self, id_string): try: prefix, count = id_string.rsplit("_", 1) count = int(count) except ValueError: pass else: if prefix == self.prefix: self.counter = max(count, self.counter)
Register a manually assigned id as used, to avoid collisions.
def facts(self): fact = lib.EnvGetNextFact(self._env, ffi.NULL) while fact != ffi.NULL: yield new_fact(self._env, fact) fact = lib.EnvGetNextFact(self._env, fact)
Iterate over the asserted Facts.
def columns_in_filters(filters): if not filters: return [] if not isinstance(filters, str): filters = ' '.join(filters) columns = [] reserved = {'and', 'or', 'in', 'not'} for toknum, tokval, _, _, _ in generate_tokens(StringIO(filters).readline): if toknum == NAME and tokval ...
Returns a list of the columns used in a set of query filters. Parameters ---------- filters : list of str or str List of the filters as passed passed to ``apply_filter_query``. Returns ------- columns : list of str List of all the strings mentioned in the filters.
def yml_fnc(fname, *args, **options): key = "ac_safe" fnc = getattr(yaml, r"safe_" + fname if options.get(key) else fname) return fnc(*args, **common.filter_from_options(key, options))
An wrapper of yaml.safe_load, yaml.load, yaml.safe_dump and yaml.dump. :param fname: "load" or "dump", not checked but it should be OK. see also :func:`yml_load` and :func:`yml_dump` :param args: [stream] for load or [cnf, stream] for dump :param options: keyword args may contain "ac_safe" ...
def set_attr_value(self, key, attr, value): idx = self._keys[key] self._attrs[attr][idx].set(value)
set the value of a given attribute for a given key
def _(obj): tz_offset = obj.utcoffset() if not tz_offset or tz_offset == UTC_ZERO: iso_datetime = obj.strftime('%Y-%m-%dT%H:%M:%S.%fZ') else: iso_datetime = obj.isoformat() return iso_datetime
ISO 8601 format. Interprets naive datetime as UTC with zulu suffix.
def _check_panel(self, length): n = len(self.index) if divmod(n, length)[1] != 0: raise ValueError("Panel length '%g' must evenly divide length of series '%g'" % (length, n)) if n == length: raise ValueError("Panel length '%g' cannot be length...
Check that given fixed panel length evenly divides index. Parameters ---------- length : int Fixed length with which to subdivide index
def run_alias(): mode = Path(sys.argv[0]).stem help = True if len(sys.argv) <= 1 else False if mode == 'lcc': sys.argv.insert(1, 'c') elif mode == 'lpython': sys.argv.insert(1, 'python') sys.argv.insert(1, 'run') if help: sys.argv.append('--help') main.main(prog_name=...
Quick aliases for run command.
def knob_subgroup(self, cutoff=7.0): if cutoff > self.cutoff: raise ValueError("cutoff supplied ({0}) cannot be greater than self.cutoff ({1})".format(cutoff, self.cutoff)) return KnobGroup(m...
KnobGroup where all KnobsIntoHoles have max_kh_distance <= cutoff.
def _get_factor(self, belief_prop, evidence): final_factor = factor_product(*belief_prop.junction_tree.get_factors()) if evidence: for var in evidence: if var in final_factor.scope(): final_factor.reduce([(var, evidence[var])]) return final_factor
Extracts the required factor from the junction tree. Parameters: ---------- belief_prop: Belief Propagation Belief Propagation which needs to be updated. evidence: dict a dict key, value pair as {var: state_of_var_observed}
def building(shape=None, gray=False): name = 'cms.mat' url = URL_CAM + name dct = get_data(name, subset=DATA_SUBSET, url=url) im = np.rot90(dct['im'], k=3) return convert(im, shape, gray=gray)
Photo of the Centre for Mathematical Sciences in Cambridge. Returns ------- An image with the following properties: image type: color (or gray scales if `gray=True`) size: [442, 331] (if not specified by `size`) scale: [0, 1] type: float64
def cache_key(self, repo: str, branch: str, task: Task, git_repo: Repo) -> str: return "{repo}_{branch}_{hash}_{task}".format(repo=self.repo_id(repo), branch=branch, hash=self.current_git_hash(repo, branc...
Returns the key used for storing results in cache.
def humanize_filesize(filesize: int) -> Tuple[str, str]: for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: if filesize < 1024.0: return '{:3.1f}'.format(filesize), unit+'B' filesize /= 1024.0
Return human readable pair of size and unit from the given filesize in bytes.
def contents_match(self, path): checksum = file_hash(path) kv = unitdata.kv() stored_checksum = kv.get('hardening:%s' % path) if not stored_checksum: log('Checksum for %s has not been calculated.' % path, level=DEBUG) return False elif stored_checksum != c...
Determines if the file content is the same. This is determined by comparing hashsum of the file contents and the saved hashsum. If there is no hashsum, then the content cannot be sure to be the same so treat them as if they are not the same. Otherwise, return True if the hashsums are th...
def datasets(self, libref: str = '') -> str: code = "proc datasets" if libref: code += " dd=" + libref code += "; quit;" if self.nosub: print(code) else: if self.results.lower() == 'html': ll = self._io.submit(code, "html") ...
This method is used to query a libref. The results show information about the libref including members. :param libref: the libref to query :return:
def _decode_linode_plan_label(label): sizes = avail_sizes() if label not in sizes: if 'GB' in label: raise SaltCloudException( 'Invalid Linode plan ({}) specified - call avail_sizes() for all available options'.format(label) ) else: plan = labe...
Attempts to decode a user-supplied Linode plan label into the format in Linode API output label The label, or name, of the plan to decode. Example: `Linode 2048` will decode to `Linode 2GB`
def sort_dict(self, data, key): return sorted(data, key=itemgetter(key)) if data else []
Sort a list of dictionaries by dictionary key
def allow_exception(self, exc_class): name = exc_class.__name__ self._allowed_exceptions[name] = exc_class
Allow raising this class of exceptions from commands. When a command fails on the server side due to an exception, by default it is turned into a string and raised on the client side as an ExternalError. The original class name is sent but ignored. If you would like to instead raise a...
def battlecry_requires_target(self): if self.has_combo and self.controller.combo: if PlayReq.REQ_TARGET_FOR_COMBO in self.requirements: return True for req in TARGETING_PREREQUISITES: if req in self.requirements: return True return False
True if the play action of the card requires a target
def signed_int_to_unsigned_hex(signed_int: int) -> str: hex_string = hex(struct.unpack('Q', struct.pack('q', signed_int))[0])[2:] if hex_string.endswith('L'): return hex_string[:-1] return hex_string
Converts a signed int value to a 64-bit hex string. Examples: 1662740067609015813 => '17133d482ba4f605' -5270423489115668655 => 'b6dbb1c2b362bf51' :param signed_int: an int to convert :returns: unsigned hex string
def keys(cls, name, hash_key, range_key=None, throughput=None): return cls(cls.KEYS, name, hash_key, range_key, throughput=throughput)
Create an index that projects only key attributes
def get_property_dict(entity_proto): return dict((p.key, p.value) for p in entity_proto.property)
Convert datastore.Entity to a dict of property name -> datastore.Value. Args: entity_proto: datastore.Entity proto message. Usage: >>> get_property_dict(entity_proto) {'foo': {string_value='a'}, 'bar': {integer_value=2}} Returns: dict of entity properties.
def unregister_event(self, event_name, handler): try: self._event_handlers[event_name].remove(handler) except ValueError: pass
Unregister a callable that will be called when event is raised. :param event_name: The name of the event (see knack.events for in-built events) :type event_name: str :param handler: The callback that was used to register the event :type handler: function
def hashes(self): for url_variant in self.url_permutations(self.canonical): url_hash = self.digest(url_variant) yield url_hash
Hashes of all possible permutations of the URL in canonical form
def get_block_by_hash(self, block_hash: Hash32) -> BaseBlock: validate_word(block_hash, title="Block Hash") block_header = self.get_block_header_by_hash(block_hash) return self.get_block_by_header(block_header)
Returns the requested block as specified by block hash.
def remote_file(self, branch='master', filename=''): LOG.info('Retrieving "%s" from "%s".', filename, self.git_short) file_contents = '' try: file_blob = self.project.files.get(file_path=filename, ref=branch) except gitlab.exceptions.GitlabGetError: file_blob = No...
Read the remote file on Git Server. Args: branch (str): Git Branch to find file. filename (str): Name of file to retrieve relative to root of repository. Returns: str: Contents of remote file. Raises: FileNotFoundError: Requested...
def get_instantiated_service(self, name): if name not in self.instantiated_services: raise UninstantiatedServiceException return self.instantiated_services[name]
Get instantiated service by name
def register_area(self, area_code, index, userdata): size = ctypes.sizeof(userdata) logger.info("registering area %s, index %s, size %s" % (area_code, index, size)) size = ctypes.sizeof(userdata) return self.library.Srv_Regi...
Shares a memory area with the server. That memory block will be visible by the clients.
def Search(self, text, wholewords=0, titleonly=0): if text and text != '' and self.file: return extra.search(self.file, text, wholewords, titleonly) else: return None
Performs full-text search on the archive. The first parameter is the word to look for, the second indicates if the search should be for whole words only, and the third parameter indicates if the search should be restricted to page titles. This method will return a tuple, the firs...
def stop(self): if self._died.ready(): _log.debug('already stopped %s', self) return if self._being_killed: _log.debug('already being killed %s', self) try: self._died.wait() except: pass return ...
Stop the container gracefully. First all entrypoints are asked to ``stop()``. This ensures that no new worker threads are started. It is the extensions' responsibility to gracefully shut down when ``stop()`` is called on them and only return when they have stopped. After all e...
def add_tunnel_port(self, name, tunnel_type, remote_ip, local_ip=None, key=None, ofport=None): options = 'remote_ip=%(remote_ip)s' % locals() if key: options += ',key=%(key)s' % locals() if local_ip: options += ',local_ip=%(local_ip)s' % locals() ...
Creates a tunnel port. :param name: Port name to be created :param tunnel_type: Type of tunnel (gre or vxlan) :param remote_ip: Remote IP address of tunnel :param local_ip: Local IP address of tunnel :param key: Key of GRE or VNI of VxLAN :param ofport: Requested OpenFlo...
def disable(self, retain_port=False): self.update_server(disabled=True) if retain_port: return self.update_device(disabled=True) if self.conf.dhcp_delete_namespaces and self.network.namespace: ns_ip = ip_lib.IPWrapper(self.root_helper, ...
Teardown DHCP. Disable DHCP for this network by updating the remote server and then destroying any local device and namespace.
def getStreamNetworkAsWkt(self, session, withNodes=True): wkt_list = [] for link in self.streamLinks: wkt_link = link.getAsWkt(session) if wkt_link: wkt_list.append(wkt_link) if withNodes: for node in link.nodes: wkt...
Retrieve the stream network geometry in Well Known Text format. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database withNodes (bool, optional): Include nodes. Defaults to False. Returns: str: Well Known ...
def filter_product_filename_generator(obs_info,nn): proposal_id = obs_info[0] visit_id = obs_info[1] instrument = obs_info[2] detector = obs_info[3] filter = obs_info[4] product_filename_dict = {} product_filename_dict["image"] = "hst_{}_{}_{}_{}_{}.fits".format(proposal_id,visit_id,instrume...
Generate image and sourcelist filenames for filter products Parameters ---------- obs_info : list list of items that will be used to generate the filenames: proposal_id, visit_id, instrument, detector, and filter nn : string the single-exposure image number (NOTE: only used in ...
def iscsi_resource(self): return iscsi.ISCSIResource( self._conn, utils.get_subresource_path_by( self, ["Oem", "Hpe", "Links", "iScsi"]), redfish_version=self.redfish_version)
Property to provide reference to bios iscsi resource instance It is calculated once when the first time it is queried. On refresh, this property gets reset.
def get_logger(self, name="deployment-logger", level=logging.DEBUG): log = logging logger = log.getLogger(name) fmt = log.Formatter("%(asctime)s %(funcName)s " "%(levelname)s: %(message)s") handler = log.StreamHandler(stream=sys.stdout) handler.setLeve...
Get a logger object that will log to stdout.
def ascent(self): total_ascent = 0.0 altitude_data = self.altitude_points() for i in range(len(altitude_data) - 1): diff = altitude_data[i+1] - altitude_data[i] if diff > 0.0: total_ascent += diff return total_ascent
Returns ascent of workout in meters
def _load(self): if self.is_sw or self.platform_name == 'EOS-Aqua': scale = 0.001 else: scale = 1.0 detector = read_modis_response(self.requested_band_filename, scale) self.rsr = detector if self._sort: self.sort()
Load the MODIS RSR data for the band requested
def _create_body(self, name, flavor=None, volume=None, databases=None, users=None, version=None, type=None): if flavor is None: flavor = 1 flavor_ref = self.api._get_flavor_ref(flavor) if volume is None: volume = 1 if databases is None: dat...
Used to create the dict required to create a Cloud Database instance.
def renew_local_branch(branch, start_point, remote=False): if branch in branches(): checkout(start_point) delete(branch, force=True, remote=remote) result = new_local_branch(branch, start_point) if remote: publish(branch) return result
Make a new local branch from that start_point start_point is a git "commit-ish", e.g branch, tag, commit If a local branch already exists it is removed If remote is true then push the new branch to origin
def example_method(self, i3s_output_list, i3s_config): full_text = self.format.format(output='example') response = { 'cached_until': time() + self.cache_timeout, 'full_text': full_text } return response
This method will return an empty text message so it will NOT be displayed on your i3bar. If you want something displayed you should write something in the 'full_text' key of your response. See the i3bar protocol spec for more information: http://i3wm.org/docs/i3bar-protocol.htm...
def get_structure_with_nodes(self): new_s = Structure.from_sites(self.structure) for v in self.vnodes: new_s.append("X", v.frac_coords) return new_s
Get the modified structure with the voronoi nodes inserted. The species is set as a DummySpecie X.
def create(self, article, attachment, inline=False, file_name=None, content_type=None): return HelpdeskAttachmentRequest(self).post(self.endpoint.create, article=article, attachments=attachment, ...
This function creates attachment attached to article. :param article: Numeric article id or :class:`Article` object. :param attachment: File object or os path to file :param inline: If true, the attached file is shown in the dedicated admin UI for inline attachments and its url can ...
def get_repo_revision(): repopath = _findrepo() if not repopath: return '' try: import mercurial.hg, mercurial.ui, mercurial.scmutil from mercurial.node import short as hexfunc except ImportError: pass else: ui = mercurial.ui.ui() repo = mercurial.hg.r...
Returns mercurial revision string somelike `hg identify` does. Format is rev1:short-id1+;rev2:short-id2+ Returns an empty string if anything goes wrong, such as missing .hg files or an unexpected format of internal HG files or no mercurial repository found.
def singledispatch(*, nargs=None, nouts=None, ndefs=None): def wrapper(f): return wraps(f)(SingleDispatchFunction(f, nargs=nargs, nouts=nouts, ndefs=ndefs)) return wrapper
singledispatch decorate of both functools.singledispatch and func
def rmSelf(f): def new_f(*args, **kwargs): newArgs = args[1:] result = f(*newArgs, **kwargs) return result return new_f
f -> function. Decorator, removes first argument from f parameters.
def parse_summary(content, reference_id=None): summary = None m = _END_SUMMARY_PATTERN.search(content) if m: end_of_summary = m.start() m = _START_SUMMARY_PATTERN.search(content, 0, end_of_summary) or _ALTERNATIVE_START_SUMMARY_PATTERN.search(content, 0, end_of_summary) if m: ...
\ Extracts the summary from the `content` of the cable. If no summary can be found, ``None`` is returned. `content` The content of the cable. `reference_id` The reference identifier of the cable.
def attach_framebuffer(self, screen_id, framebuffer): if not isinstance(screen_id, baseinteger): raise TypeError("screen_id can only be an instance of type baseinteger") if not isinstance(framebuffer, IFramebuffer): raise TypeError("framebuffer can only be an instance of type IFr...
Sets the graphics update target for a screen. in screen_id of type int in framebuffer of type :class:`IFramebuffer` return id_p of type str
def create_archiver(typename): archiver = _ARCHIVER_BY_TYPE.get(typename) if not archiver: raise ValueError('No archiver registered for {!r}'.format(typename)) return archiver
Returns Archivers in common configurations. :API: public The typename must correspond to one of the following: 'tar' Returns a tar archiver that applies no compression and emits .tar files. 'tgz' Returns a tar archiver that applies gzip compression and emits .tar.gz files. 'tbz2' Returns a tar archiver...
def resume_writing(self): if not self._can_send.is_set(): self._can_send.set() self.transport.resume_reading()
Transport calls when the send buffer has room.
def patch(self, request, format=None): data = request.data.copy() try: ct = ChatType.objects.get(id=data.pop("chat_type")) data["chat_type"] = ct except ChatType.DoesNotExist: return typeNotFound404 if not self.is_path_unique( data["id"], d...
Update an existing Channel
def take_profit_replace(self, accountID, orderID, **kwargs): return self.replace( accountID, orderID, order=TakeProfitOrderRequest(**kwargs) )
Shortcut to replace a pending Take Profit Order in an Account Args: accountID : The ID of the Account orderID : The ID of the Take Profit Order to replace kwargs : The arguments to create a TakeProfitOrderRequest Returns: v20.response.Response containing...
def parse_file(file): lines = [] for line in file: line = line.rstrip('\n') if line == '%%': yield from parse_item(lines) lines.clear() elif line.startswith(' '): lines[-1] += line[1:] else: lines.append(line) yield from parse_...
Take an open file containing the IANA subtag registry, and yield a dictionary of information for each subtag it describes.
def lookup(alias): if alias in matchers: return matchers[alias] else: norm = normalize(alias) if norm in normalized: alias = normalized[norm] return matchers[alias] if -1 != alias.find('_'): norm = normalize(alias).replace('_', '') return looku...
Tries to find a matcher callable associated to the given alias. If an exact match does not exists it will try normalizing it and even removing underscores to find one.
def assign_ranks_to_grid(grid, ranks): assignments = deepcopy(grid) ranks["0b0"] = 0 ranks["-0b1"] = -1 for i in range(len(grid)): for j in range(len(grid[i])): if type(grid[i][j]) is list: for k in range(len(grid[i][j])): assignments[i][j][k] = ra...
Takes a 2D array of binary numbers represented as strings and a dictionary mapping binary strings to integers representing the rank of the cluster they belong to, and returns a grid in which each binary number has been replaced with the rank of its cluster.
def reset(self): self.v = self.c self.u = self.b * self.v self.fired = 0.0 self.current = self.bias
Resets all state variables.
def init_app(self, app, path='templates.yaml'): if self._route is None: raise TypeError("route is a required argument when app is not None") self.app = app app.ask = self app.add_url_rule(self._route, view_func=self._flask_view_func, methods=['POST']) app.jinja_loader...
Initializes Ask app by setting configuration variables, loading templates, and maps Ask route to a flask view. The Ask instance is given the following configuration variables by calling on Flask's configuration: `ASK_APPLICATION_ID`: Turn on application ID verification by setting this var...
def extended_capabilities(self): buf = (ctypes.c_uint8 * 32)() self._dll.JLINKARM_GetEmuCapsEx(buf, 32) return list(buf)
Gets the capabilities of the connected emulator as a list. Args: self (JLink): the ``JLink`` instance Returns: List of 32 integers which define the extended capabilities based on their value and index within the list.
def _do_lumping(self): right_eigenvectors = self.right_eigenvectors_[:, :self.n_macrostates] index = index_search(right_eigenvectors) A = right_eigenvectors[index, :] A = inv(A) A = fill_A(A, right_eigenvectors) if self.do_minimization: A = self._optimize_A(A)...
Perform PCCA+ algorithm by optimizing transformation matrix A. Creates the following member variables: ------- A : ndarray The transformation matrix. chi : ndarray The membership matrix microstate_mapping : ndarray Mapping from microstates to ...
def as_stream(self): if not self.singular: raise ArgumentError("Attempted to convert a non-singular selector to a data stream, it matches multiple", selector=self) return DataStream(self.match_type, self.match_id, self.match_spec == DataStreamSelector.MatchSystemOnly)
Convert this selector to a DataStream. This function will only work if this is a singular selector that matches exactly one DataStream.
def oracle_approximating(self): X = np.nan_to_num(self.X.values) shrunk_cov, self.delta = covariance.oas(X) return self.format_and_annualise(shrunk_cov)
Calculate the Oracle Approximating Shrinkage estimate :return: shrunk sample covariance matrix :rtype: np.ndarray
def create_supercut_in_batches(composition, outputfile, padding): total_clips = len(composition) start_index = 0 end_index = BATCH_SIZE batch_comp = [] while start_index < total_clips: filename = outputfile + '.tmp' + str(start_index) + '.mp4' try: create_supercut(composi...
Create & concatenate video clips in groups of size BATCH_SIZE and output finished video file to output directory.
def updated_dimensions(self): return [("ntime", args.ntime), ("nchan", args.nchan), ("na", args.na), ("npsrc", len(lm_coords))]
Inform montblanc about dimension sizes
def string_to_response(content_type): def outer_wrapper(req_function): @wraps(req_function) def newreq(request, *args, **kwargs): try: outp = req_function(request, *args, **kwargs) if issubclass(outp.__class__, HttpResponse): response =...
Wrap a view-like function that returns a string and marshalls it into an HttpResponse with the given Content-Type If the view raises an HttpBadRequestException, it will be converted into an HttpResponseBadRequest.
def handle_update(self, args): component = int(args[0]) action = int(args[1]) params = [int(x) for x in args[2:]] _LOGGER.debug("Updating %d(%s): c=%d a=%d params=%s" % ( self._integration_id, self._name, component, action, params)) if component in self._components: return self._compon...
The callback invoked by the main event loop if there's an event from this keypad.
def all(cls, client, **kwargs): max_date = kwargs['max_date'] if 'max_date' in kwargs else None max_fetches = \ kwargs['max_fetches'] if 'max_fetches' in kwargs else None url = 'https://api.robinhood.com/options/positions/' params = {} data = client.get(url, params=pa...
fetch all option positions
def get_redshift(self, dist): dist, input_is_array = ensurearray(dist) try: zs = self.nearby_d2z(dist) except TypeError: self.setup_interpolant() zs = self.nearby_d2z(dist) replacemask = numpy.isnan(zs) if replacemask.any(): zs[repl...
Returns the redshift for the given distance.
def phase_type(self, value): self._params.phase_type = value self._overwrite_lock.disable()
compresses the waveform horizontally; one of ``"normal"``, ``"resync"``, ``"resync2"``
def product(target, prop1, prop2, **kwargs): r value = target[prop1]*target[prop2] for item in kwargs.values(): value *= target[item] return value
r""" Calculates the product of multiple property values Parameters ---------- target : OpenPNM Object The object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary properties. prop1 : string ...
def getPeers(self, offset=0, limit=1000): select = models.Peer.select().order_by( models.Peer.url).limit(limit).offset(offset) return [peers.Peer(p.url, record=p) for p in select]
Get the list of peers using an SQL offset and limit. Returns a list of peer datamodel objects in a list.
def prepare_sort_key(self): if isinstance(self.convert_type, str): try: app_name, model_name = self.convert_type.split('.') except ValueError: raise ImproperlyConfigured('"{}" is not a valid converter type. String-based converter types must be specified in...
Triggered by view_function._sort_converters when our sort key should be created. This can't be called in the constructor because Django models might not be ready yet.
def list_streams(self, types=[], inactive=False): req_hook = 'pod/v1/streams/list' json_query = { "streamTypes": types, "includeInactiveStreams": inactive } req_args = json.dumps(json_query) status_code, response = self._...
list user streams
def _evaluate_usecols(usecols, names): if callable(usecols): return {i for i, name in enumerate(names) if usecols(name)} return usecols
Check whether or not the 'usecols' parameter is a callable. If so, enumerates the 'names' parameter and returns a set of indices for each entry in 'names' that evaluates to True. If not a callable, returns 'usecols'.
def to_flat(coord): if coord is None: return go.N * go.N return go.N * coord[0] + coord[1]
Converts from a Minigo coordinate to a flattened coordinate.
def remove(path): if not os.path.exists(path): return if os.path.isdir(path): return shutil.rmtree(path) if os.path.isfile(path): return os.remove(path)
Wrapper that switches between os.remove and shutil.rmtree depending on whether the provided path is a file or directory.
def as_minimized(values: List[float], maximized: List[bool]) -> List[float]: return [v * -1. if m else v for v, m in zip(values, maximized)]
Return vector values as minimized
def load_data(): boston = load_boston() X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=99, test_size=0.25) ss_X = StandardScaler() ss_y = StandardScaler() X_train = ss_X.fit_transform(X_train) X_test = ss_X.transform(X_test) y_train = ss_y.fit_tr...
Load dataset, use boston dataset
def _should_ignore(self, path): for ignore in self.options.ignores: if fnmatch.fnmatch(path, ignore): return True return False
Return True iff path should be ignored.
def preview(self, obj, request=None): source = self.get_thumbnail_source(obj) if source: try: from easy_thumbnails.files import get_thumbnailer except ImportError: logger.warning( _( '`easy_thumbnails` is...
Generate the HTML to display for the image. :param obj: An object with a thumbnail_field defined. :return: HTML for image display.
def _CreateShapePointFolder(self, shapes_folder, shape): folder_name = shape.shape_id + ' Shape Points' folder = self._CreateFolder(shapes_folder, folder_name, visible=False) for (index, (lat, lon, dist)) in enumerate(shape.points): placemark = self._CreatePlacemark(folder, str(index+1)) point =...
Create a KML Folder containing all the shape points in a shape. The folder contains placemarks for each shapepoint. Args: shapes_folder: A KML Shape Folder ElementTree.Element instance shape: The shape to plot. Returns: The Folder ElementTree.Element instance or None.
def any_match(self, urls): return any(urlparse(u).hostname in self for u in urls)
Check if any of the given URLs has a matching host. :param urls: an iterable containing URLs :returns: True if any host has a listed match :raises InvalidURLError: if there are any invalid URLs in the sequence
def QA_fetch_get_sh_margin(date): if date in trade_date_sse: data= pd.read_excel(_sh_url.format(QA_util_date_str2int (date)), 1).assign(date=date).assign(sse='sh') data.columns=['code','name','leveraged_balance','leveraged_buyout','leveraged_p...
return shanghai margin data Arguments: date {str YYYY-MM-DD} -- date format Returns: pandas.DataFrame -- res for margin data
def list_resources(self, device_id): api = self._get_api(mds.EndpointsApi) return [Resource(r) for r in api.get_endpoint_resources(device_id)]
List all resources registered to a connected device. .. code-block:: python >>> for r in api.list_resources(device_id): print(r.name, r.observable, r.uri) None,True,/3/0/1 Update,False,/5/0/3 ... :param str device_id: The ID of the d...
def file_handler(self, handler_type, path, prefixed_path, source_storage): if self.faster: if prefixed_path not in self.found_files: self.found_files[prefixed_path] = (source_storage, path) self.task_queue.put({ 'handler_type': handler_type, ...
Create a dict with all kwargs of the `copy_file` or `link_file` method of the super class and add it to the queue for later processing.
def login_form_factory(Form, app): class LoginForm(Form): def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.remember.data = False return LoginForm
Return extended login form.
def purge(self): while not self.stopped.isSet(): self.stopped.wait(timeout=defines.EXCHANGE_LIFETIME) self._messageLayer.purge()
Clean old transactions
def delete(self): self.bucket.size -= self.size Part.query_by_multipart(self).delete() self.query.filter_by(upload_id=self.upload_id).delete()
Delete a multipart object.
def process_xml(xml_str): try: tree = ET.XML(xml_str, parser=UTB()) except ET.ParseError as e: logger.error('Could not parse XML string') logger.error(e) return None sp = _process_elementtree(tree) return sp
Return processor with Statements extracted from a Sparser XML. Parameters ---------- xml_str : str The XML string obtained by reading content with Sparser, using the 'xml' output mode. Returns ------- sp : SparserXMLProcessor A SparserXMLProcessor which has extracted St...
async def deactivate(cls, access_key: str) -> dict: q = 'mutation($access_key: String!, $input: ModifyKeyPairInput!) {' + \ ' modify_keypair(access_key: $access_key, props: $input) {' \ ' ok msg' \ ' }' \ '}' variables = { 'access_key': ac...
Deactivates this keypair. Deactivated keypairs cannot make any API requests unless activated again by an administrator. You need an admin privilege for this operation.
def tween(self, t): if t is None: return None if self.method in self.method_to_tween: return self.method_to_tween[self.method](t) elif self.method in self.method_1param: return self.method_1param[self.method](t, self.param1) elif self.method in self.me...
t is number between 0 and 1 to indicate how far the tween has progressed
def _get_prepped_model_field(model_obj, field): field = model_obj._meta.get_field(field) value = field.get_db_prep_save(getattr(model_obj, field.attname), connection) return value
Gets the value of a field of a model obj that is prepared for the db.