Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
338,700
def git_exec(self, command, **kwargs): from .cli import verbose_echo command.insert(0, self.git) if kwargs.pop(, False): return result
Execute git commands
338,701
def build(self, shutit): if shutit.build[] in (,): if shutit.get_current_shutit_pexpect_session_environment().install_type == : shutit.add_to_bashrc() if not shutit.command_available(): shutit.install() shutit.lsb_release() elif shutit.get_current_shutit_pexpect_session_environment().install...
Initializes target ready for build and updating package management if in container.
338,702
def eval_components(self, *args, **kwargs): bound_arguments = self.__signature__.bind(*args, **kwargs) kwargs = bound_arguments.arguments components = dict(zip(self, self.numerical_components)) for symbol in self.ordered_symbols: if symbol.name not in kwar...
:return: evaluated lambda functions of each of the components in model_dict, to be used in numerical calculation.
338,703
def _domain_event_job_completed_cb(conn, domain, params, opaque): _salt_send_domain_event(opaque, conn, domain, opaque[], { : params })
Domain job completion events handler
338,704
def within_airport( self, start: timelike, stop: timelike, airport: Union[Airport, str], count: bool = False, ) -> Optional[pd.DataFrame]: start = to_datetime(start) stop = to_datetime(stop) before_hour = round_time(start, how="before") ...
EXPERIMENTAL.
338,705
async def train(state, tf_records): model_path = os.path.join(fsdb.models_dir(), state.train_model_name) await run( , , *tf_records, .format(os.path.join(FLAGS.flags_dir, )), .format(fsdb.working_dir()), .format(model_path), .format(state.seed), ) elapsed = time.time(...
Run training and write a new model to the fsdb models_dir. Args: state: the RL loop State instance. tf_records: a list of paths to TensorFlow records to train on.
338,706
def _build_url(self): self.connection["upload_url"] = ( "%s/%s" % (self.connection["jss"].base_url, "dbfileupload")) self.connection["delete_url"] = ( "%s/%s" % (self.connection["jss"].base_url, "casperAdminSave.jxml"))
Build the URL for POSTing files.
338,707
def add_from_file(self, fpath): if self.tree is None: base, name = os.path.split(fpath) self.add_resource_path(base) self.tree = tree = ET.parse(fpath) self.root = tree.getroot() self.objects = {} else: pass
Load ui definition from file.
338,708
def deactivate(): if not in os.environ or not in os.environ: raise EnvironmentError() utils.restore_env_from_file(os.environ[])
Deactivates an environment by restoring all env vars to a clean state stored prior to activating environments
338,709
def add_ellipsoid(self, x0, radii, lcar=None, with_volume=True, holes=None): if holes is None: holes = [] if holes: assert with_volume p = [ self.add_point(x0, lcar=lcar), self.add_point([x0[0] + radii[0], x0[1], x0[2]], lcar=lc...
Creates an ellipsoid with radii around a given midpoint :math:`x_0`.
338,710
def update(self, client): update_cmd = "{sudo} ".format( sudo=self.get_sudo_exec_wrapper(), refresh=self.get_refresh_repo_cmd(), update=self.get_update_cmd() ) out = try: out = ipa_utils.execute_ssh_command( clien...
Execute update command on instance.
338,711
def tag(self, utterance, context_trie=None): tokens = self.tokenizer.tokenize(utterance) entities = [] if len(self.regex_entities) > 0: for part, idx in self._iterate_subsequences(tokens): local_trie = Trie() for regex_entity in self.regex_ent...
Tag known entities within the utterance. Args: utterance(str): a string of natural language text context_trie(trie): optional, a trie containing only entities from context for this request Returns: dictionary, with the following keys match(str): the p...
338,712
def make_github_blueprint( client_id=None, client_secret=None, scope=None, redirect_url=None, redirect_to=None, login_url=None, authorized_url=None, session_class=None, storage=None, ): github_bp = OAuth2ConsumerBlueprint( "github", __name__, client_i...
Make a blueprint for authenticating with GitHub using OAuth 2. This requires a client ID and client secret from GitHub. You should either pass them to this constructor, or make sure that your Flask application config defines them, using the variables :envvar:`GITHUB_OAUTH_CLIENT_ID` and :envvar:`GITHUB_...
338,713
def create(cls, result_id=None, summary=None, file_modified_at=None): asset = cls(result_id, summary, file_modified_at) db.session.add(asset) db.session.commit() return asset
Initialize an instance and save it to db.
338,714
def run(self): workspace = self.workflow.plugin_workspace.get(self.key, {}) cf_maps_to_remove = workspace.get(, []) for cm_key, osbs in cf_maps_to_remove: try: osbs.delete_config_map(cm_key) self.log.debug("ConfigMap %s deleted", cm_key) ...
Run the plugin.
338,715
def extract(self, point_x, point_y, radius=0): row, col = map_pixel(point_x, point_y, self.x_cell_size, self.y_cell_size, self.xmin, self.ymax) col2 = np.abs(radius/self.x_cell_size).astype(int) row2 = np.abs(radius/self.y_cell_size).astype(int) retu...
geo.extract(x, y, radius=r) Return subraster of raster geo around location (x,y) with radius r where (x,y) and r are in the same coordinate system as geo
338,716
def assert_datasource_protocol(event): assert event.type in DATASOURCE_TYPE if not event.type == DATASOURCE_TYPE.DONE: assert isinstance(event.dt, datetime) assert event.dt.tzinfo == pytz.utc
Assert that an event meets the protocol for datasource outputs.
338,717
def debug(module, name, pm=False): module = _normalize_module(module) testsrc = testsource(module, name) debug_script(testsrc, pm, module.__dict__)
Debug a single doctest docstring. Provide the module (or dotted name of the module) containing the test to be debugged and the name (within the module) of the object with the docstring with tests to be debugged.
338,718
def load_settings(file_path, module_name=, secret_key=): title = try: _path_arg = % (title, str(file_path)) except: raise ValueError( % title) from os import path if module_name: try: _path_arg = _path_arg.replace(, % str(module_name)) ...
a method to load data from json valid files :param file_path: string with path to settings file :param module_name: [optional] string with name of module containing file path :param secret_key: [optional] string with key to decrypt drep file :return: dictionary with settings data
338,719
def _set_udld(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=udld.udld, is_container=, presence=False, yang_name="udld", rest_name="udld", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u: {u...
Setter method for udld, mapped from YANG variable /interface/hundredgigabitethernet/udld (container) If this variable is read-only (config: false) in the source YANG file, then _set_udld is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_u...
338,720
def print_saveframe(self, sf, f=sys.stdout, file_format="nmrstar", tw=3): if file_format == "nmrstar": for sftag in self[sf].keys(): if sftag[:5] == "loop_": print(u"\n{}loop_".format(tw * u" "), file=f) self.print_loo...
Print saveframe into a file or stdout. We need to keep track of how far over everything is tabbed. The "tab width" variable tw does this for us. :param str sf: Saveframe name. :param io.StringIO f: writable file-like stream. :param str file_format: Format to use: `nmrstar` or `j...
338,721
async def abort(self): state = await self.state() res = await self.call("X_Abort", MasterSessionID=state.MasterSessionID) return res
Abort current group session.
338,722
def __convert_string_type(self, p_c_tuple): if not isinstance(p_c_tuple, tuple): raise Exception(.format(p_c_tuple)) converted = [text_type] * len(p_c_tuple) for i, pos_element in enumerate(p_c_tuple): if six.PY2 and isinstance(pos_element, str): ...
* What you can do - it normalizes string types into str
338,723
def parseMalformedBamHeader(headerDict): headerString = " ".join( "{}:{}".format(k, v) for k, v in headerDict.items() if k != ) ret = {} for item in headerString.split(): key, value = item.split(":", 1) ret[key] = type(headerDict.get(key, ""))(value) if in headerDi...
Parses the (probably) intended values out of the specified BAM header dictionary, which is incompletely parsed by pysam. This is caused by some tools incorrectly using spaces instead of tabs as a seperator.
338,724
def create(input, template, field, outdir, prefix, otype, command, index, dpi, verbose, unicode_support): logging.basicConfig(level=LOGGING_LVL) log = logging.getLogger(__name__) verbose_switch(verbose) input_file = input fields = field log.debug(.format(input_file))...
Use docstamp to create documents from the content of a CSV file or a Google Spreadsheet. Examples: \n docstamp create -i badge.csv -t badge_template.svg -o badges docstamp create -i badge.csv -t badge_template.svg -o ./badges -d pdf
338,725
def ar1(rho, mu, sigma, size=1): return np.array([x for x in ar1_gen(rho, mu, sigma, size)])
Return an autoregressive series of order one AR(1). .. math:: X_t = \mu_t + \rho (X_{t-1}-\mu_{t-1} + \epsilon_t If mu is a sequence and size > len(mu), the algorithm loops through mu. :Stochastics: rho : scalar in [0,1] mu : scalar or sequence sigma : scalar > 0 ...
338,726
def get_currencies_info() -> Element: response = requests.get(const.CBRF_API_URLS[]) return XML(response.text)
Get META information about currencies url: http://www.cbr.ru/scripts/XML_val.asp :return: :class: `Element <Element 'Valuta'>` object :rtype: ElementTree.Element
338,727
def get_zname(self, var, coords=None): if coords is not None: coord = self.get_variable_by_axis(var, , coords) if coord is not None and coord.name in var.dims: return coord.name dimlist = list(self.z.intersection(var.dims)) if dimlist: ...
Get the name of the z-dimension This method gives the name of the z-dimension (which is not necessarily the name of the coordinate if the variable has a coordinate attribute) Parameters ---------- var: xarray.Variables The variable to get the dimension for c...
338,728
def coords(obj): if in obj: for f in obj[]: for c in coords(f): yield c else: if isinstance(obj, (tuple, list)): coordinates = obj elif in obj: coordinates = obj[][] else: coordi...
Yields the coordinates from a Feature or Geometry. :param obj: A geometry or feature to extract the coordinates from. :type obj: Feature, Geometry :return: A generator with coordinate tuples from the geometry or feature. :rtype: generator
338,729
def set_modulations(self, dimension, phonon_modes, delta_q=None, derivative_order=None, nac_q_direction=None): if self._dynamical_matrix is None: msg = ("Dynamical matrix ...
Generate atomic displacements of phonon modes. The design of this feature is not very satisfactory, and thus API. Therefore it should be reconsidered someday in the fugure. Parameters ---------- dimension : array_like Supercell dimension with respect to the primitive...
338,730
def _match(self, regex): cregex = re.compile(regex) for line in self.content.splitlines(): match = cregex.match(line) if match: return match raise Exception(.format( regex_to_error_msg(regex), self.name ))
Find the first line matching regex and return the match object
338,731
def threaded_start(self, no_init=False): thread = Thread(target=self.init_connections, kwargs={ : no_init}) thread.setDaemon(True) thread.start() thread.join()
Spawns a worker thread to set up the zookeeper connection
338,732
def decode_jwt(encoded_token, secret, algorithm, identity_claim_key, user_claims_key, csrf_value=None, audience=None, leeway=0, allow_expired=False): options = {} if allow_expired: options[] = False data = jwt.decode(encoded_token, secret, algorithms=[algorit...
Decodes an encoded JWT :param encoded_token: The encoded JWT string to decode :param secret: Secret key used to encode the JWT :param algorithm: Algorithm used to encode the JWT :param identity_claim_key: expected key that contains the identity :param user_claims_key: expected key that contains the...
338,733
def _insert(self, trigram): words = list(map(self._sanitize, trigram)) key = self._WSEP.join(words[:2]).lower() next_word = words[2] self._db.setdefault(key, []) if next_word not in self._db[key]: self._db[key].append(next_word)
Insert a trigram in the DB
338,734
def ungroupslice(groups,gslice): eltsbefore=0 for i in range(gslice[0]): eltsbefore+=len(groups[i])-1 x=eltsbefore+gslice[1]; return [x-1,x+gslice[2]-1]
this is a helper for contigsub.
338,735
def resumable(self): d previously been working onjobsll filter out all the jobs that arenre working on. queue_names = set([queue.name for queue in self.queues]) return [job for job in jobs if job.queue_name in queue_names]
Find all the jobs that we'd previously been working on
338,736
def createSections(self): self.soma = h.Section(name=, cell=self) self.dend = h.Section(name=, cell=self)
Create the sections of the cell.
338,737
def is_addable(self, device, automount=True): if not self.is_automount(device, automount): return False if device.is_filesystem: return not device.is_mounted if device.is_crypto: return self._prompt and not device.is_unlocked if device.is_part...
Check if device can be added with ``auto_add``.
338,738
def to_funset(self): fs = set() for i, n in self.nodes.iteritems(): fs.add(gringo.Fun(, [n, i])) for j, i in self.hyper.iteritems(): fs.add(gringo.Fun(, [i, j, len(self.edges[self.edges.hyper_idx == j])])) for j, v, s in self.edges.itertuples(index=Fals...
Converts the hypergraph to a set of `gringo.Fun`_ instances Returns ------- set Representation of the hypergraph as a set of `gringo.Fun`_ instances .. _gringo.Fun: http://potassco.sourceforge.net/gringo.html#Fun
338,739
def calculate_maximum_diameter(self): self.maxd_atom_1, self.maxd_atom_2, self.maximum_diameter = max_dim( self.elements, self.coordinates) self.properties[] = { : self.maximum_diameter, : int(self.maxd_atom_1), : int(self.maxd_atom_2), } ...
Return the maximum diamension of a molecule. Returns ------- :class:`float` The maximum dimension of the molecule.
338,740
def add_resource(self, resource): updated_sentence = NeedsProfile.format_sentence( resource[], resource) if self.edit_item: item = self.edit_item item.setText(updated_sentence) self.edit_item = None else: item = QtWidgets.QList...
Add a resource to the minimum needs table. :param resource: The resource to be added :type resource: dict
338,741
def load_object(obj) -> object: if isinstance(obj, str): if in obj: module_name, obj_name = obj.split() if not module_name: module_name = else: module_name = obj obj = importlib.import_module(module_name) if obj_name: ...
Load an object. Args: obj (str|object): Load the indicated object if this is a string; otherwise, return the object as is. To load a module, pass a dotted path like 'package.module'; to load an an object from a module pass a path like 'package.module:name'. ...
338,742
def _lmder1_linear_full_rank(n, m, factor, target_fnorm1, target_fnorm2): def func(params, vec): s = params.sum() temp = 2. * s / m + 1 vec[:] = -temp vec[:params.size] += params def jac(params, jac): jac.fill(-2. / m) for i in range(n): ...
A full-rank linear function (lmder test #1)
338,743
def GetParentFileEntry(self): location = getattr(self.path_spec, , None) if location is None: return None parent_location = self._file_system.DirnamePath(location) if parent_location is None: return None if parent_location == : parent_location = self._file_system.PATH_SEPARA...
Retrieves the root file entry. Returns: FakeFileEntry: parent file entry or None if not available.
338,744
def _getcallargs(func, positional, named): args, varargs, varkw, defaults = inspect.getargspec(func) f_name = func.__name__ arg2value = {} assigned_tuple_params = [] def assign(arg, value): if isinstance(arg, str): arg2value[arg] = value else: ...
Get the mapping of arguments to values. Generates a dict, with keys being the function argument names (including the names of the * and ** arguments, if any), and values the respective bound values from 'positional' and 'named'. A parameter for the request is injected. Returns a tuple of the dict,...
338,745
def predict_proba(self, X): X = self._check_array(X) self._check_method("predict_proba") if isinstance(X, da.Array): return X.map_blocks( _predict_proba, estimator=self._postfit_estimator, dtype="float", ...
Probability estimates. For dask inputs, a dask array or dataframe is returned. For other inputs (NumPy array, pandas dataframe, scipy sparse matrix), the regular return value is returned. If the underlying estimator does not have a ``predict_proba`` method, then an ``AttributeE...
338,746
def _error_msg_network(option, expected): msg = return msg.format(option, .join(str(e) for e in expected))
Build an appropriate error message from a given option and a list of expected values.
338,747
def reject_user_timesheet(request, user_id): form = YearMonthForm(request.GET or request.POST) user = User.objects.get(pk=user_id) if form.is_valid(): from_date, to_date = form.save() entries = Entry.no_join.filter( status=Entry.VERIFIED, user=user, start_time__gte=from_date...
This allows admins to reject all entries, instead of just one
338,748
def add_capability(base, *classes): if _debug: add_capability._debug("add_capability %r %r", base, classes) if not issubclass(base, Collector): raise TypeError("base must be a subclass of Collector") for cls in classes: if not issubclass(cls, Capability): raise T...
Add capabilites to an existing base, all objects get the additional functionality, but don't get inited. Use with great care!
338,749
def delete_notebook_id(self, notebook_id): name = self.mapping[notebook_id] del self.mapping[notebook_id] del self.rev_mapping[name]
Delete a notebook's id only. This doesn't delete the actual notebook.
338,750
def canonical(self): Ac1 = np.hstack((self.deltah, np.zeros((self.nh, self.nz)))) Ac2 = np.hstack((np.zeros((self.nz, self.nh)), self.a22)) Ac = np.vstack((Ac1, Ac2)) Bc = np.vstack((self.thetah, np.zeros((self.nz, self.nc)))) Cc = np.vstack((np.zeros((self.nh, self.nw))...
Compute canonical preference representation Uses auxiliary problem of 9.4.2, with the preference shock process reintroduced Calculates pihat, llambdahat and ubhat for the equivalent canonical household technology
338,751
def can_share_folder(self, user, folder): return folder.parent_id is None and folder.author_id == user.id
Return True if `user` can share `folder`.
338,752
def check_output(*args, **kwargs): if hasattr(subprocess, ): return subprocess.check_output(stderr=subprocess.STDOUT, universal_newlines=True, *args, **kwargs) else: process = subprocess.Popen(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ...
Compatibility wrapper for Python 2.6 missin g subprocess.check_output
338,753
def create_token(self, token_name, project_name, dataset_name, is_public): url = self.url() + .format( dataset_name) + .format(project_name) + \ .format(token_name) json = { ...
Creates a token with the given parameters. Arguments: project_name (str): Project name dataset_name (str): Dataset name project is based on token_name (str): Token name is_public (int): 1 is public. 0 is not public Returns: bool: True if projec...
338,754
def _read_config_file(self): try: with open(self.config, ) as f: config_data = json.load(f) except FileNotFoundError: config_data = {} return config_data
read in the configuration file, a json file defined at self.config
338,755
def dump(src): return b.join(binascii.hexlify(bytes(x)) for x in zip(src[::4], src[1::4], src[2::4], src[3::4]))
Returns data in hex format in groups of 4 octets delimited by spaces for debugging purposes.
338,756
def document_scale(cls): params_list = [] cls_param_string = docstring_parameters_section(cls) cls_param_dict = parameters_str_to_dict(cls_param_string) cls_params = set(cls_param_dict.keys()) for i, base in enumerate(cls.__bases__): base_param_string = param_string = doc...
Create a documentation for a scale Import the superclass parameters It replaces `{superclass_parameters}` with the documentation of the parameters from the superclass. Parameters ---------- cls : type A scale class Returns ------- cls : type The scale class with a...
338,757
def run_dcos_command(command, raise_on_error=False, print_output=True): call = shlex.split(command) call.insert(0, ) print("\n{}{}\n".format(shakedown.fchr(), .join(call))) proc = subprocess.Popen(call, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = proc.communicate() re...
Run `dcos {command}` via DC/OS CLI :param command: the command to execute :type command: str :param raise_on_error: whether to raise a DCOSException if the return code is nonzero :type raise_on_error: bool :param print_output: whether to print the resulting stdout/stderr from ru...
338,758
def _tab_complete_init(items, post_prompt, insensitive, fuzzy, stream): Get a valid match, given: text - the portion of text currently trying to complete state - the index 0..inf which is an index into the list of valid matches. Put another way, given t...
Create and use a tab-completer object
338,759
def encode_images_as_png(images): if tf.executing_eagerly(): for image in images: yield tf.image.encode_png(image).numpy() else: (height, width, channels) = images[0].shape with tf.Graph().as_default(): image_t = tf.placeholder(dtype=tf.uint8, shape=(height, width, channels)) encode...
Yield images encoded as pngs.
338,760
def default_external_files_dir_name(model_name): name, ext = os.path.splitext(model_name) return name + CONF.external_files_suffix
Parameters ---------- model_name: with or without extension
338,761
def Handle_Search(self, msg): search_term = msg[][] results = self.db.searchForItem(search_term) reply = {"status": "OK", "type": "search", "object": { "received search": msg[][], "results": result...
Handle a search. :param msg: the received search :type msg: dict :returns: The message to reply with :rtype: str
338,762
def image_list_detailed(request, marker=None, sort_dir=, sort_key=, filters=None, paginate=False, reversed_order=False, **kwargs): limit = getattr(settings, , 1000) page_size = utils.get_page_size(request) if paginate: request_size = page_size + ...
Thin layer above glanceclient, for handling pagination issues. It provides iterating both forward and backward on top of ascetic OpenStack pagination API - which natively supports only iterating forward through the entries. Thus in order to retrieve list of objects at previous page, a request with the ...
338,763
def _scalar_coef_op_left(func): @wraps(func) def verif(self, scoef): if isinstance(scoef, ScalarCoefs): if len(self._vec) == len(scoef._vec): return ScalarCoefs(func(self, self._vec, scoef._vec), self...
decorator for operator overloading when ScalarCoef is on the left
338,764
def get_gateway_info(self): def process_result(result): return GatewayInfo(result) return Command(, [ROOT_GATEWAY, ATTR_GATEWAY_INFO], process_result=process_result)
Return the gateway info. Returns a Command.
338,765
def to_ele(x): "Convert and return the :class:`~xml.etree.ElementTree.Element` for the XML document *x*. If *x* is already an :class:`~xml.etree.ElementTree.Element` simply returns that." if sys.version < : return x if etree.iselement(x) else etree.fromstring(x, parser=parser) else: return x...
Convert and return the :class:`~xml.etree.ElementTree.Element` for the XML document *x*. If *x* is already an :class:`~xml.etree.ElementTree.Element` simply returns that.
338,766
def MGMT_ACTIVE_GET(self, Addr=, TLVs=[]): print % self.port try: cmd = WPANCTL_CMD + if len(TLVs) != 0: tlvs = "".join(hex(tlv).lstrip("0x").zfill(2) for tlv in TLVs) setTLVCmd = WPANCTL_CMD + + tlvs if self.__sendCom...
send MGMT_ACTIVE_GET command Returns: True: successful to send MGMT_ACTIVE_GET False: fail to send MGMT_ACTIVE_GET
338,767
def find_time_base(self, gps, first_ms_stamp): t = self._gpsTimeToTime(gps.Week, gps.TimeMS) self.set_timebase(t - gps.T*0.001) self.timestamp = self.timebase + first_ms_stamp*0.001
work out time basis for the log - new style
338,768
def on_signout_action_activated(self, action, params): if self.profile: self.upload_page.pause_tasks() self.download_page.pause_tasks() self.show_signin_dialog(auto_signin=False)
在退出登录前, 应该保存当前用户的所有数据
338,769
def AgregarRetencion(self, cod_retencion, descripcion, importe, **kwargs): "Agrega la información referente a las retenciones de la liquidación" ret = dict(codRetencion=cod_retencion, descripcion=descripcion, importe=importe) self.solicitud[].append(ret) return True
Agrega la información referente a las retenciones de la liquidación
338,770
async def identify(self): payload = { : self.IDENTIFY, : { : self.token, : { : sys.platform, : , : , : , : }, : Tr...
Sends the IDENTIFY packet.
338,771
def get_media_urls(tweet): media = get_media_entities(tweet) urls = [m.get("media_url_https") for m in media] if media else [] return urls
Gets the https links to each media entity in the tweet. Args: tweet (Tweet or dict): tweet Returns: list: list of urls. Will be an empty list if there are no urls present. Example: >>> from tweet_parser.getter_methods.tweet_entities import get_media_urls >>> tweet = {'crea...
338,772
def eval_policy(eval_positions): model_paths = oneoff_utils.get_model_paths(fsdb.models_dir()) idx_start = FLAGS.idx_start eval_every = FLAGS.eval_every print("Evaluating models {}-{}, eval_every={}".format( idx_start, len(model_paths), eval_every)) player = None for i, idx in...
Evaluate all positions with all models save the policy heatmaps as CSVs CSV name is "heatmap-<position_name>-<model-index>.csv" CSV format is: model number, value network output, policy network outputs position_name is taken from the SGF file Policy network outputs (19x19) are saved in flat order (see...
338,773
def send_keys(self, text: str = ) -> None: self.click() self._parent.send_keys(text)
Simulates typing keys.
338,774
def lsmod(self): lines = shell_out("lsmod", timeout=0).splitlines() return [line.split()[0].strip() for line in lines]
Return a list of kernel module names as strings.
338,775
def from_file(cls, fp, storage=None): if storage is None: storage = cls.DEFAULT_STORAGE return cls.from_storage(storage.load(fp))
Load from file. Parameters ---------- fp : `str` or `file` File or path. storage : `type`, optional Storage class (default: cls.DEFAULT_STORAGE) Returns ------- `markovchain.Markov`
338,776
def isgenerator(obj): return isinstance(obj, GeneratorType) or (hasattr(obj, ) and isinstance(getattr(obj, ), GeneratorType))
Returns True if object is a generator, or a generator wrapped by a tqdm object.
338,777
def run(): args = client_helper.grab_server_args() workbench = zerorpc.Client(timeout=300, heartbeat=60) workbench.connect(+args[]++args[]) data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),) file_list = [os.path.join(data_path, child) for child in os.li...
This client shows workbench extacting files from a zip file.
338,778
def archive(self, output_path): if self.path is None: raise ArgumentError("Cannot archive a recipe yet without a reference to its original yaml file in self.path") outfile = zipfile.ZipFile(output_path, , zipfile.ZIP_DEFLATED) outfile.write(self.path, arcname="recipe_scri...
Archive this recipe and all associated files into a .ship archive. Args: output_path (str): The path where the .ship file should be saved.
338,779
def start(self): if self.num_workers: self.queue = Queue(maxsize=self.num_workers) self.workers = [_Worker(self) for _ in range(self.num_workers)] for worker in self.workers: worker.start() self.running = True
Start the workers.
338,780
def first_kwonly_arg(name): def decorate(wrapped): if sys.version_info[0] == 2: arg_names, varargs, _, defaults = inspect.getargspec(wrapped) else: arg_names, varargs, _, defaults = inspect.getfullargspec(wrapped)[:4] if not defaults: raise TypeError...
Emulates keyword-only arguments under python2. Works with both python2 and python3. With this decorator you can convert all or some of the default arguments of your function into kwonly arguments. Use ``KWONLY_REQUIRED`` as the default value of required kwonly args. :param name: The name of the first defau...
338,781
def location(value): try: location = geoip() and geoip().city(value) except Exception: try: location = geoip() and geoip().country(value) except Exception as e: warnings.warn(str(e)) location = None if location and location[]: if in l...
Transform an IP address into an approximate location. Example output: * Zwolle, The Netherlands * The Netherlands * None
338,782
def context(self): }
Build the interpolation context from the schemas
338,783
def firstChild(hot_map, index): children = hot_map[index][2] if children: return children[0][1] else: return hot_map[index][1]
Return the first child of the node indicated by index.
338,784
def simulate_custom_policy(PolicyInputList=None, ActionNames=None, ResourceArns=None, ResourcePolicy=None, ResourceOwner=None, CallerArn=None, ContextEntries=None, ResourceHandlingOption=None, MaxItems=None, Marker=None): pass
Simulate how a set of IAM policies and optionally a resource-based policy works with a list of API actions and AWS resources to determine the policies' effective permissions. The policies are provided as strings. The simulation does not perform the API actions; it only checks the authorization to determine if the s...
338,785
def endBy(p, sep): return separated(p, sep, 0, maxt=float(), end=True)
`endBy(p, sep)` parses zero or more occurrences of `p`, separated and ended by `sep`. Returns a list of values returned by `p`.
338,786
def chimera_view(*molecules): try: import nglview as nv except ImportError: raise ImportError() import chimera class _ChimeraStructure(nv.Structure): def __init__(self, *molecules): if not molecules: raise ValueError() self.ext = "pdb...
Depicts the requested molecules with NGLViewer in a Python notebook. This method does not require a headless Chimera build, however. Parameters ---------- molecules : tuple of chimera.Molecule Molecules to display. If none is given, all present molecules in Chimera canvas will be displa...
338,787
def linear_color_map(values, color_range=None): if color_range is None: color_range = np.array([[255, 0, 0, 255], [0, 255, 0, 255]], dtype=np.uint8) else: color_range = np.asanyarray(color_range, ...
Linearly interpolate between two colors. If colors are not specified the function will interpolate between 0.0 values as red and 1.0 as green. Parameters -------------- values : (n, ) float Values to interpolate color_range : None, or (2, 4) uint8 What colors should extrema be set...
338,788
def filename_match(fsearch, filename, width, height): fsearch = clean_path(fsearch) filename = clean_path(filename) if fsearch == filename: return True if fsearch.find() == -1: return False basename, fileext = os.path.splitext(fsearch) nickname, extinfo = basename.split(, 1...
<nickname>@({width}x{height}|auto).(png|jpg|jpeg)
338,789
def connect(self, fun): name = fun.__name__ if not name.startswith(): raise ValueError( ) eventname = name[3:] try: emitter = self.events[eventname] except KeyError: raise ValueError( ...
Connect a function to an event The name of the function should be on_X, with X the name of the event (e.g. 'on_draw'). This method is typically used as a decorator on a function definition for an event handler. Parameters ---------- fun : callable T...
338,790
def INDEX_OF_ARRAY(string_expression, substring_expression, start=None, end=None): res = [string_expression, substring_expression] if start is not None: res.append(start) if end is not None: res.append(end) return {: res}
Searches an array for an occurence of a specified value and returns the array index of the first occurence. See https://docs.mongodb.com/manual/reference/operator/aggregation/zip/ for more details :param string_expression: Any valid expression as long as it resolves to an array. :param substring_express...
338,791
def _send_ssh_pub(self, load, ssh_minions=False): if self.opts[] is True and ssh_minions is True: log.debug() threading.Thread(target=self.ssh_client.cmd, kwargs=load).start()
Take a load and send it across the network to ssh minions
338,792
def get_next_entry(file, entrymarker="\xFE\xFF\xFE\xFF\xFE\xFF\xFE\xFF\xFE\xFF", only_coord=True, blocksize=65535): s current cursor position -- this can be used advantageously if you want to read only a specific entry by seeking before supplying the file handle). This will read any string length between two en...
Find or read the next ecc entry in a given ecc file. Call this function multiple times with the same file handle to get subsequent markers positions (this is not a generator but it works very similarly, because it will continue reading from the file's current cursor position -- this can be used advantageously if yo...
338,793
def accept(self, logevent): if self.components and logevent.component not in self.components: return False if self.levels and logevent.level not in self.levels: return False if self.namespaces and logevent.namespace not in self.namespaces: re...
Process line. Overwrite BaseFilter.accept() and return True if the provided logevent should be accepted (causing output), or False if not.
338,794
def explain(self, bindVars={}, allPlans = False) : return self.database.explainAQLQuery(self.query, bindVars, allPlans)
Returns an explanation of the query. Setting allPlans to True will result in ArangoDB returning all possible plans. False returns only the optimal plan
338,795
def sleep_for_rate_limit(self): if self.rate_limit is not None and self.rate_limit <= self.min_rate_to_sleep: seconds_to_reset = self.calculate_time_to_reset() if seconds_to_reset < 0: logger.warning("Value of sleep for rate limit is negative, reset it to 0") ...
The fetching process sleeps until the rate limit is restored or raises a RateLimitError exception if sleep_for_rate flag is disabled.
338,796
def _iter_dimensions(self): return ( Dimension(raw_dimension.dimension_dict, raw_dimension.dimension_type) for raw_dimension in self._raw_dimensions )
Generate Dimension object for each dimension dict.
338,797
def ConstField(name, value, marshal=None): if marshal is None: marshal = value if isinstance(marshal, Struct): marshal = type(marshal) elif not isinstance(marshal, Marshal): raise InstructError("don't know how to serialize const field %s value %s (consider adding a marshal argum...
This macro can be used in several methods: >>> ConstField("foo", 5, UBInt8) This created a constant field called ``foo`` with a value of 5 and is serialized/deserialized using UBInt8. >>> ConstField("foo", MyStruct(my_field=1, my_other_field=2)) This time ``foo`` is set with the ``MyStruct`` instanc...
338,798
def notGroup (states, *stateIndexPairs): start, dead = group(states, *stateIndexPairs) finish = len(states) states.append([]) states[start].append((DEFAULT, finish)) return start, finish
Like group, but will add a DEFAULT transition to a new end state, causing anything in the group to not match by going to a dead state. XXX I think this is right...
338,799
def _average(self): r, g, b, a = 0, 0, 0, 0 for clr in self: r += clr.r g += clr.g b += clr.b a += clr.alpha r /= len(self) g /= len(self) b /= len(self) a /= len(self) return color(r, g, b, a, mode="rgb")
Returns one average color for the colors in the list.