Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
358,700
def remover(self, id_model): if not is_valid_int_param(id_model): raise InvalidParameterError( u) url = + str(id_model) + code, xml = self.submit(None, , url) return self.response(code, xml)
Remove Model from by the identifier. :param id_model: Identifier of the Model. Integer value and greater than zero. :return: None :raise InvalidParameterError: The identifier of Model is null and invalid. :raise ModeloEquipamentoNaoExisteError: Model not registered. :raise Mod...
358,701
def _pip_cmd(self, name=None, prefix=None): if (name and prefix) or not (name or prefix): raise TypeError("conda pip: exactly one of ""or " "required.") if name and self.environment_exists(name=name): prefix = self.get_prefix_envname(name) ...
Get pip location based on environment `name` or `prefix`.
358,702
def _get_admin_route_name(model_or_instance): model = model_or_instance if isinstance(model_or_instance, type) else type(model_or_instance) return .format(meta=model._meta)
Get the base name of the admin route for a model or model instance. For use with :func:`django.urls.reverse`, although it still needs the specific route suffix appended, for example ``_changelist``.
358,703
def redo(self, channel, image): self.logger.debug("image set") chname = channel.name old_highlight = channel.extdata.thumbs_old_highlight if image is not None: thumbkey = self._get_thumb_key(chname, image) new_highlig...
This method is called when an image is set in a channel.
358,704
def newPanelTab(self): view = self._currentPanel.currentView() if view: new_view = view.duplicate(self._currentPanel) self._currentPanel.addTab(new_view, new_view.windowTitle())
Creates a new panel with a copy of the current widget.
358,705
def snr_series_to_xml(snr_series, document, sngl_inspiral_id): snr_lal = snr_series.lal() snr_lal.name = snr_lal.sampleUnits = snr_xml = _build_series(snr_lal, (u, u), None, , ) snr_node = document.childNodes[-1].appendChild(snr_xml) eid_param = ligolw_param.Pa...
Save an SNR time series into an XML document, in a format compatible with BAYESTAR.
358,706
def create_rl_lin_comb_method(op_name, klass, x_roles, y_roles): def new_method(self, other, x_roles=x_roles, y_roles=y_roles): if not check_special_methods(): raise NotImplementedError( % (op_name, str(self))) x = [] y = [] for...
Creates a new binary special method with left and right versions, such as A.__mul__(B) <=> A*B, A.__rmul__(B) <=> [B*A if B.__mul__(A) fails] for target class. The method is called __op_name__.
358,707
def get_size(vm_): s size. Used by create_node(). sizeslugslugThe specified size, \, could not be found.'.format(vm_size) )
Return the VM's size. Used by create_node().
358,708
def RandomNormalInitializer(stddev=1e-2): def init(shape, rng): return (stddev * backend.random.normal(rng, shape)).astype() return init
An initializer function for random normal coefficients.
358,709
def create(self, data, **kwargs): self.client.post(self.url, data=data)
Create classifitions for specific entity
358,710
def unshare(flags): res = lib.unshare(flags) if res != 0: _check_error(ffi.errno)
Disassociate parts of the process execution context. :param flags int: A bitmask that specifies which parts of the execution context should be unshared.
358,711
def url_name_for_action(self, action): return "%s.%s_%s" % (self.module_name.lower(), self.model_name.lower(), action)
Returns the reverse name for this action
358,712
def finalize_processes(self): self._term_signal.value = 1 if self._check_thread is not None: self._check_thread.join() for proc in self._procs: proc.join()
Finalize processes :param _MultiprocessOffload self: this
358,713
def copy(self, dst, **kwargs): _fs, filename = opener.parse(self.uri) _fs_dst, filename_dst = opener.parse(dst) copyfile(_fs, filename, _fs_dst, filename_dst, **kwargs) return [{: , : self.pointer, : dst}]
Copy file to a new destination. Returns JSON Patch with proposed change pointing to new copy.
358,714
def compare_graphs(graph1, mode, graph2=None): package_path = ding0.__path__[0] file = path.join(package_path, , , ) if mode == : try: nx.write_gpickle(graph1, file) print(, file) except: raise FileNotFoundError(, file) elif mode == : ...
Compares graph with saved one which is loaded via networkx' gpickle Parameters ---------- graph1 : networkx.graph First Ding0 MV graph for comparison graph2 : networkx.graph Second Ding0 MV graph for comparison. If a second graph is not provided it will be laoded from disk with ...
358,715
def _flatten(self, iterator, **filter_options): resp = list() for entry in iterator: for tup in entry: if self._matches_filter(tup, **filter_options): resp.append(tup) return resp
iterator here gives as lists of tuples. Method flattens the structure to a single list of tuples.
358,716
async def get_attached_modules(request): hw = hw_from_req(request) if ff.use_protocol_api_v2(): hw_mods = await hw.discover_modules() module_data = [ { : mod.name(), : mod.display_name(), : mod.port, : mod.device_in...
On success (including an empty "modules" list if no modules are detected): // status: 200 { "modules": [ { /** name of module */ "name": "string", /** model identifier (i.e. part number) */ "model": "string", /**...
358,717
def handle(self, key, value): master = {} master[] = value master[] = 0 master[] = int(self.get_current_time()) elements = key.split(":") dict = {} dict[] = elements[1] dict[] = elements[2] extras = self.get_lo...
Processes a vaild action info request @param key: The key that matched the request @param value: The value associated with the key
358,718
def predict(self, X=None): time1 = time.time() if X is not None: for x in X: assert len(x) == 2, \ X1, X2 = zip(*X) num_voxels1 = X1[0].shape[1] num_voxels2 = X2[0].shape[1] if num_voxe...
Use a trained model to predict correlation data. first compute the correlation of the input data, and then normalize across all samples in the list if there are more than one sample, and then predict via self.clf. If X is None, use the similarity vectors produced in fit ...
358,719
def mime_type(self, path): name, ext = os.path.splitext(path) return MIME_TYPES[ext]
Get mime-type from filename
358,720
def p_type_def_empty(p): p[0] = make_type(_TYPE(gl.DEFAULT_TYPE).name, p.lexer.lineno, implicit=True)
typedef :
358,721
def _extract_optional_list_field(blob, name): value = _optional_list(typesafe_pop(blob, name, [])) if value is None: raise ParserError( .format(name)) return value
Handle optional fields that can be either a string or a list of strings.
358,722
def parse(self): "Parses the *rpc-reply*." if self._parsed: return root = self._root = to_ele(self._raw) ok = root.find(qualify("ok")) if ok is None: error = root.find(+qualify()) if error is not None: for err in root...
Parses the *rpc-reply*.
358,723
def get_url(self): line = self.line try: parsed = URI.parse(line) line = parsed.to_string(escape_password=False, direct=False, strip_ref=True) except ValueError: pass else: self._parsed_url = parsed return lin...
Sets ``self.name`` if given a **PEP-508** style URL
358,724
def get_customizationspec_ref(si, customization_spec_name): customization_spec_name = si.content.customizationSpecManager.GetCustomizationSpec(name=customization_spec_name) return customization_spec_name
Get a reference to a VMware customization spec for the purposes of customizing a clone si ServiceInstance for the vSphere or ESXi server (see get_service_instance) customization_spec_name Name of the customization spec
358,725
def apply_branchset(self, branchset_node, branchset): apply_to_branches = branchset_node.attrib.get() if apply_to_branches: apply_to_branches = apply_to_branches.split() for branch_id in apply_to_branches: if branch_id not in self.branches: ...
See superclass' method for description and signature specification. Parses branchset node's attribute ``@applyToBranches`` to apply following branchests to preceding branches selectively. Branching level can have more than one branchset exactly for this: different branchsets can apply t...
358,726
def _get_raw_data(self, name): filestem = for filestem, list_fvar in self._files.items(): if name in list_fvar: break fieldfile = self.step.sdat.filename(filestem, self.step.isnap, force_legacy=True) ...
Find file holding data and return its content.
358,727
def remove_time_words(text_string): if text_string is None or text_string == "": return "" elif isinstance(text_string, str): for word in TIME_WORDS: text_string = re.sub(r+word+r, "", text_string) return " ".join(text_string.split()) else: raise InputError("...
Removes any word associated to time (day, week, month, etc.) within text_string and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed
358,728
def package_loading(self): t1 = time.time() yield None t2 = time.time() self.package_load_time += t2 - t1
Use this around code in your package repository that is loading a package, for example from file or cache.
358,729
def from_json(json): return Point( lat=json[], lon=json[], time=isostr_to_datetime(json[]) )
Creates Point instance from JSON representation Args: json (:obj:`dict`): Must have at least the following keys: lat (float), lon (float), time (string in iso format). Example, { "lat": 9.3470298, "lon": 3.79274, ...
358,730
def do_fullscreen(self, line): self.bot.canvas.sink.trigger_fullscreen_action(True) print(self.response_prompt, file=self.stdout)
Make the current window fullscreen
358,731
def print_run_bidirectional_blast(reference, other_genome, dbtype, outdir): if dbtype == : command = elif dbtype == : command = else: raise ValueError() r_folder, r_name, r_ext = utils.split_folder_and_path(reference) g_folder, g_name, g_ext = utils.split_folder...
Write torque submission files for running bidirectional blast on a server and print execution command. Args: reference (str): Path to "reference" genome, aka your "base strain" other_genome (str): Path to other genome which will be BLASTed to the reference dbtype (str): "nucl" or "prot" - w...
358,732
def decode(mode=unicode_errors_default): def dec(f): f._nvim_decode = mode return f return dec
Configure automatic encoding/decoding of strings.
358,733
def in_use_connection_count(self, address): try: connections = self.connections[address] except KeyError: return 0 else: return sum(1 if connection.in_use else 0 for connection in connections)
Count the number of connections currently in use to a given address.
358,734
def set_suspend(self, thread, stop_reason, suspend_other_threads=False, is_pause=False): main self._threads_suspended_single_notification.increment_suspend_time() if is_pause: self._threads_suspended_single_notification.on_pause() info = self._mark_suspend(thread, stop_reaso...
:param thread: The thread which should be suspended. :param stop_reason: Reason why the thread was suspended. :param suspend_other_threads: Whether to force other threads to be suspended (i.e.: when hitting a breakpoint with a suspend all threads policy)...
358,735
def find_command(cmd, paths=None, pathext=None): if paths is None: paths = os.environ.get(, ).split(os.pathsep) if isinstance(paths, six.string_types): paths = [paths] if pathext is None: pathext = get_pathext() pathext = [ext for ext in pathext.lower().split(os.pathsep...
Searches the PATH for the given command and returns its path
358,736
def insert_cols(self, col, no_cols=1): post_command_event(self.main_window, self.ContentChangedMsg) tab = self.grid.current_table self.code_array.insert(col, no_cols, axis=1, tab=tab)
Adds no_cols columns before col, appends if col > maxcols and marks grid as changed
358,737
def notify(self, value: Any) -> asyncio.Future: if self._state == value: return None self._state = value return Publisher.notify(self, value)
Only notifies subscribers if state has changed. See also Publisher.notify(). :param value: value to be emitted to subscribers :returns: a future if at least one subscriber has returned a future, elsewise None
358,738
def _put_header(self): self.session._out( % self.pdf_version) if self.session.compression: self.session.buffer += + chr(235) + chr(236) + chr(237) + chr(238) + "\n"
Standard first line in a PDF.
358,739
def parseFeed(filename, yesterday): dom = xml.dom.minidom.parse(filename) getText = lambda node, tag: node.getElementsByTagName(tag)[0].childNodes[0].data getNode = lambda tag: dom.getElementsByTagName(tag) content = getNode()[0] feedTitle = getText(content, ) feedLink = getText(content...
Parse an RSS feed and filter only entries that are newer than yesterday.
358,740
def build_detection_class(folder, dataset_filename, label, sender_known=True): with open(dataset_filename, ) as dataset: for filename in os.listdir(folder): filename = os.path.join(folder, filename) sender, msg = parse_msg_sender(filename, sender_known)...
Builds signature detection class. Signature detection dataset includes patterns for two classes: * class for positive patterns (goes with label 1) * class for negative patterns (goes with label -1) The patterns are build of emails from `folder` and appended to dataset file. >>> build_signatur...
358,741
def factory(cls, **kwargs): for name, obj in inspect.getmembers(sys.modules[__name__]): if inspect.isclass(obj) and issubclass(obj, UserAuthnMethod): try: if obj.__name__ == cls: return obj(**kwargs) except AttributeError: pass
Factory method that can be used to easily instantiate a class instance :param cls: The name of the class :param kwargs: Keyword arguments :return: An instance of the class or None if the name doesn't match any known class.
358,742
def _handle_substatements(self, stmt: Statement, sctx: SchemaContext) -> None: for s in stmt.substatements: if s.prefix: key = ( sctx.schema_data.modules[sctx.text_mid].prefix_map[s.prefix][0] + ":" + s.keyword) else: ...
Dispatch actions for substatements of `stmt`.
358,743
def smembers(self, key, *, encoding=_NOTSET): return self.execute(b, key, encoding=encoding)
Get all the members in a set.
358,744
def opener(mode=): def open_file(f): if f is sys.stdout or f is sys.stdin: return f elif f == : return sys.stdin if in mode else sys.stdout elif f.endswith(): return bz2.BZ2File(f, mode) elif f.endswith(): return gzip.open(f, mod...
Factory for creating file objects Keyword Arguments: - mode -- A string indicating how the file is to be opened. Accepts the same values as the builtin open() function. - bufsize -- The file's desired buffer size. Accepts the same values as the builtin open() function.
358,745
def msg_curse(self, args=None, max_width=None): ret = [] if not self.stats or self.is_disable(): return ret ret.append(self.curse_add_line(global_message(), "TITLE")) for alert in self.stats: ret...
Return the dict to display in the curse interface.
358,746
def _get_thumbnail_filename(filename, append_text="-thumbnail"): name, ext = os.path.splitext(filename) return .join([name, append_text, ext])
Returns a thumbnail version of the file name.
358,747
def scalar_term(self, st): if isinstance(st, binary_type): return _ScalarTermS(st, self._jinja_sub) elif isinstance(st, text_type): return _ScalarTermU(st, self._jinja_sub) elif st is None: return _ScalarTermU(u(), self._jinja_sub) else: ...
Return a _ScalarTermS or _ScalarTermU from a string, to perform text and HTML substitutions
358,748
def convert_rtc(cls, timestamp): if timestamp & (1 << 31): timestamp &= ~(1 << 31) delta = datetime.timedelta(seconds=timestamp) return cls._Y2KReference + delta
Convert a number of seconds since 1/1/2000 to UTC time.
358,749
def getmtime(self, path, use_sudo=False): func = use_sudo and run_as_root or self.run with self.settings(hide(, )): return int(func( % locals()).strip())
Return the time of last modification of path. The return value is a number giving the number of seconds since the epoch Same as :py:func:`os.path.getmtime()`
358,750
def add_summaries(self, step, *tags_and_values): values = [] to_print = [] for tag, value in tags_and_values: values.append(tf.Summary.Value(tag=tag, simple_value=float(value))) to_print.append( % (tag, value)) if self._summary_writer: summary = tf.Summary(value=values) even...
Adds summaries to the writer and prints a log statement.
358,751
def t_singlequote_end(self, t): r"ID' t.lexer.string_value = None t.lexer.pop_state() return t
r"
358,752
def ldap_server_host_use_vrf(self, **kwargs): config = ET.Element("config") ldap_server = ET.SubElement(config, "ldap-server", xmlns="urn:brocade.com:mgmt:brocade-aaa") host = ET.SubElement(ldap_server, "host") hostname_key = ET.SubElement(host, "hostname") hostname_key....
Auto Generated Code
358,753
def receive_subscription_message(self, topic_name, subscription_name, peek_lock=True, timeout=60): if peek_lock: return self.peek_lock_subscription_message(topic_name, subscription_name, ...
Receive a message from a subscription for processing. topic_name: Name of the topic. subscription_name: Name of the subscription. peek_lock: Optional. True to retrieve and lock the message. False to read and delete the message. Default is True (lo...
358,754
def get(self, value, default=None): path = value if isinstance(value, Path) else Path(str(value)) subtree = self for part in path.parts: try: subtree = subtree[part] except KeyError: return default return subtree
Return a subtree if exists.
358,755
def Tags(self): return { TENSORS: list(self.tensors_by_tag.keys()), GRAPH: self._graph is not None, META_GRAPH: self._meta_graph is not None, RUN_METADATA: list(self._tagged_metadata.keys()) }
Return all tags found in the value stream. Returns: A `{tagType: ['list', 'of', 'tags']}` dictionary.
358,756
def _update_inernal(self, varp_list): if self.group_spike: self._b_prob_all = 1.-param_to_array(varp_list[0].gamma_group) [np.multiply(self._b_prob_all, 1.-vp.gamma_group, self._b_prob_all) for vp in varp_list[1:]] else: self._b_prob_all = 1.-param_t...
Make an update of the internal status by gathering the variational posteriors for all the individual models.
358,757
def write_locked(*args, **kwargs): def decorator(f): attr_name = kwargs.get(, ) @six.wraps(f) def wrapper(self, *args, **kwargs): rw_lock = getattr(self, attr_name) with rw_lock.write_lock(): return f(self, *args, **kwargs) return wrapp...
Acquires & releases a write lock around call into decorated method. NOTE(harlowja): if no attribute name is provided then by default the attribute named '_lock' is looked for (this attribute is expected to be a :py:class:`.ReaderWriterLock` object) in the instance object this decorator is attached to.
358,758
def move_phasecenter(d, l1, m1, u, v): logger.info( % (l1, m1)) data_resamp = numpyview(data_resamp_mem, , datashape(d)) rtlib.phaseshift_threaded(data_resamp, d, l1, m1, u, v)
Handler function for phaseshift_threaded
358,759
def sv_variants(institute_id, case_name): page = int(request.form.get(, 1)) variant_type = request.args.get(, ) institute_obj, case_obj = institute_and_case(store, institute_id, case_name) form = SvFiltersForm(request.form) default_panels = [] for panel in case_obj[]: if panel[]...
Display a list of structural variants.
358,760
def commit(self): if self.after is None: self.after = self.qteWidget.toHtml() else: pos = self.qteWidget.textCursor().position() self.qteWidget.setHtml(self.after) self.placeCursor(pos)
Put the document into the new state.
358,761
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): super(CreateKeyPairResponsePayload, self).read( input_buffer, kmip_version=kmip_version ) local_buffer = utils.BytearrayStream(input_buffer.read(self.length)) if self.is_tag_next( ...
Read the data encoding the CreateKeyPair response payload and decode it into its constituent parts. Args: input_buffer (stream): A data buffer containing encoded object data, supporting a read method. kmip_version (KMIPVersion): An enumeration defining the KMIP ...
358,762
def quoted(parser=any_token): quote_char = quote() value, _ = many_until(parser, partial(one_of, quote_char)) return build_string(value)
Parses as much as possible until it encounters a matching closing quote. By default matches any_token, but can be provided with a more specific parser if required. Returns a string
358,763
def write_inp(mesh, path = None, maxwidth = 40, sections = "solid"): def set_to_inp(sets, keyword): ss = "" for sk in sets.keys(): labels = sets[sk].loc[sets[sk]].index.values labels = list(labels) labels.sort() if len(labels)!= 0: ss += "*{0}, {0}={1}\n".format(keyword, sk)...
Exports the mesh to the INP format.
358,764
def get_snmp_information(self): snmp_dict = { : , : , : , : {} } commands = [ , , ] snmp_config = self.device.run_commands(commands, encoding=) for line in snmp_config...
get_snmp_information() for EOS. Re-written to not use TextFSM
358,765
def plot(self, f, lfilter=None, plot_xy=False, **kargs): f = lambda_tuple_converter(f) lfilter = lambda_tuple_converter(lfilter) if lfilter is None: lst_pkts = [f(*e) for e in self.res] else: lst_pkts = [f(*e) for e in self.res if lfil...
Applies a function to each packet to get a value that will be plotted with matplotlib. A list of matplotlib.lines.Line2D is returned. lfilter: a truth function that decides whether a packet must be plotted
358,766
def has_mail_attachment(self, name, mail_folder=, check_regex=False): mail_attachments = self._retrieve_mails_attachments_by_name(name, mail_folder, check_regex, ...
Checks the mail folder for mails containing attachments with the given name. :param name: The name of the attachment that will be searched for. :type name: str :param mail_folder: The mail folder where to look at. :type mail_folder: str :param check_regex: Checks the name for a ...
358,767
def process_files(self, path, recursive=False): self._logger.info(, path) for (path, file) in files_generator(path, recursive): if not file.endswith(BATCH_EXTENSION): self.process_file(os.path.join(path, file))
Apply normalizations over all files in the given directory. Iterate over all files in a given directory. Normalizations will be applied to each file, storing the result in a new file. The extension for the new file will be the one defined in BATCH_EXTENSION. Args: p...
358,768
def GRUCell(units): return GeneralGRUCell( candidate_transform=lambda: core.Dense(units=units), memory_transform=combinators.Identity, gate_nonlinearity=core.Sigmoid, candidate_nonlinearity=core.Tanh)
Builds a traditional GRU cell with dense internal transformations. Gated Recurrent Unit paper: https://arxiv.org/abs/1412.3555 Args: units: Number of hidden units. Returns: A Stax model representing a traditional GRU RNN cell.
358,769
def _TransmitBreakpointUpdates(self, service): reconnect = False retry_list = [] while self._transmission_queue: breakpoint, retry_count = self._transmission_queue.popleft() try: service.debuggees().breakpoints().update( debuggeeId=self._debuggee_id, id=breakpoint...
Tries to send pending breakpoint updates to the backend. Sends all the pending breakpoint updates. In case of transient failures, the breakpoint is inserted back to the top of the queue. Application failures are not retried (for example updating breakpoint in a final state). Each pending breakpoin...
358,770
def _all_create_or_get_groups(self, key, start_hdf5_group=None): if start_hdf5_group is None: newhdf5_group = self._trajectory_group else: newhdf5_group = start_hdf5_group created = False if key == : return newhdf5_group, created split...
Creates new or follows existing group nodes along a given colon separated `key`. :param key: Colon separated path along hdf5 file, e.g. `parameters.mobiles.cars`. :param start_hdf5_group: HDF5 group from where to start, leave `None` for the trajectory group. :return:...
358,771
def init(self): if not self.enabled: logger.info(" the module is disabled.") return True try: connections = self.test_connection() except Exception as exp: logger.error("initialization, test connection failed. Error: %s", str(exp)) ...
Called by the daemon broker to initialize the module
358,772
def dispatch_message(self, message_type, client_id, client_storage, args, kwargs): logger.debug("Backend message ({message_type}) : {args} {kwargs}".format( message_type=dict(MESSAGES_TYPES)[message_type], args=args, kwargs=kwargs)) if message_type in [ON_OPEN, ON_CLOSE, ON_RECEIVE...
Calls callback functions
358,773
def main(*args, **kwargs): parser = argparse.ArgumentParser() parser.add_argument(, type=str) parser.add_argument(, type=str) parsed_args = parser.parse_args() get_all_requires(parsed_args.package_name) json_file = open(parsed_args.output_filename, ) json_file.write(json.d...
Simple entry-point that takes the package name and json output
358,774
def add_experiment_choice(experiment, choice): redis = oz.redis.create_connection() oz.bandit.Experiment(redis, experiment).add_choice(choice)
Adds an experiment choice
358,775
def reconnect(self): conn = _mysql.connect(**self._db_args) if conn is not None: self.close() self._db = conn
Closes the existing database connection and re-opens it.
358,776
def call(method, path, ret_type, ret_is_list=False, data=None, params=None, api_version=1): check_api_version(method.im_self, api_version) if data is not None: data = json.dumps(Attr(is_api_list=True).to_json(data, False)) ret = method(path, data=data, params=params) else: ret = method(path, pa...
Generic function for calling a resource method and automatically dealing with serialization of parameters and deserialization of return values. @param method: method to call (must be bound to a resource; e.g., "resource_root.get"). @param path: the full path of the API method to call. @param r...
358,777
def random_codons(peptide, frequency_cutoff=0.0, weighted=False, table=None): sc if table is None: table = CODON_FREQ_BY_AA[] new_table = _cutoff(table, frequency_cutoff) rna = for amino_acid in str(peptide): codons = new_table[amino_acid.upper()] if not codons: ...
Generate randomized codons given a peptide sequence. :param peptide: Peptide sequence for which to generate randomized codons. :type peptide: coral.Peptide :param frequency_cutoff: Relative codon usage cutoff - codons that are rarer will not be used. Frequen...
358,778
def wrap_deepmind_retro(env, scale=True, frame_stack=4): env = WarpFrame(env) env = ClipRewardEnv(env) if frame_stack > 1: env = FrameStack(env, frame_stack) if scale: env = ScaledFloatFrame(env) return env
Configure environment for retro games, using config similar to DeepMind-style Atari in wrap_deepmind
358,779
def build_unit_name(dimensions): name = for unit in dimensions: if unit[] < 0: name += power = abs(unit[]) if power == 1: name += unit[] elif power == 2: name += + unit[] elif power == 3: name += + unit[] e...
Build the name of the unit from its dimensions.
358,780
def parameter(self): D = {} for source in PARAM_SOURCE_ORDER: D.update(self.params[source]) return D
Return the current best value of a parameter
358,781
def pos_tokenize(self: object, fileids: str): for para in self.paras(fileids): yield [ self.pos_tagger(word_tokenize(sent)) for sent in sent_tokenize(para) ]
Segments, tokenizes, and POS tag a document in the corpus.
358,782
def mk_dict(results,description): rows=[] for row in results: row_dict={} for idx in range(len(row)): col=description[idx][0] row_dict[col]=row[idx] rows.append(row_dict) return rows
Given a result list and descrition sequence, return a list of dictionaries
358,783
def prepend_dataset_with_weather(samples, location=, weather_columns=None, use_cache=True, verbosity=0): if verbosity > 1: print(.format(weather_columns)) if not weather_columns: return samples timestamps = pd.DatetimeIndex([s[].index[0] for s in samples]) years = range(timestamps.m...
Prepend weather the values specified (e.g. Max TempF) to the samples[0..N]['input'] vectors samples[0..N]['target'] should have an index with the date timestamp If you use_cache for the curent year, you may not get the most recent data. Arguments: samples (list of dict): {'input': np.array(), 'ta...
358,784
def sfs(dac, n=None): dac, n = _check_dac_n(dac, n) dac = dac.astype(int, copy=False) x = n + 1 s = np.bincount(dac, minlength=x) return s
Compute the site frequency spectrum given derived allele counts at a set of biallelic variants. Parameters ---------- dac : array_like, int, shape (n_variants,) Array of derived allele counts. n : int, optional The total number of chromosomes called. Returns ------- sfs...
358,785
def explore_show_head(self, uri, check_headers=None): print("HEAD %s" % (uri)) if (re.match(r, uri)): response = requests.head(uri) else: response = self.head_on_file(uri) print(" status: %s" % (response.status_code)) if...
Do HEAD on uri and show infomation. Will also check headers against any values specified in check_headers.
358,786
def shrink(self, src, width=0, max_value=0, filter_method=None, path=None, flags=0): if filter_method: get_ = _madoka.Sketch_get__ set_ = _madoka.Sketch_set__ new_sketch = Sketch(width, max_value, path, flags, src.seed) for table_id in rang...
Shrink sketch Params: <Sketch> src_sketch <int> width <int> max_value <lambda> | <function> filter <str> path <int> flags
358,787
def line_received(self, line): self._received_lines += 1 self.loop.create_task(self._inform_watchdog()) pattern = r msg = re.match(pattern, line) if msg: src, mtype, mid, msb, lsb = self._dissect_msg(msg) if lsb is not None: self._...
Gets called by data_received() when a complete line is received. Inspect the received line and process or queue accordingly.
358,788
def _get_po_paths(locales=[]): basedirs = [os.path.join(, ), ] if os.environ.get(): from django.conf import settings basedirs.extend(settings.LOCALE_PATHS) basedirs = set(map(os.path.abspath, filter(os.path.isdir, basedirs))) if not basedirs: raise CommandError("This ...
Returns paths to all relevant po files in the current project.
358,789
def to_java_rdd(jsc, features, labels, batch_size): data_sets = java_classes.ArrayList() num_batches = int(len(features) / batch_size) for i in range(num_batches): xi = ndarray(features[:batch_size].copy()) yi = ndarray(labels[:batch_size].copy()) data_set = java_classes.DataSet...
Convert numpy features and labels into a JavaRDD of DL4J DataSet type. :param jsc: JavaSparkContext from pyjnius :param features: numpy array with features :param labels: numpy array with labels: :return: JavaRDD<DataSet>
358,790
def controls(self, move): to_move = self.board.turn analysis_board = chess.Board(self.board.fen()) analysis_board.push(move) squares = 0 for square in chess.SQUARES: if move.to_square in analysis_board.attackers(to_move, square): squares |= chess.BB_SQUARES[square] return Squa...
Returns a set of attacked/defended squares
358,791
def next(self): while True: x, y = next(self.scan) if self.predicate is not None and not self.predicate(x,y): if self.abort: raise StopIteration("Boundary crossed!") elif (x < self.minx or x > self.maxx or y < self.miny...
Next point in iteration
358,792
def iterations(self, parameter): return numpy.arange(0, self.last_iteration(parameter), self.thinned_by)
Returns the iteration each sample occurred at.
358,793
def _apply_concretization_strategies(self, idx, strategies, action): for s in strategies: try: idxes = s.concretize(self, idx) except SimUnsatError: idxes = None if idxes: return idxes raise SimMemoryAddress...
Applies concretization strategies on the index, until one of them succeeds.
358,794
def _offset_dt(cls, dt, offset_str): match = cls._offset_pattern.match(offset_str) if match is None: raise ValueError( " is not a valid offset string" % offset_str ) sign, hours_str, minutes_str = match.groups() sign_factor = -1 if sign ==...
Return a |datetime| instance that is offset from datetime *dt* by the timezone offset specified in *offset_str*, a string like ``'-07:00'``.
358,795
def parse_disruptions(self, xml): obj = xmltodict.parse(xml) disruptions = {} disruptions[] = [] disruptions[] = [] if obj[][]: raw_disruptions = obj[][][] if isinstance(raw_disruptions, collections.OrderedDict): raw_disruptions =...
Parse the NS API xml result into Disruption objects @param xml: raw XML result from the NS API
358,796
def difference_update(self, *sets): items_to_remove = set() for other in sets: items_to_remove |= set(other) self._update_items([item for item in self.items if item not in items_to_remove])
Update this OrderedSet to remove items from one or more other sets. Example: >>> this = OrderedSet([1, 2, 3]) >>> this.difference_update(OrderedSet([2, 4])) >>> print(this) OrderedSet([1, 3]) >>> this = OrderedSet([1, 2, 3, 4, 5]) >>> thi...
358,797
def _readline(self, prompt=, callback=None): if self._reading: raise RuntimeError() if not callback and not self.isVisible(): raise RuntimeError( ) self._reading = True self._show_prompt(prompt, newline=False)...
Reads one line of input from the user. Parameters ---------- prompt : str, optional The prompt to print before reading the line. callback : callable, optional A callback to execute with the read line. If not specified, input is read *synchronously* a...
358,798
def link_user_account(self, user_id, body): url = self._url(.format(user_id)) return self.client.post(url, data=body)
Link user accounts. Links the account specified in the body (secondary account) to the account specified by the id param of the URL (primary account). Args: id (str): The user_id of the primary identity where you are linking the secondary account to. bo...
358,799
def createsuperusers(): from django.contrib.auth import models as auth_models from django.conf import settings from django.core.mail import send_mail from django.contrib.sites import models as site_models import uuid from django.db import transaction from django.db.models import Q ...
Creates all superusers defined in settings.INITIAL_SUPERUSERS. These superusers do not have any circles. They are plain superusers. However you may want to signup yourself and make this new user a super user then.