Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
358,000
def take(self, indices, axis=0, convert=None, is_copy=True, **kwargs): if convert is not None: msg = ("The parameter is deprecated " "and will be removed in a future version.") warnings.warn(msg, FutureWarning, stacklevel=2) nv.validate_take(tuple(),...
Return the elements in the given *positional* indices along an axis. This means that we are not indexing according to actual values in the index attribute of the object. We are indexing according to the actual position of the element in the object. Parameters ---------- ...
358,001
def update(context, id, etag, name, team_id, data, active): result = feeder.update(context, id=id, etag=etag, name=name, team_id=team_id, data=data, state=utils.active_string(active)) utils.format_output(result, context.format)
update(context, id, etag, name, team_id, data, active) Update a Feeder. >>> dcictl feeder-update [OPTIONS] :param string id: ID of the feeder [required] :param string etag: Entity tag of the feeder resource [required] :param string name: Name of the feeder :param string team_id: ID of the tea...
358,002
def process_win_streak(data): if data[].count()>0: data[] = data[].str.len() data.loc[data[].str[0]==,] = -data[] data[] = data[] data = data.drop(,1) return data
Convert "+++"/"---" formatted win/loss streak column into a +/- integer column
358,003
def split_resource_path(resource): pieces = [] for piece in resource.split(): if path.sep in piece \ or (path.altsep and path.altsep in piece) or \ piece == path.pardir: raise ResourceNotFound(resource) elif piece and piece != : pieces.append(pi...
Split a path into segments and perform a sanity check. If it detects '..' in the path it will raise a `TemplateNotFound` error.
358,004
def convert_to_float_list(value): if isinstance(value, list) or value is None: return value else: s = re.findall(, value) for k, v in enumerate(s): try: s[k] = float(v) except ValueError: pass return s
Converts a comma separate string to a list :param value: the format must be 1.2,-3.5 (commas with no space) :type value: String :returns: List :example: >>> convert_to_integer_list('003,003,004,004') [1.2, -3.5]
358,005
def pospawn(self, pawn): if self._turn < pawn.thing[]: pawn.pos = self.pos_along(0) return elif ( pawn.thing[] and self._turn >= pawn.thing[] ): pawn.pos = self.pos_along(1) return try: ...
Position a :class:`Pawn` that is my child so as to reflect how far its :class:`Thing` has gone along my :class:`Portal`.
358,006
def get_cli_profile(): try: from azure.cli.core._profile import Profile from azure.cli.core._session import ACCOUNT from azure.cli.core._environment import get_config_dir except ImportError: raise ImportError("You need to install to load CLI credentials") azure_folde...
Return a CLI profile class. .. versionadded:: 1.1.6 :return: A CLI Profile :rtype: azure.cli.core._profile.Profile :raises: ImportError if azure-cli-core package is not available
358,007
def is_float(value, min=None, max=None): (min_val, max_val) = _is_num_param( (, ), (min, max), to_float=True) if not isinstance(value, number_or_string_types): raise VdtTypeError(value) if not isinstance(value, float): try: value = float(value) excep...
A check that tests that a given value is a float (an integer will be accepted), and optionally - that it is between bounds. If the value is a string, then the conversion is done - if possible. Otherwise a VdtError is raised. This can accept negative values. >>> vtor = Validator() >>> vtor.che...
358,008
def update_cache(force=False, cache_file=None): if not cache_file: cache_file = find_config() cache_config = devpipeline_configure.parser.read_config(cache_file) cache = devpipeline_configure.cache._CachedConfig(cache_config, cache_file) if force or _is_outdated(cache_file, cache): ...
Load a build cache, updating it if necessary. A cache is considered outdated if any of its inputs have changed. Arguments force -- Consider a cache outdated regardless of whether its inputs have been modified.
358,009
def create_hotkey(self, folder, description, modifiers, key, contents): modifiers.sort() if not self.configManager.check_hotkey_unique(modifiers, key, None, None): raise Exception("The specified hotkey and modifier combination is already in use") self.monitor.suspen...
Create a text hotkey Usage: C{engine.create_hotkey(folder, description, modifiers, key, contents)} When the given hotkey is pressed, it will be replaced with the given text. Modifiers must be given as a list of strings, with the following values permitted: ...
358,010
def make_desktop_entry(d): assert d[].endswith() d.setdefault(, ) d.setdefault(, ) if isinstance(d[], list): d[] = .join(d[]) assert isinstance(d[], bool) d[] = {False: , True: }[d[]] fo = open(d[], "w") fo.write( % d) if d[] == : fo.write() el...
Create a desktop entry that conforms to the format of the Desktop Entry Specification by freedesktop.org. See: http://freedesktop.org/Standards/desktop-entry-spec These should work for both KDE and Gnome2 An entry is a .desktop file that includes the application's type, executable, name, e...
358,011
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]): assert isinstance(pt, tuple) l_pt = len(pt) assert l_pt > 1 for i in pt: assert isinstance(i, float) assert isinstance(shift, list) l_sh = len(shift) assert l_sh == l_pt for i in shift: assert isinstance(i, float) r...
Return given point shifted in N dimensions.
358,012
def create_alter(): alter = upkey("alter").setResultsName("action") prim_or_star = primitive | "*" set_throughput = ( Suppress(upkey("set")) + Optional(Suppress(upkey("index")) + var.setResultsName("index")) + create_throughput(prim_or_star) ) drop_index = ( Su...
Create the grammar for the 'alter' statement
358,013
def groupby(df, *, group_cols: Union[str, List[str]], aggregations: Dict[str, Union[str, List[str]]]): df = df.groupby(group_cols, as_index=False).agg(aggregations) if df.columns.nlevels == 2: level_0 = df.columns.get_level_values(0) level_1 = df.columns.get_leve...
Aggregate values by groups. --- ### Parameters *mandatory :* - `group_cols` (*list*): list of columns used to group data - `aggregations` (*dict*): dictionnary of values columns to group as keys and aggregation function to use as values (See the [list of aggregation functions]( https:...
358,014
def set_callbacks(self, **kwargs): for name in self.SUPPORTED_CALLBACKS: func = kwargs.get(name, getattr(self, name)) setattr(self, name, func)
Set callbacks for input events
358,015
def p_user_add_link(self): if self.check_post_role()[]: pass else: return False post_data = self.get_post_data() post_data[] = self.get_current_user() cur_uid = tools.get_uudd(2) while MLink.get_by_uid(cur_uid): cur_uid = too...
user add link.
358,016
def build_query(self, **filters): field_facets = {} date_facets = {} query_facets = {} facet_serializer_cls = self.view.get_facet_serializer_class() if self.view.lookup_sep == ":": raise AttributeError("The %(cls)s.lookup_sep attribute conflicts with the Hay...
Creates a dict of dictionaries suitable for passing to the SearchQuerySet `facet`, `date_facet` or `query_facet` method. All key word arguments should be wrapped in a list. :param view: API View :param dict[str, list[str]] filters: is an expanded QueryDict or a mapping of keys to a lis...
358,017
def _get(self, action, show, proxy, timeout): silent = self.flags[] if action in self.cache: if action != and action != : utils.stderr("+ %s results in cache" % action, silent) return else: self.cache[action] = {} if sel...
make HTTP request and cache response
358,018
def keypoint_resize_random_crop(image, annos, mask=None, size=(368, 368)): if len(np.shape(image)) == 2: image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB) def resize_image(image, annos, mask, target_width, target_height): y, x, _ = np.shape(image) ratio_y = target_height /...
Reszie the image to make either its width or height equals to the given sizes. Then randomly crop image without influence scales. Resize the image match with the minimum size before cropping, this API will change the zoom scale of object. Parameters ----------- image : 3 channel image The g...
358,019
def _argsort_and_resolve_ties(time, random_state): n_samples = len(time) order = numpy.argsort(time, kind="mergesort") i = 0 while i < n_samples - 1: inext = i + 1 while inext < n_samples and time[order[i]] == time[order[inext]]: inext +=...
Like numpy.argsort, but resolves ties uniformly at random
358,020
def minmax(self, minimum=None, maximum=None): if(minimum is None and maximum is None): return {"minimum": self._minimum, "maximum": self._maximum} if minimum is not None: if not isinstance(minimum, (int, long)): if minimum < 0: raise ValueError() self._minimum = minimum ...
Min/Max Sets or gets the minimum and maximum number of items for the Array Arguments minimum {uint} -- The minimum value maximum {uint} -- The maximum value Raises: ValueError Returns: None
358,021
def get_composition_metadata(self): metadata = dict(self._mdata[]) metadata.update({: self._my_map[]}) return Metadata(**metadata)
Gets the metadata for linking this asset to a composition. return: (osid.Metadata) - metadata for the composition *compliance: mandatory -- This method must be implemented.*
358,022
def close(self): if not self.is_running: return self._state = CLOSED self.logger.debug() while True: try: conn = self._connections.get(block=False) except Empty: break conn.close_stream() ...
Immediately close all connections and stop workers.
358,023
def start_playing(self, on_exit, args): if "cache" in args.keys() and os.path.isfile(args["cache"]): thread = threading.Thread( target=self.run_mpg123, args=(on_exit, args["cache"]) ) else: new_url = NetEase().songs_url([args["song_id...
Runs the given args in subprocess.Popen, and then calls the function on_exit when the subprocess completes. on_exit is a callable object, and args is a lists/tuple of args that would give to subprocess.Popen.
358,024
def _write_packet(self, final): status = 1 if final else 0 _header.pack_into(self._buf, 0, self._type, status, self._pos, 0, self._packet_no) self._packet_no = (self._packet_no + 1) % 256 self._transport.sendall(self._buf[:self._pos]) self._pos = 8
Writes single TDS packet into underlying transport. Data for the packet is taken from internal buffer. :param final: True means this is the final packet in substream.
358,025
def where(boolean_expr, true_expr, false_null_expr): op = ops.Where(boolean_expr, true_expr, false_null_expr) return op.to_expr()
Equivalent to the ternary expression: if X then Y else Z Parameters ---------- boolean_expr : BooleanValue (array or scalar) true_expr : value Values for each True value false_null_expr : value Values for False or NULL values Returns ------- result : arity depending on inpu...
358,026
def zremrangebyscore(self, key, min_score, max_score): return self._execute([b, key, min_score, max_score])
Removes all elements in the sorted set stored at key with a score between min and max. Intervals are described in :meth:`~tredis.RedisClient.zrangebyscore`. Returns the number of elements removed. .. note:: **Time complexity**: ``O(log(N)+M)`` with ``N`` being the number o...
358,027
def get_initial_state_args(value_and_gradients_function, initial_position, grad_tolerance, control_inputs=None): if control_inputs: with tf.control_dependencies(control_inputs): f0, df0 = value_and_gradients_function(initial...
Returns a dictionary to populate the initial state of the search procedure. Performs an initial convergence check and the first evaluation of the objective function. Args: value_and_gradients_function: A Python callable that accepts a tensor and returns a tuple of two tensors: the objective function v...
358,028
def makeDoubleLinked(dom, parent=None): dom.parent = parent for child in dom.childs: child.parent = dom makeDoubleLinked(child, dom)
Standard output from `dhtmlparser` is single-linked tree. This will make it double-linked. Args: dom (obj): :class:`.HTMLElement` instance. parent (obj, default None): Don't use this, it is used in recursive call.
358,029
def load(self): stream = self.fs.load() stream = self.codec.decompress(stream) return stream
Load the data from a file. :rtype: io.BytesIO
358,030
def get_more(collection_name, num_to_return, cursor_id): data = __ZERO data += bson._make_c_string(collection_name) data += struct.pack("<i", num_to_return) data += struct.pack("<q", cursor_id) return __pack_message(2005, data)
Get a **getMore** message.
358,031
def notice_stream(self, stream): self._routes_by_stream[stream] = set([stream.remote_id]) self._propagate_up(mitogen.core.ADD_ROUTE, stream.remote_id, stream.name) mitogen.core.listen( obj=stream, name=, func=lambda: self._on_s...
When this parent is responsible for a new directly connected child stream, we're also responsible for broadcasting DEL_ROUTE upstream if/when that child disconnects.
358,032
def check_order(self): for feature, info in self.constraints.items(): self._check_feature(feature, info, ) self._check_feature(feature, info, ) self._check_position(feature, info) return not self.has_errors()
Performs the check and store the violations in self.violations. :return: boolean indicating the error state
358,033
def _build_request_factory(cls, session: AppSession): def request_factory(*args, **kwargs): request = session.factory.class_map[](*args, **kwargs) user_agent = session.args.user_agent or session.default_user_agent request.fields[] = user_agent if sessi...
Create the request factory. A request factory is any callable object that returns a :class:`.http.Request`. The callable must accept the same arguments to Request. Returns: A callable object
358,034
def error(self, message): super(_EndpointsParser, self).error(message)
Override superclass to support customized error message. Error message needs to be rewritten in order to display visible commands only, when invalid command is called by user. Otherwise, hidden commands will be displayed in stderr, which is not expected. Refer the following argparse python documentati...
358,035
def from_array(array): if array is None or not array: return None assert_type_or_raise(array, dict, parameter_name="array") data = {} data[] = float(array.get()) data[] = float(array.get()) data[] = int(array.get()) if array.get() is not Non...
Deserialize a new InputLocationMessageContent from a given dictionary. :return: new InputLocationMessageContent instance. :rtype: InputLocationMessageContent
358,036
def cli(context, mongodb, username, password, authdb, host, port, loglevel, config, demo): log_format = None coloredlogs.install(level=loglevel, fmt=log_format) LOG.info("Running scout version %s", __version__) LOG.debug("Debug logging enabled.") mongo_config = {} cli_config = {} ...
scout: manage interactions with a scout instance.
358,037
def _packet_loop(self): while self._is_running: if self.inbox.empty() \ and not self.new_packet.wait(self._packet_timeout): continue ip, port, packet = self.inbox.get() if self.inbox.empty(): self.new_p...
Packet processing loop :rtype: None
358,038
def etau_madau(wave, z, **kwargs): if not isinstance(z, numbers.Real): raise exceptions.SynphotError( ) if np.isscalar(wave) or len(wave) <= 1: raise exceptions.SynphotError() wave = units.validate_quantity(wave, u.AA, **kwargs).value ll = 912.0 c = np.array([3.6e...
Madau 1995 extinction for a galaxy at given redshift. This is the Lyman-alpha prescription from the photo-z code BPZ. The Lyman-alpha forest approximately has an effective "throughput" which is a function of redshift and rest-frame wavelength. One would multiply the SEDs by this factor before p...
358,039
def has_predecessor(self, u, v, t=None): return self.has_interaction(v, u, t)
Return True if node u has predecessor v at time t (optional). This is true if graph has the edge u<-v. Parameters ---------- u, v : nodes Nodes can be, for example, strings or numbers. Nodes must be hashable (and not None) Python objects. t : snapshot id...
358,040
def make_logging_undefined(logger=None, base=None): if logger is None: import logging logger = logging.getLogger(__name__) logger.addHandler(logging.StreamHandler(sys.stderr)) if base is None: base = Undefined def _log_message(undef): if undef._undefined_hint is...
Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__name__) LoggingUndefined = make_logging_undefined( logger=lo...
358,041
def with_stmt__26(self, with_loc, context, with_var, colon_loc, body): if with_var: as_loc, optional_vars = with_var item = ast.withitem(context_expr=context, optional_vars=optional_vars, as_loc=as_loc, loc=context.loc.join(optional_vars.loc)) ...
(2.6, 3.0) with_stmt: 'with' test [ with_var ] ':' suite
358,042
def run_service(prediction_fxn, namespace, prediction_type, block=False): subscribe = .format(namespace, prediction_type) if block: print else: print print , subscribe def run(): c = get_client(config.AGENT, config.ENTITY) def cb(msg): po = msgpack....
Supported prediction_type: - hvac - occupancy
358,043
def cat(self, out_ndx=None): if out_ndx is None: out_ndx = self.output self.make_ndx(o=out_ndx, input=[]) return out_ndx
Concatenate input index files. Generate a new index file that contains the default Gromacs index groups (if a structure file was defined) and all index groups from the input index files. :Arguments: out_ndx : filename Name of the output index file; if ``None`` ...
358,044
def launch(self, workflow_job_template=None, monitor=False, wait=False, timeout=None, extra_vars=None, **kwargs): if extra_vars is not None and len(extra_vars) > 0: kwargs[] = parser.process_extra_vars(extra_vars) debug.log(, header=) self._pop_none(kwargs) ...
Launch a new workflow job based on a workflow job template. Creates a new workflow job in Ansible Tower, starts it, and returns back an ID in order for its status to be monitored. =====API DOCS===== Launch a new workflow job based on a workflow job template. :param workflow_jo...
358,045
def _collate_results(self, field=None): import pandas as pd field = field if field else self._kwargs["field"] if field not in ("auto", "abundance", "readcount", "readcount_w_children"): raise OneCodexException("Specified field ({}) not valid.".format(field)) ...
For a list of objects associated with a classification result, return the results as a DataFrame and dict of taxa info. Parameters ---------- field : {'readcount_w_children', 'readcount', 'abundance'} Which field to use for the abundance/count of a particular taxon in a samp...
358,046
def check_input(input): def to_jtensor(i): if isinstance(i, np.ndarray): return JTensor.from_ndarray(i) elif isinstance(i, JTensor): return i else: raise Exception("Error unknown input type %s" % type(i)) if typ...
:param input: ndarray or list of ndarray or JTensor or list of JTensor. :return: (list of JTensor, isTable)
358,047
def roc_auc(fg_vals, bg_vals): y_true, y_score = values_to_labels(fg_vals, bg_vals) return roc_auc_score(y_true, y_score)
Computes the ROC Area Under Curve (ROC AUC) Parameters ---------- fg_vals : array_like list of values for positive set bg_vals : array_like list of values for negative set Returns ------- score : float ROC AUC score
358,048
def data(self, rows=None): rows = tf.range(self._capacity) if rows is None else rows assert rows.shape.ndims == 1 episode = tools.nested.map(lambda var: tf.gather(var, rows), self._buffers) length = tf.gather(self._length, rows) return episode, length
Access a batch of episodes from the memory. Padding elements after the length of each episode are unspecified and might contain old data. Args: rows: Episodes to select, defaults to all. Returns: Tuple containing a tuple of transition quantities with batch and time dimensions, and a...
358,049
def write_color_old( text, attr=None): u res = [] chunks = terminal_escape.split(text) n = 0 if attr is None: attr = 15 for chunk in chunks: m = escape_parts.match(chunk) if m: for part in m.group(1).split(u";"): if part == u"0": ...
u'''write text at current cursor position and interpret color escapes. return the number of characters written.
358,050
def inputs(self, name): self._closed() step = self._get_step(name, make_copy=False) return step.list_inputs()
List input names and types of a step in the steps library. Args: name (str): name of a step in the steps library.
358,051
def binarize(self, threshold=0): if not self.is_binarized(): self.pianoroll = (self.pianoroll > threshold)
Binarize the pianoroll. Parameters ---------- threshold : int or float A threshold used to binarize the pianorolls. Defaults to zero.
358,052
def read(file, system): blocks = [ , , , , , , , , , , , , , , , , , , ] nol = [1, 1, 1, 1, 1, 4, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0] rawd = re.compile(r) retval = True version = 0 b = 0 raw = {} for item in blocks: raw[item] = [] dat...
read PSS/E RAW file v32 format
358,053
def dumps(value): from contoml.file.file import TOMLFile if not isinstance(value, TOMLFile): raise RuntimeError("Can only dump a TOMLFile instance loaded by load() or loads()") return value.dumps()
Dumps a data structure to TOML source code. The given value must be either a dict of dict values, a dict, or a TOML file constructed by this module.
358,054
def get(*args, **kwargs): from invenio.modules.oauthclient.models import RemoteToken q = RemoteToken.query return q.count(), q.all()
Get users.
358,055
def insert_chunk(self, id_): if not isinstance(id_, text_type): id_ = id_.decode() if not is_valid_chunk_id(id_): raise KeyError("AIFF key must be four ASCII characters.") self.__fileobj.seek(self.__next_offset) self.__fileobj.write(pack(, id_.ljust(4)...
Insert a new chunk at the end of the IFF file
358,056
def database_to_SimaPro_csv(self): self.parameter_scan() csv_args = {} csv_args[] = [] db = self.database[] product_filter = lambda x: db[x][] == process_filter = lambda x: db[x][] == processes = list(filter(process_filter, db)) prod...
Export the lcopt model as a SimaPro csv file. The file will be called "<ModelName>_database_export.csv"
358,057
def loadVectors(self, filename, cols = None, everyNrows = 1, delim = , checkEven = 1, patterned = 0): return self.loadVectorsFromFile(filename, cols, everyNrows, delim, checkEven, patterned)
Load a set of vectors from a file. Takes a filename, list of cols you want (or None for all), get every everyNrows (or 1 for no skipping), and a delimeter.
358,058
def append_multiple(self, data, segment=0): if not hasattr(data, ): raise TypeError("append_multiple must be passed an iterable object") tmp_list = [] if hasattr(data, ): if len(data) <= self._block_size: self._builder.append_mu...
Append multiple rows to an SFrame. Throws a RuntimeError if one or more column's type is incompatible with a type appended. Parameters ---------- data : iterable[iterable] A collection of multiple iterables, each representing a single row. segment : int ...
358,059
def match(elem, seq_expr): if type(seq_expr) is str: if seq_expr == : return True elif seq_expr == : return elem.is_numerical() elif seq_expr == : return not elem.is_numerical() else: r...
Return True if elem (an element of elem_list) matches seq_expr, an element in self.sequence
358,060
def validate_num_assertions(self): encrypted_assertion_nodes = OneLogin_Saml2_XML.query(self.document, ) assertion_nodes = OneLogin_Saml2_XML.query(self.document, ) valid = len(encrypted_assertion_nodes) + len(assertion_nodes) == 1 if (self.encrypted): assertion_no...
Verifies that the document only contains a single Assertion (encrypted or not) :returns: True if only 1 assertion encrypted or not :rtype: bool
358,061
def _protected_inverse(x1): with np.errstate(divide=, invalid=): return np.where(np.abs(x1) > 0.001, 1. / x1, 0.)
Closure of log for zero arguments.
358,062
def encrypters(self): return set(m.encrypter for m in self._sessionkeys if isinstance(m, PKESessionKey))
A ``set`` containing all key ids (if any) to which this message was encrypted.
358,063
def _non_reducing_slice(slice_): kinds = (ABCSeries, np.ndarray, Index, list, str) if isinstance(slice_, kinds): slice_ = IndexSlice[:, slice_] def pred(part): return ((isinstance(part, slice) or is_list_like(part)) and not isinstance(part, t...
Ensurse that a slice doesn't reduce to a Series or Scalar. Any user-paseed `subset` should have this called on it to make sure we're always working with DataFrames.
358,064
def process(self, diagnostic): diagnostic.notes += self._appended_notes self.render_diagnostic(diagnostic) if diagnostic.level == "fatal" or \ (self.all_errors_are_fatal and diagnostic.level == "error"): raise Error(diagnostic)
The default implementation of :meth:`process` renders non-fatal diagnostics to ``sys.stderr``, and raises fatal ones as a :class:`Error`.
358,065
def iterslice(iterable, start=0, stop=None, step=1): if step < 0: raise ValueError("The step can not be negative: given" % step) if not isinstance(start, int): if not isinstance(stop, int) and stop: return stops_when(starts_when(iterable, start), stop) ...
Like itertools.islice, but accept int and callables. If `start` is a callable, start the slice after the first time start(item) == True. If `stop` is a callable, stop the slice after the first time stop(item) == True.
358,066
def set_bind(self): self.bind(, lambda e: self.add(0.1)) self.bind(, lambda e: self.sub(0.1)) self.bind(, lambda e: self.add(0.1)) self.bind(, lambda e: self.sub(0.1)) self.bind(, lambda e: self.add(1)) self.bind(, lambda e: self.sub(1)) self.bind(, lambd...
Sets key bindings.
358,067
def as_nick(self, name): orig = self.get_nickname() self.nick(name) try: yield orig finally: self.nick(orig)
Set the nick for the duration of the context.
358,068
def uuid_from_kronos_time(time, _type=UUIDType.RANDOM): return timeuuid_from_time(int(time) + UUID_TIME_OFFSET, type=_type)
Generate a UUID with the specified time. If `lowest` is true, return the lexicographically first UUID for the specified time.
358,069
def _sunos_memdata(): grains = {: 0, : 0} prtconf = for line in __salt__[](prtconf, python_shell=True).splitlines(): comps = line.split() if comps[0].strip() == and comps[1].strip() == : grains[] = int(comps[2].strip()) swap_cmd = salt.utils.path.which() swap_dat...
Return the memory information for SunOS-like systems
358,070
def upload(self, local_fn: str, remote_fn: str = , dont_overwrite: bool = False) -> None: if in local_fn: for local_subfn in glob.glob(local_fn): self.upload(local_subfn) return if in local_fn: self.log("skipping backup file {local_fn}") return i...
Uploads file to remote instance. If location not specified, dumps it into default directory. If remote location has files or directories with the same name, behavior is undefined.
358,071
def on_graph_def(self, graph_def, device_name, wall_time): del wall_time self._graph_defs[device_name] = graph_def if not self._graph_defs_arrive_first: self._add_graph_def(device_name, graph_def) self._incoming_channel.get()
Implementation of the GraphDef-carrying Event proto callback. Args: graph_def: A GraphDef proto. N.B.: The GraphDef is from the core runtime of a debugged Session::Run() call, after graph partition. Therefore it may differ from the GraphDef available to the general TensorBoard. For ex...
358,072
def send_messages(self, request, queryset, bulk=False): ret = [] errors = [] r = "" for device in queryset: try: if bulk: r = queryset.send_message("Test bulk notification") else: r = device.send_message("Test single notification") if r: ret.append(r) except GCMError as e: ...
Provides error handling for DeviceAdmin send_message and send_bulk_message methods.
358,073
def _calculate_correctedF3X4(self): def F(phi): phi_reshape = phi.reshape((3, N_NT)) functionList = [] stop_frequency = [] for x in range(N_STOP): codonFrequency = STOP_CODON_TO_NT_INDICES[x] * phi_reshape codonFrequency =...
Calculate `phi` based on the empirical `e_pw` values
358,074
def maybe_scheduled_sampling(self, features, logits, losses): hparams = self.hparams problem_hparams = self._problem_hparams if hparams.scheduled_sampling_prob == 0.0: return (logits, losses) modality = problem_hparams.modality["targets"] if modality != modalities.ModalityType...
Scheduled sampling. Performs forward inference again with "targets" feature replaced with values sampled from the model. This is the identity unless self.hparams.scheduled_sampling_prob > 0 (default). **WARNING**: This is not a faithful implementation of scheduled sampling. This implementatio...
358,075
def _de_casteljau_one_round(nodes, degree, lambda1, lambda2, lambda3): r dimension, num_nodes = nodes.shape num_new_nodes = num_nodes - degree - 1 new_nodes = np.empty((dimension, num_new_nodes), order="F") index = 0 parent_i1 = 0 parent_i2 = 1 parent_i3 = degree + 1 f...
r"""Performs one "round" of the de Casteljau algorithm for surfaces. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. .. note:: This is a helper function, used by :func:`make_transform` and :func:`_specialize_surface` (and ...
358,076
def validate_input_source_config_source_url_url(self, **kwargs): config = ET.Element("config") validate = ET.Element("validate") config = validate input = ET.SubElement(validate, "input") source = ET.SubElement(input, "source") config_source = ET.SubElement(sourc...
Auto Generated Code
358,077
def hume_process_jsonld(): if request.method == : return {} response = request.body.read().decode() body = json.loads(response) jsonld_str = body.get() jsonld = json.loads(jsonld_str) hp = hume.process_jsonld(jsonld) return _stmts_from_proc(hp)
Process Hume JSON-LD and return INDRA Statements.
358,078
def add_sign_transaction(self, signer: Account): if self.sig_list is None or len(self.sig_list) == 0: self.sig_list = [] elif len(self.sig_list) >= TX_MAX_SIG_SIZE: raise SDKException(ErrorCode.param_err()) tx_hash = self.hash256() sig_data = signer.gener...
This interface is used to add signature into the transaction. :param signer: an Account object which will sign the transaction. :return: a Transaction object which has been signed.
358,079
def change_scale(self, new_scale): offset = self.scale.offset(self._mjd, new_scale, self.eop) result = self.datetime + timedelta(seconds=offset) return self.__class__(result, scale=new_scale)
Args: new_scale (str) Return: Date
358,080
def prepare_user_module(self, user_module=None, user_ns=None): if user_module is None and user_ns is not None: user_ns.setdefault("__name__", "__main__") class DummyMod(object): "A dummy module used for IPythons__builtin____builtins__', builtin_mod) ...
Prepare the module and namespace in which user code will be run. When IPython is started normally, both parameters are None: a new module is created automatically, and its __dict__ used as the namespace. If only user_module is provided, its __dict__ is used as the namespace. ...
358,081
def _add_include_arg(arg_parser): arg_parser.add_argument("--include", metavar=, action=, type=to_unicode, dest=, help="Specifies a single path to include. This argument c...
Adds optional repeatable include parameter to a parser. :param arg_parser: ArgumentParser parser to add this argument to.
358,082
def all_versions_equal(self, versions): if len(versions) <= 1: return True semver = None for key, version in versions.items(): if semver is None: try: semver, _, __ = version_object_and_next(version) except V...
Verify that all the versions are the same. :param versions: :return:
358,083
def save(self, specfiles=None, compress=True, path=None): if specfiles is None: specfiles = [_ for _ in viewkeys(self.info)] else: specfiles = aux.toList(specfiles) for specfile in specfiles: if specfile not in self.info: warntext = \...
Writes the specified specfiles to ``siic`` files on the hard disk. .. note:: If ``.save()`` is called and no ``siic`` files are present in the specified path new files are generated, otherwise old files are replaced. :param specfiles: the name of an ms-run file or a...
358,084
def add_group_maintainer(self, name, user): self.service.add_group_maintainer( name, user, self.url_prefix, self.auth, self.session, self.session_send_opts)
Add the given user to the named group. Both group and user must already exist for this to succeed. Args: name (string): Name of group. user (string): User to add to group. version (optional[string]): Version of the Boss API to use. Defaults to the latest supported ...
358,085
def install(): reactor = ThreadedSelectReactor() from twisted.internet.main import installReactor installReactor(reactor) return reactor
Configure the twisted mainloop to be run using the select() reactor.
358,086
def join_time_series(serieses, ignore_year=False, T_s=None, aggregator=): if ignore_year: df = pd.DataFrame() for name, ts in serieses.iteritems(): sod = np.array(map(lambda x: (x.hour * 3600 + x.minute * 60 + x.second), ts.index.time)) ...
Combine a dict of pd.Series objects into a single pd.DataFrame with optional downsampling FIXME: For ignore_year and multi-year data, the index (in seconds) is computed assuming 366 days per year (leap year). So 3 out of 4 years will have a 1-day (86400 s) gap Arguments: series (dict of Seri...
358,087
def getInfo(self, query=None, process=False, mode="phonefy", qURI=None): results = [] data = "" if self._modeIsValid(mode=mode) and self._isValidQuery(query, mode=mode): if mode in ["mailfy", "phonefy", "searchfy", "usufy"]: try: results ...
Method that checks the presence of a given query and recovers the first list of complains. Args: ----- query: Query to verify. process: Calling the processing function. mode: Mode to be executed. qURI: A query to be checked. Return: -----...
358,088
def debug_derivative(self, guess): from .lmmin import check_derivative return check_derivative(self.component.npar, self.data.size, self.lm_model, self.lm_deriv, guess)
returns (explicit, auto)
358,089
def listen_for_updates(self): self.toredis.subscribe(self.group_pubsub, callback=self.callback)
Attach a callback on the group pubsub
358,090
def extract_props(self, settings): props = {} for param in self.call_parameters: if param in settings: props[param] = settings[param] else: props[param] = None return props
Extract all valuable properties to be displayed
358,091
def build_actions(self): checkau = ActionUnit("Sanity Checks", "Check the workfile. If the file is not conform, ask the user to continue.", self.sanity_check) copyau = ActionUnit("Copy File", "Copy the workfil...
Create an ActionCollection that will perform sanity checks, copy the file, create a database entry and perform cleanup actions and in case of a failure clean everything up. :param work: the workfile :type work: :class:`JB_File` :param release: the releasefile :type release: :cla...
358,092
def chat_post_message(self, text, room_id=None, channel=None, **kwargs): if room_id: return self.__call_api_post(, roomId=room_id, text=text, kwargs=kwargs) elif channel: return self.__call_api_post(, channel=channel, text=text, kwargs=kwargs) else: r...
Posts a new chat message.
358,093
def rekey(dikt): for k in dikt.iterkeys(): if isinstance(k, basestring): ik=fk=None try: ik = int(k) except ValueError: try: fk = float(k) except ValueError: continue ...
Rekey a dict that has been forced to use str keys where there should be ints by json.
358,094
def parse_simple_duration(duration): elements = _parse_duration_string(_clean(duration)) if not elements: raise ParseError() return _timedelta_from_elements(elements)
Attepmt to parse an ISO8601 formatted duration, using a naive calculation. Accepts a ``duration`` which must be an ISO8601 formatted string, and assumes 365 days in a year and 30 days in a month for the calculation. Returns a ``datetime.timedelta`` object.
358,095
def db_query(self, client_id, msg): content = msg[] query = content.get(, {}) keys = content.get(, None) buffers = [] empty = list() try: records = self.db.find_records(query, keys) except Exception as e: content = error.wrap_excep...
Perform a raw query on the task record database.
358,096
def validate_sign(xml, cert=None, fingerprint=None, fingerprintalg=, validatecert=False, debug=False, xpath=None, multicerts=None): if xml is None or xml == : raise Exception() elem = OneLogin_Saml2_XML.to_etree(xml) xmlsec.enable_debug_trace(debug) xmlsec.tree.add_...
Validates a signature (Message or Assertion). :param xml: The element we should validate :type: string | Document :param cert: The public cert :type: string :param fingerprint: The fingerprint of the public cert :type: string :param fingerprintalg: The algorit...
358,097
def gabc(elem, doc): if type(elem) == Code and "gabc" in elem.classes: if doc.format == "latex": if elem.identifier == "": label = "" else: label = + elem.identifier + return latex( "\n\\smallskip\n{%\n" + ...
Handle gabc file inclusion and gabc code block.
358,098
def cnst_A0T(self, Y0): r Y0f = sl.rfftn(Y0, None, self.cri.axisN) return sl.irfftn( sl.dot(self.B.T, np.conj(self.Df) * Y0f, axis=self.cri.axisC), self.cri.Nv, self.cri.axisN)
r"""Compute :math:`A_0^T \mathbf{y}_0` component of :math:`A^T \mathbf{y}` (see :meth:`.ADMMTwoBlockCnstrnt.cnst_AT`).
358,099
def get_decoder(cls, config: DecoderConfig, prefix: str) -> : config_type = type(config) if config_type not in cls.__registry: raise ValueError( % config_type.__name__) decoder_cls, suffix = cls.__registry[config_type] return decoder_cls(config=config, prefi...
Creates decoder based on config type. :param config: Decoder config. :param prefix: Prefix to prepend for decoder. :return: Decoder instance.