Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
6,700
def markdown(iterable, renderer=HTMLRenderer): with renderer() as renderer: return renderer.render(Document(iterable))
Output HTML with default settings. Enables inline and block-level HTML tags.
6,701
def push_account_task(obj_id): lock_id = "%s-push-account-%s" % (settings.ENV_PREFIX, obj_id) acquire_lock = lambda: cache.add(lock_id, "true", LOCK_EXPIRE) release_lock = lambda: cache.delete(lock_id) if acquire_lock(): UserModel = get_user_model() try: upload_inter...
Async: push_account_task.delay(Account.id)
6,702
def get_first(): client = po.connect() all_droplets = client.droplets.list() id = all_droplets[0][] return client.droplets.get(id)
return first droplet
6,703
def _get_hosted_zone_limit(self, limit_type, hosted_zone_id): result = self.conn.get_hosted_zone_limit( Type=limit_type, HostedZoneId=hosted_zone_id ) return result
Return a hosted zone limit [recordsets|vpc_associations] :rtype: dict
6,704
def fetch_token(self, client_secret, code, context, scope, redirect_uri, token_url=): res = self.post(token_url, {: self.client_id, : client_secret, : code, : context, ...
Fetches a token from given token_url, using given parameters, and sets up session headers for future requests. redirect_uri should be the same as your callback URL. code, context, and scope should be passed as parameters to your callback URL on app installation. Raises HttpException on ...
6,705
def search(self, fields=None, query=None, filters=None): results = self.search_json(fields, query)[] results = self.search_normalize(results) entities = [ type(self)(self._server_config, **result) ...
Search for entities. At its simplest, this method searches for all entities of a given kind. For example, to ask for all :class:`nailgun.entities.LifecycleEnvironment` entities:: LifecycleEnvironment().search() Values on an entity are used to generate a search query, and t...
6,706
def get_columns(self, font): font = self.get_font(font) return self.fonts[six.text_type(font)][]
Return the number of columns for the given font.
6,707
def fit(self, X, y, step_size=0.1, init_weights=None, warm_start: bool=False): assert len(np.shape(X)) == 2, .format(len(np.shape(X))) assert np.shape(X)[0] > 1, \ .format(np.shape(X)[0]) assert np.shape(X)[1] == len(y), ( .f...
Fit the weights on the given predictions. Args: X (array-like): Predictions of different models for the labels. y (array-like): Labels. step_size (float): Step size for optimizing the weights. Smaller step sizes most likely improve resulting sc...
6,708
def watch_files(self): try: while 1: sleep(1) try: files_stat = self.get_files_stat() except SystemExit: logger.error("Error occurred, server shut down") self.shutdown_server() ...
watch files for changes, if changed, rebuild blog. this thread will quit if the main process ends
6,709
def vertex_normals(self): assert hasattr(self.faces_sparse, ) vertex_normals = geometry.mean_vertex_normals( vertex_count=len(self.vertices), faces=self.faces, face_normals=self.face_normals, sparse=self.faces_sparse) return verte...
The vertex normals of the mesh. If the normals were loaded we check to make sure we have the same number of vertex normals and vertices before returning them. If there are no vertex normals defined or a shape mismatch we calculate the vertex normals from the mean normals of the faces th...
6,710
def str_rstrip(x, to_strip=None): sl = _to_string_sequence(x).rstrip( if to_strip is None else to_strip) if to_strip != else x return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl)
Remove trailing characters from a string sample. :param str to_strip: The string to be removed :returns: an expression containing the modified string column. Example: >>> import vaex >>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.'] >>> df = vaex.from_arrays(text=text) >...
6,711
def create_cookie(self, delete=None): value = if delete else self._serialize(self.data) split_url = parse.urlsplit(self.adapter.url) domain = split_url.netloc.split()[0] if not in domain: template = else: template = ( ...
Creates the value for ``Set-Cookie`` HTTP header. :param bool delete: If ``True`` the cookie value will be ``deleted`` and the Expires value will be ``Thu, 01-Jan-1970 00:00:01 GMT``.
6,712
def get_shark_field(self, fields): out = super(BACK, self).get_shark_field(fields) out.update({: self.acked_seqs, : self.bitmap_str}) return out
:fields: str[]
6,713
def get_config(self): self.update_network_description() result = dict(self.__dict__) result[] = None result[] = None result[] = None result[] = None return result
serialize to a dict all attributes except model weights Returns ------- dict
6,714
def _get_channel(self): channel = self._transport.open_session() channel.set_combine_stderr(True) channel.get_pty() return channel
Returns a channel according to if there is a redirection to do or not.
6,715
def build_trips(pfeed, routes, service_by_window): routes = pd.merge(routes[[, ]], pfeed.frequencies) routes = pd.merge(routes, pfeed.service_windows) rows = [] for index, row in routes.iterrows(): shape = row[] route = row[] window = row[] star...
Given a ProtoFeed and its corresponding routes (DataFrame), service-by-window (dictionary), return a DataFrame representing ``trips.txt``. Trip IDs encode route, direction, and service window information to make it easy to compute stop times later.
6,716
def _parse_launch_error(data): return LaunchFailure( data.get(ERROR_REASON, None), data.get(APP_ID), data.get(REQUEST_ID), )
Parses a LAUNCH_ERROR message and returns a LaunchFailure object. :type data: dict :rtype: LaunchFailure
6,717
def add_sparse_covariance_matrix(self,x,y,names,iidx,jidx,data): if not isinstance(x, np.ndarray): x = np.array(x) if not isinstance(y, np.ndarray): y = np.array(y) assert x.shape[0] == y.shape[0] assert x.shape[0] == len(names) ...
build a pyemu.SparseMatrix instance implied by Vario2d Parameters ---------- x : (iterable of floats) x-coordinate locations y : (iterable of floats) y-coordinate locations names : (iterable of str) names of locations. If None, cov must not be...
6,718
def _readBlock(self): if self.interrupted or self.fp is None: if self.debug: log.msg() return True length = self.blocksize if self.bytes_remaining is not None and length > self.bytes_remaining: length = self.bytes_remaining ...
Read a block of data from the remote reader.
6,719
def datasetsBM(host=biomart_host): stdout_ = sys.stdout stream = StringIO() sys.stdout = stream server = BiomartServer(biomart_host) server.show_datasets() sys.stdout = stdout_ variable = stream.getvalue() v=variable.replace("{"," ") v=v.replace("}"," ") v=v.replace(...
Lists BioMart datasets. :param host: address of the host server, default='http://www.ensembl.org/biomart' :returns: nothing
6,720
def generate_unit_squares(image_width, image_height): for x in range(image_width): for y in range(image_height): yield [(x, y), (x + 1, y), (x + 1, y + 1), (x, y + 1)]
Generate coordinates for a tiling of unit squares.
6,721
def _get_baremetal_connections(self, port, only_active_switch=False, from_segment=False): connections = [] is_native = False if self.trunk.is_trunk_subport(port) else True all_link_info = port[bc.portbindings.PROFI...
Get switch ips and interfaces from baremetal transaction. This method is used to extract switch/interface information from transactions where VNIC_TYPE is baremetal. :param port: Received port transaction :param only_active_switch: Indicator for selecting c...
6,722
def vmomentsurfacemass(self,R,n,m,t=0.,nsigma=None,deg=False, epsrel=1.e-02,epsabs=1.e-05,phi=0., grid=None,gridpoints=101,returnGrid=False, hierarchgrid=False,nlevels=2, print_progress=False, ...
NAME: vmomentsurfacemass PURPOSE: calculate the an arbitrary moment of the velocity distribution at (R,phi) times the surfacmass INPUT: R - radius at which to calculate the moment (in natural units) phi= azimuth (rad unless deg=True) n - vR^n...
6,723
def get_arguments(self): MetricCommon.get_arguments(self) if self.args.metricName is not None: self.metricName = self.args.metricName if self.args.displayName is not None: self.displayName = self.args.displayName ...
Extracts the specific arguments of this CLI
6,724
def iter(self, order=, sort=True): from casacore.tables import tableiter return tableiter(self._table, [self._column], order, sort)
Return a :class:`tableiter` object on this column.
6,725
def content(self): content = self._get_content() if bool(content and in content): return content return safe_unicode(content)
Returns lazily content of the FileNode. If possible, would try to decode content from UTF-8.
6,726
def subscribe(self, objectID, varIDs=(tc.VAR_ROAD_ID, tc.VAR_LANEPOSITION), begin=0, end=2**31 - 1): Domain.subscribe(self, objectID, varIDs, begin, end)
subscribe(string, list(integer), int, int) -> None Subscribe to one or more object values for the given interval.
6,727
def apply_trend_constraint(self, limit, dt, distribution_skip=False, **kwargs): if type(limit) != Quantity: limit = limit * u.m/u.s if type(dt) != Quantity: dt = dt * u.day dRVs = np.absolute(self.dRV(dt)) c1 = UpperLimit(d...
Constrains change in RV to be less than limit over time dt. Only works if ``dRV`` and ``Plong`` attributes are defined for population. :param limit: Radial velocity limit on trend. Must be :class:`astropy.units.Quantity` object, or else interpreted as m/s. ...
6,728
def _set_get_media_detail(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=get_media_detail.get_media_detail, is_leaf=True, yang_name="get-media-detail", rest_name="get-media-detail", parent=self, path_helper=self._path_helper, extmethods=self._extmeth...
Setter method for get_media_detail, mapped from YANG variable /brocade_interface_ext_rpc/get_media_detail (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_get_media_detail is considered as a private method. Backends looking to populate this variable should do so via...
6,729
def read_file(file_path_name): with io.open(os.path.join(os.path.dirname(__file__), file_path_name), mode=, encoding=) as fd: return fd.read()
Read the content of the specified file. @param file_path_name: path and name of the file to read. @return: content of the specified file.
6,730
def upload(client, source_dir): print() print() print() listings_folder = os.path.join(source_dir, ) langfolders = filter(os.path.isdir, list_dir_abspath(listings_folder)) for language_dir in langfolders: language = os.path.basename(language_dir) with open(os.path.join(lang...
Upload listing files in source_dir. folder herachy.
6,731
def _generateForTokenSecurity(self, username, password, tokenUrl, expiration=None, client=): query_dict = {: username, : password, ...
generates a token for a feature service
6,732
def _fluent_params(self, fluents, ordering) -> FluentParamsList: variables = [] for fluent_id in ordering: fluent = fluents[fluent_id] param_types = fluent.param_types objects = () names = [] if param_types is None: nam...
Returns the instantiated `fluents` for the given `ordering`. For each fluent in `fluents`, it instantiates each parameter type w.r.t. the contents of the object table. Returns: Sequence[Tuple[str, List[str]]]: A tuple of pairs of fluent name and a list of instantiated f...
6,733
def hide(self): self.tk.withdraw() self._visible = False if self._modal: self.tk.grab_release()
Hide the window.
6,734
def data(self, index, role=Qt.DisplayRole): if not index.isValid(): return None def convertValue(row, col, columnDtype): value = None if columnDtype == object: value = self._dataFrame.ix[row, col] elif columnDtype in self._floatD...
return data depending on index, Qt::ItemDataRole and data type of the column. Args: index (QtCore.QModelIndex): Index to define column and row you want to return role (Qt::ItemDataRole): Define which data you want to return. Returns: None if index is invalid ...
6,735
def orchestrate_high(data, test=None, queue=False, pillar=None, **kwargs): { stage_one: {salt.state: [{tgt: "db*"}, {sls: postgres_setup}]}, stage_two: {salt.state: [{tgt: "web*"}, {sls: apache_setup}, { require: [{salt: stage_one}], ...
Execute a single state orchestration routine .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt-run state.orchestrate_high '{ stage_one: {salt.state: [{tgt: "db*"}, {sls: postgres_setup}]}, stage_two: {salt.state: [{tgt: "web...
6,736
def to_dict(self, *, include_keys=None, exclude_keys=None, use_default_excludes=True): data = self.__dict__ if include_keys: return pick(data, include_keys, transform=self._other_to_dict) else: skeys = self.exclude_keys_serialize if use_default_excludes else None ekeys = exclude_keys...
Converts the class to a dictionary. :include_keys: if not None, only the attrs given will be included. :exclude_keys: if not None, all attrs except those listed will be included, with respect to use_default_excludes. :use_default_excludes: if True, then the class-level exclude_keys_serialize will be co...
6,737
def compute(cls, observation, prediction, key=None): assert isinstance(observation, (dict, float, int, pq.Quantity)) assert isinstance(prediction, (dict, float, int, pq.Quantity)) obs, pred = cls.extract_means_or_values(observation, prediction, ...
Compute a ratio from an observation and a prediction.
6,738
def _projection_to_paths(cls, root_key, projection): if in projection: return True inclusive = True sub_projection = {} for key, value in projection.items(): if key in [, ]: continue if key.startswith(): ...
Expand a $sub/$sub. projection to a single projection of True (if inclusive) or a map of full paths (e.g `employee.company.tel`).
6,739
def _process_priv_part(perms): _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == : _tmp[previous] = True else: ...
Process part
6,740
def get_lib_volume_mounts(base_lib_name, assembled_specs): volumes = [_get_lib_repo_volume_mount(assembled_specs[][base_lib_name])] volumes.append(get_command_files_volume_mount(base_lib_name, test=True)) for lib_name in assembled_specs[][base_lib_name][][]: lib_spec = assembled_specs[][lib_nam...
Returns a list of the formatted volume specs for a lib
6,741
def getcomments(object): try: lines, lnum = findsource(object) except IOError: return None if ismodule(object): start = 0 if lines and lines[0][:2] == : start = 1 while start < len(lines) and string.strip(lines[start]) in [, ]: start = start + 1 if ...
Get lines of comments immediately preceding an object's source code.
6,742
def on_train_begin(self, **kwargs): "Create the optimizers for the generator and critic if necessary, initialize smootheners." if not getattr(self,,None): self.opt_gen = self.opt.new([nn.Sequential(*flatten_model(self.generator))]) else: self.opt_gen.lr,self.opt_gen.wd = self.opt.lr,...
Create the optimizers for the generator and critic if necessary, initialize smootheners.
6,743
def is_downloaded(self, file_path): if os.path.exists(file_path): self.chatbot.logger.info() return True return False
Check if the data file is already downloaded.
6,744
def genlet(generator_function=None, prime=True): if generator_function is None: return GeneratorLink.wraplet(prime=prime) elif not callable(generator_function): return GeneratorLink.wraplet(prime=generator_function) return GeneratorLink.wraplet(prime=prime)(generator_function)
Decorator to convert a generator function to a :py:class:`~chainlink.ChainLink` :param generator_function: the generator function to convert :type generator_function: generator :param prime: advance the generator to the next/first yield :type prime: bool When used as a decorator, this function can...
6,745
def add(self, item, position=5): if item in self.items: return self.items[item] = position self._add_dep(item) self.order = None self.changed(code_changed=True)
Add an item to the list unless it is already present. If the item is an expression, then a semicolon will be appended to it in the final compiled code.
6,746
def set_jinja2_silent_none(config): config.commit() jinja2_env = config.get_jinja2_environment() jinja2_env.finalize = _silent_none
if variable is None print '' instead of 'None'
6,747
def _parse_ignores(self): error_message = ( colorama.Fore.RED + "{} does not appear to be a valid pylintrc file".format(self.rcfile) + colorama.Fore.RESET ) if not os.path.isfile(self.rcfile): if not self._is_using_default_rcfile(): ...
Parse the ignores setting from the pylintrc file if available.
6,748
def t_stringdollar_rbrace(self, t): r t.lexer.braces -= 1 if t.lexer.braces == 0: t.lexer.begin()
r'\}
6,749
def perform_update(self, serializer): instance = serializer.save() instance.history.create(data=instance.data)
creates a record in the `bulbs.promotion.PZoneHistory` :param obj: the instance saved :param created: boolean expressing if the object was newly created (`False` if updated)
6,750
def _compute_attenuation(self, rup, dists, imt, C): vec = np.ones(len(dists.rrup)) a1 = (np.log10(np.sqrt(dists.rrup ** 2.0 + C[] ** 2.0)), np.log10(70. * vec)) a = np.column_stack([a1[0], a1[1]]) b3 = (np.log10(np.sqrt(dists.rrup ** 2.0 + C[] ** 2.0) / ...
Compute the second term of the equation described on p. 1866: " [(c4 + c5 * M) * min{ log10(R), log10(70.) }] + [(c4 + c5 * M) * max{ min{ log10(R/70.), log10(140./70.) }, 0.}] + [(c8 + c9 * M) * max{ log10(R/140.), 0}] "
6,751
def at(self, instant): for event in self: if event.begin <= instant <= event.end: yield event
Iterates (in chronological order) over all events that are occuring during `instant`. Args: instant (Arrow object)
6,752
def show_hide(self, *args): log.debug("Show_hide called") if self.forceHide: self.forceHide = False return if not HidePrevention(self.window).may_hide(): return if not self.win_prepare(): return if not self.window.get_pr...
Toggles the main window visibility
6,753
def bank_account_number(self): start = get_iban_spec(self.country_code).bban_split_pos + 4 return self._id[start:]
Return the IBAN's Bank Account Number.
6,754
def stream_file(self, url, folder=None, filename=None, overwrite=False): path = self.get_path_for_url(url, folder, filename, overwrite) f = None try: f = open(path, ) for chunk in self.response.iter_content(chunk_size=10240): if chunk: ...
Stream file from url and store in provided folder or temporary folder if no folder supplied. Must call setup method first. Args: url (str): URL to download filename (Optional[str]): Filename to use for downloaded file. Defaults to None (derive from the url). folder (...
6,755
def get_property(obj, name): if obj == None or name == None: return None names = name.split(".") if names == None or len(names) == 0: return None return RecursiveObjectReader._perform_get_property(obj, names, 0)
Recursively gets value of object or its subobjects property specified by its name. The object can be a user defined object, map or array. The property name correspondently must be object property, map key or array index. :param obj: an object to read property from. :param name: a name...
6,756
def finish( self, width=1, color=None, fill=None, roundCap=False, dashes=None, even_odd=False, morph=None, closePath=True ): if self.draw_cont == "": return ...
Finish the current drawing segment. Notes: Apply stroke and fill colors, dashes, line style and width, or morphing. Also determines whether any open path should be closed by a connecting line to its start point.
6,757
def write_flows_to_gssha_time_series_xys(self, path_to_output_file, series_name, series_id, river_index=None, ...
Write out RAPID output to GSSHA WMS time series xys file. Parameters ---------- path_to_output_file: str Path to the output xys file. series_name: str The name for the series. series_id: int The ID to give the series. river_index: :obj...
6,758
def authorize(self, me, state=None, next_url=None, scope=): redirect_url = flask.url_for( self.flask_endpoint_for_function(self._authorized_handler), _external=True) return self._start_indieauth( me, redirect_url, state or next_url, scope)
Authorize a user via Micropub. Args: me (string): the authing user's URL. if it does not begin with https?://, http:// will be prepended. state (string, optional): passed through the whole auth process, useful if you want to maintain some state, e.g. the starting pag...
6,759
def get_notify_observers_kwargs(self): return { : self._u_new, : self._x_new, : self._y_new, : self._z, : self._xi, : self._sigma, : self._t_new, : self.idx, }
Return the mapping between the metrics call and the iterated variables. Return ---------- notify_observers_kwargs: dict, the mapping between the iterated variables.
6,760
def cmp(self,junc,tolerance=0): if self.overlaps(junc,tolerance): return 0 if self.left.chr == junc.right.chr: if self.left.start > junc.right.start: return -1 if self.right.chr == junc.left.chr: if self.right.start < junc.right.start: return 1 return 2
output comparison and allow for tolerance if desired * -1 if junc comes before self * 1 if junc comes after self * 0 if overlaps * 2 if else :param junc: :param tolerance: optional search space (default=0, no tolerance) :type junc: Junction :type tolerance: int :return: value of co...
6,761
def fuzzybreaks(scale, breaks=None, boundary=None, binwidth=None, bins=30, right=True): if isinstance(scale, scale_discrete): breaks = scale.get_breaks() return -0.5 + np.arange(1, len(breaks)+2) else: if breaks is not None: breaks = scale....
Compute fuzzy breaks For a continuous scale, fuzzybreaks "preserve" the range of the scale. The fuzzing is close to numerical roundoff and is visually imperceptible. Parameters ---------- scale : scale Scale breaks : array_like Sequence of break points. If provided and the ...
6,762
def from_pypirc(pypi_repository): ret = {} pypirc_locations = PYPIRC_LOCATIONS for pypirc_path in pypirc_locations: pypirc_path = os.path.expanduser(pypirc_path) if os.path.isfile(pypirc_path): parser = configparser.SafeConfigParser() parser.read(pypirc_path) ...
Load configuration from .pypirc file, cached to only run once
6,763
def set_gae_attributes(span): for env_var, attribute_key in GAE_ATTRIBUTES.items(): attribute_value = os.environ.get(env_var) if attribute_value is not None: pair = {attribute_key: attribute_value} pair_attrs = Attributes(pair)\ .format_attributes_json()...
Set the GAE environment common attributes.
6,764
def get_render(name, data, trans=): translation.activate(trans) config = loader.get_template(name) result = config.render(data).replace(, ) translation.deactivate() return result
Render string based on template :param name: -- full template name :type name: str,unicode :param data: -- dict of rendered vars :type data: dict :param trans: -- translation for render. Default 'en'. :type trans: str,unicode :return: -- rendered string :rtype: str,unicode
6,765
def findall(self, string): output = [] for match in self.pattern.findall(string): if hasattr(match, ): match = [match] self._list_add(output, self.run(match)) return output
Parse string, returning all outputs as parsed by functions
6,766
def _finishSphering(self): self._normOffset = self._samples.mean(axis=0) * -1.0 self._samples += self._normOffset variance = self._samples.var(axis=0) variance[numpy.where(variance == 0.0)] = 1.0 self._normScale = 1.0 / numpy.sqrt(variance) self._samples *= s...
Compute normalization constants for each feature dimension based on the collected training samples. Then normalize our training samples using these constants (so that each input dimension has mean and variance of zero and one, respectively.) Then feed these "sphered" training samples into the underlyin...
6,767
def layout(self, slide): image = Image.new(, (WIDTH, HEIGHT), ) draw = ImageDraw.Draw(image) draw.font = self.font self.vertical_layout(draw, slide) self.horizontal_layout(draw, slide) return slide
Return layout information for slide
6,768
def main(): project_root = utils.get_project_root() infofile = os.path.join(project_root, "raw-datasets/info.yml") logging.info("Read ...", infofile) with open(infofile, ) as ymlfile: datasets = yaml.load(ymlfile) for dataset in datasets: local_path_file = os.path.join(proj...
Main part of the download script.
6,769
def config(): config = get_config() print(.format(click.style(__version__, bold=True))) print(.format(click.style(str(config.endpoint), bold=True))) print(.format(click.style(config.version, bold=True))) print(.format(click.style(config.access_key, bold=True))) masked_skey = config.secret_k...
Shows the current configuration.
6,770
async def retrieve(self, url, **kwargs): try: async with self.websession.request(, url, **kwargs) as res: if res.status != 200: raise Exception("Could not retrieve information from API") if res.content_type == : return ...
Issue API requests.
6,771
def parse_variable(self, variable): data = None if variable is not None: variable = variable.strip() if re.match(self._variable_match, variable): var = re.search(self._variable_parse, variable) data = { : var.group(0), ...
Method to parse an input or output variable. **Example Variable**:: #App:1234:output!String Args: variable (string): The variable name to parse. Returns: (dictionary): Result of parsed string.
6,772
def lowercase_to_camelcase(python_input, camelcase_input=None): if camelcase_input: if python_input.__class__ != camelcase_input.__class__: raise ValueError( % (camelcase_input.__class__, python_input.__class__)) if isinstance(python_input, dict): return _to_camelcase_...
a function to recursively convert data with lowercase key names into camelcase keys :param camelcase_input: list or dictionary with lowercase keys :param python_input: [optional] list or dictionary with default camelcase keys in output :return: dictionary with camelcase key names
6,773
def _is_number_match_OO(numobj1_in, numobj2_in): numobj1 = _copy_core_fields_only(numobj1_in) numobj2 = _copy_core_fields_only(numobj2_in) if (numobj1.extension is not None and numobj2.extension is not None and numobj1.extension != numobj2.extension): return MatchType...
Takes two phone number objects and compares them for equality.
6,774
def _get_temperature(self, data): temp = (data[2] & ~(1 << 7)) + (data[3] / 100) sign = (data[2] >> 7) & 1 if sign == 0: return round(temp, 2) return round(-1 * temp, 2)
Return temperature in celsius
6,775
def _uptime_windows(): if hasattr(ctypes, ) and hasattr(ctypes.windll, ): lib = ctypes.windll.kernel32 else: try: lib = ctypes.CDLL() except (AttributeError, OSError): return None if hasattr(lib, ): lib.GetTickCount64.restyp...
Returns uptime in seconds or None, on Windows. Warning: may return incorrect answers after 49.7 days on versions older than Vista.
6,776
def validate_arguments(self, start_date, end_date, **kwargs): if set(kwargs) < set(self.required_filters): raise InvalidRequestInputError( .format(set(self.required_filters.keys()), self.query_name) )
Validate query arguments.
6,777
def decodeMessage(self, data): message = proto_pb2.Msg() message.ParseFromString(data) return message
Decode a protobuf message into a list of Tensor events
6,778
def zone_schedules_restore(self, filename): _LOGGER.info("Restoring schedules to ControlSystem %s (%s)...", self.systemId, self.location) _LOGGER.info("Reading from backup file: %s...", filename) with open(filename, ) as file_input: schedule_db = file_i...
Restore all zones on control system from the given file.
6,779
def signed_session(self, session=None): self.set_token() return super(MSIAuthentication, self).signed_session(session)
Create requests session with any required auth headers applied. If a session object is provided, configure it directly. Otherwise, create a new session and return it. :param session: The session to configure for authentication :type session: requests.Session :rtype: requests.Se...
6,780
def UNTL_to_encodedUNTL(subject): subject = normalize_UNTL(subject) subject = subject.replace(, ) subject = subject.replace(, ) return subject
Normalize a UNTL subject heading to be used in SOLR.
6,781
def _gcs_delete(args, _): objects = _expand_list(args[]) objects.extend(_expand_list(args[])) errs = [] for obj in objects: try: bucket, key = google.datalab.storage._bucket.parse_name(obj) if bucket and key: gcs_object = google.datalab.storage.Object(bucket, key) if gcs_objec...
Delete one or more buckets or objects.
6,782
def serialize_on_parent( self, parent, value, state ): xml_value = _hooks_apply_before_serialize(self._hooks, state, value) self._processor.serialize_on_parent(parent, xml_value, state)
Serialize the value directory on the parent.
6,783
def validate(self, pkt, messages=None): valid = True for f in self.fields: try: value = getattr(pkt, f.name) except AttributeError: valid = False if messages is not None: msg = "Telemetry field mismatch...
Returns True if the given Packet is valid, False otherwise. Validation error messages are appended to an optional messages array.
6,784
def schaffer(self, x): N = len(x) s = x[0:N - 1]**2 + x[1:N]**2 return sum(s**0.25 * (np.sin(50 * s**0.1)**2 + 1))
Schaffer function x0 in [-100..100]
6,785
def _latex_circuit_drawer(circuit, scale=0.7, filename=None, style=None, plot_barriers=True, reverse_bits=False, justify=None): tmpfilename = with tem...
Draw a quantum circuit based on latex (Qcircuit package) Requires version >=2.6.0 of the qcircuit LaTeX package. Args: circuit (QuantumCircuit): a quantum circuit scale (float): scaling factor filename (str): file path to save image to style (dict or str): dictionary of style o...
6,786
def getCandScoresMapBruteForce(self, profile): wmg = profile.getWmg(True) m = len(wmg.keys()) cands = range(m) V = self.createBinaryRelation(m) gains = dict() for cand in wmg.keys(): gains[cand] = 0 graphs = itertools.product(range(2), repeat...
Returns a dictonary that associates the integer representation of each candidate with the bayesian losses that we calculate using brute force. :ivar Profile profile: A Profile object that represents an election profile.
6,787
def scan_module(self, modpath, node): used_origins = self.map.setdefault(modpath, set()) def get_origins(modpath, name): origins = set() def walk_origins(modpath, name): for origin in self.import_map.get_origins(modpath, name): ...
Scans a module, collecting all used origins, assuming that modules are obtained only by dotted paths and no other kinds of expressions.
6,788
def Nu_Kitoh(Re, Pr, H=None, G=None, q=None): r if H and G and q: qht = 200.*G**1.2 if H < 1.5E6: fc = 2.9E-8 + 0.11/qht elif 1.5E6 <= H <= 3.3E6: fc = -8.7E-8 - 0.65/qht else: fc = -9.7E-7 + 1.3/qht m = 0.69 - 81000./qht + fc*q els...
r'''Calculates internal convection Nusselt number for turbulent vertical upward flow in a pipe under supercritical conditions according to [1]_, also shown in [2]_, [3]_ and [4]_. Depends on fluid enthalpy, mass flux, and heat flux. .. math:: Nu_b = 0.015Re_b^{0.85} Pr_b^m ...
6,789
def raises(self, expected_exception): return unittest_case.assertRaises(expected_exception, self._orig_subject, *self._args, **self._kwargs)
Ensures preceding predicates (specifically, :meth:`called_with()`) result in *expected_exception* being raised.
6,790
def run(cmd, data=None, checks=None, region=None, log_error=True, log_stdout=False): try: logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd) _do_run(cmd, checks, log_stdout) except: if log_error: logger.info("error at command"...
Run the provided command, logging details and checking for errors.
6,791
def install_cache(expire_after=12 * 3600, cache_post=False): allowable_methods = [] if cache_post: allowable_methods.append() requests_cache.install_cache( expire_after=expire_after, allowable_methods=allowable_methods)
Patches the requests library with requests_cache.
6,792
def unsubscribe(self, connection, destination): self.log.debug("Unsubscribing %s from %s" % (connection, destination)) if connection in self._topics[destination]: self._topics[destination].remove(connection) if not self._topics[destination]: del self._topics[des...
Unsubscribes a connection from the specified topic destination. @param connection: The client connection to unsubscribe. @type connection: L{coilmq.server.StompConnection} @param destination: The topic destination (e.g. '/topic/foo') @type destination: C{str}
6,793
def translate_expression(expression): logger_ts.info("enter translate_expression") m = re_filter_expr.findall(expression) matches = [] if m: for i in m: logger_ts.info("parse match: {}".format(i)) tmp = list(i[1:]) if tmp[1] in COMPARISONS: ...
Check if the expression is valid, then check turn it into an expression that can be used for filtering. :return list of lists: One or more matches. Each list has 3 strings.
6,794
def date(self): if self.commit_time: return datetime.utcfromtimestamp(self.commit_time) else: return datetime.now()
:return: datetime object
6,795
def And(*predicates, **kwargs): if kwargs: predicates += Query(**kwargs), return _flatten(_And, *predicates)
`And` predicate. Returns ``False`` at the first sub-predicate that returns ``False``.
6,796
def home_shift_summ(self): if not self.__wrapped_home: self.__wrapped_home = self.__wrap(self._home.by_player) return self.__wrapped_home
:returns: :py:class:`.ShiftSummary` by player for the home team :rtype: dict ``{ player_num: shift_summary_obj }``
6,797
def find_files(self, ID=None, fileGrp=None, pageId=None, mimetype=None, url=None, local_only=False): ret = [] fileGrp_clause = if fileGrp is None else % fileGrp file_clause = if ID is not None: file_clause += % ID if mimetype is not None: file...
Search ``mets:file`` in this METS document. Args: ID (string) : ID of the file fileGrp (string) : USE of the fileGrp to list files of pageId (string) : ID of physical page manifested by matching files url (string) : @xlink:href of mets:Flocat of mets:file ...
6,798
def vstackm(matrices): arr = np_vstack(tuple(m.matrix for m in matrices)) return Matrix(arr)
Generalizes `numpy.vstack` to :class:`Matrix` objects.
6,799
def noinfo(self, msg, oname): print % msg, if oname: print % oname else: print
Generic message when no information is found.