Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
366,600
def set_sys(layout): * if salt.utils.path.which(): __salt__[](.format(layout)) elif in __grains__[]: __salt__[](, , .format(layout)) elif in __grains__[]: __salt__[](, , ...
Set current system keyboard setting CLI Example: .. code-block:: bash salt '*' keyboard.set_sys dvorak
366,601
def _new_err(self, errclass: str, *args) -> : ex, msg = self._get_args(*args) ftb = None function = None errtype = None file = None line = None code = None ex_msg = None caller = None call...
Error constructor
366,602
def load_bot_parameters(config_bundle) -> ConfigObject: python_file = config_bundle.python_file agent_class_wrapper = import_agent(python_file) bot_parameters = agent_class_wrapper.get_loaded_class().base_create_agent_configurations() bot_parameters.parse_file(config_bundle.config_obj, config_...
Initializes the agent in the bundle's python file and asks it to provide its custom configuration object where its parameters can be set. :return: the parameters as a ConfigObject
366,603
def dropna(self, how=, thresh=None, subset=None): if how is not None and how not in [, ]: raise ValueError("how () should be or ") if subset is None: subset = self.columns elif isinstance(subset, basestring): subset = [subset] elif not isins...
Returns a new :class:`DataFrame` omitting rows with null values. :func:`DataFrame.dropna` and :func:`DataFrameNaFunctions.drop` are aliases of each other. :param how: 'any' or 'all'. If 'any', drop a row if it contains any nulls. If 'all', drop a row only if all its values are n...
366,604
def path2edges(path): node_a, node_b = tee(path) next(node_b, None) return zip(node_a, node_b)
Given: [2000343, 32722, 1819] Return: set([(2000343, 32722), (32722, 1819)]).
366,605
async def filterindex(source, func): source = transform.enumerate.raw(source) async with streamcontext(source) as streamer: async for i, item in streamer: if func(i): yield item
Filter an asynchronous sequence using the index of the elements. The given function is synchronous, takes the index as an argument, and returns ``True`` if the corresponding should be forwarded, ``False`` otherwise.
366,606
def list_data_links(self, instance): response = self.get_proto(path= + instance) message = rest_pb2.ListLinkInfoResponse() message.ParseFromString(response.content) links = getattr(message, ) return iter([Link(link) for link in links])
Lists the data links visible to this client. Data links are returned in random order. :param str instance: A Yamcs instance name. :rtype: ~collections.Iterable[.Link]
366,607
def conv2bin(data): if data.min() < 0 or data.max() > 1: data = normalize(data) out_data = data.copy() for i, sample in enumerate(out_data): for j, val in enumerate(sample): if np.random.random() <= val: out_data[i][j] = 1 else: ...
Convert a matrix of probabilities into binary values. If the matrix has values <= 0 or >= 1, the values are normalized to be in [0, 1]. :type data: numpy array :param data: input matrix :return: converted binary matrix
366,608
def _build(self): flat_initial_state = nest.flatten(self._initial_state) if self._mask is not None: flat_mask = nest.flatten(self._mask) flat_learnable_state = [ _single_learnable_state(state, state_id=i, learnable=mask) for i, (state, mask) in enumerate(zip(flat_initial_sta...
Connects the module to the graph. Returns: The learnable state, which has the same type, structure and shape as the `initial_state` passed to the constructor.
366,609
def plot_bit_for_bit(case, var_name, model_data, bench_data, diff_data): plot_title = "" plot_name = case + "_" + var_name + ".png" plot_path = os.path.join(os.path.join(livvkit.output_dir, "verification", "imgs")) functions.mkdir_p(plot_path) m_ndim = np.ndim(model_data) b_ndim = np.ndim(b...
Create a bit for bit plot
366,610
def remove_profile(name, s3=False): user = os.path.expanduser("~") if s3: f = os.path.join(user, S3_PROFILE_ID + name) else: f = os.path.join(user, DBPY_PROFILE_ID + name) try: try: open(f) except: raise Exception("Profile does not exist. Cou...
Removes a profile from your config
366,611
def quick_api(api_key, secret_key, port=8000): auth = LinkedInAuthentication(api_key, secret_key, , PERMISSIONS.enums.values()) app = LinkedInApplication(authentication=auth) print auth.authorization_url _wait_for_user_to_enter_browser(app, port) return ...
This method helps you get access to linkedin api quickly when using it from the interpreter. Notice that this method creates http server and wait for a request, so it shouldn't be used in real production code - it's just an helper for debugging The usage is basically: api = quick_api(KEY, SEC...
366,612
def acquire(self, *, raise_on_failure=True): acquired = False try: acquired = self._acquire() if raise_on_failure and not acquired: raise RateLimitExceeded("rate limit exceeded for key %(key)r" % vars(self)) yield acquired finally: ...
Attempt to acquire a slot under this rate limiter. Parameters: raise_on_failure(bool): Whether or not failures should raise an exception. If this is false, the context manager will instead return a boolean value representing whether or not the rate limit slot was ...
366,613
def get_operators(self, name=None): return self._get_elements(self.operators, , Operator, name=name)
Get the list of :py:class:`Operator` elements associated with this job. Args: name(str): Only return operators matching `name`, where `name` can be a regular expression. If `name` is not supplied, then all operators for this job are returned. Returns: list(Oper...
366,614
def _get_link_indices(self, current_modified_line): links = [] for m in self._link_regex.finditer(current_modified_line): links.append(m.span()) return links
Get a list of tuples containing start and end indices of inline anchor links :param current_modified_line: The line being examined for links :return: A list containing tuples of the form (start, end), the starting and ending indices of inline anchors links.
366,615
def resolve(self, resolve_from): session = requests.Session() session.mount(resolve_from, requests.adapters.HTTPAdapter(max_retries=self._tries)) content = self._safe_get_content(session, resolve_from) try: parsed_urls = self._response_parser.parse(content) if len(parsed_urls) > 0: ...
:API: public
366,616
def build_all(cls, list_of_kwargs): return cls.add_all([ cls.new(**kwargs) for kwargs in list_of_kwargs], commit=False)
Similar to `create_all`. But transaction is not committed.
366,617
async def create_scene_member(self, shade_position, scene_id, shade_id): data = { ATTR_SCENE_MEMBER: { ATTR_POSITION_DATA: shade_position, ATTR_SCENE_ID: scene_id, ATTR_SHADE_ID: shade_id, } } return await self.req...
Adds a shade to an existing scene
366,618
def expr_to_json(expr): if isinstance(expr, symbolics.Mul): return {"type": "Mul", "args": [expr_to_json(arg) for arg in expr.args]} elif isinstance(expr, symbolics.Add): return {"type": "Add", "args": [expr_to_json(arg) for arg in expr.args]} elif isinstance(expr, symbolics.Symbol): ...
Converts a Sympy expression to a json-compatible tree-structure.
366,619
async def dataSources(loop=None, executor=None): loop = loop or asyncio.get_event_loop() sources = await loop.run_in_executor(executor, _dataSources) return sources
Returns a dictionary mapping available DSNs to their descriptions. :param loop: asyncio compatible event loop :param executor: instance of custom ThreadPoolExecutor, if not supplied default executor will be used :return dict: mapping of dsn to driver description
366,620
def dismiss_prompt(self, text=None, wait=None): with self.driver.dismiss_modal("prompt", text=text, wait=wait): yield
Execute the wrapped code, dismissing a prompt. Args: text (str | RegexObject, optional): Text to match against the text in the modal. wait (int | float, optional): Maximum time to wait for the modal to appear after executing the wrapped code. Raises: ...
366,621
def get_field(expr, field): weld_obj = WeldObject(encoder_, decoder_) struct_var = weld_obj.update(expr) if isinstance(expr, WeldObject): struct_var = expr.obj_id weld_obj.dependencies[struct_var] = expr weld_template = weld_obj.weld_code = weld_template % {"struct":struct_v...
Fetch a field from a struct expr
366,622
def main(): parser = argparse.ArgumentParser( description= ) parser.add_argument(, nargs=, help=) parser.add_argument(, , action=, help=) parser.add_argument(, , action=, help=) parser.add_argument(, , action=, ...
Controls the flow of the ddg application
366,623
def _infer_xy_labels(darray, x, y, imshow=False, rgb=None): assert x is None or x != y if imshow and darray.ndim == 3: return _infer_xy_labels_3d(darray, x, y, rgb) if x is None and y is None: if darray.ndim != 2: raise ValueError() y, x = darray.dims elif x is ...
Determine x and y labels. For use in _plot2d darray must be a 2 dimensional data array, or 3d for imshow only.
366,624
def edge(self, c): return ca.logic_and(c, ca.logic_not(self.pre_cond(c)))
rising edge
366,625
def make_url(domain, location): url = urlparse(location) if url.scheme == and url.netloc == : return domain + url.path elif url.scheme == : return + url.netloc + url.path else: return url.geturl()
This function helps to make full url path.
366,626
def read_dist_egginfo_json(dist, filename=DEFAULT_JSON): return obj
Safely get a json within an egginfo from a distribution.
366,627
def get_project() -> Optional[str]: project = SETTINGS.project if not project: require_test_mode_enabled() raise RunError() return project
Returns the current project name.
366,628
def set_content_type (self): if self.url: self.content_type = mimeutil.guess_mimetype(self.url, read=self.get_content) else: self.content_type = u""
Return URL content type, or an empty string if content type could not be found.
366,629
def make_file_exist(self): self.parent.make_directory_exist() self.parent.touch_file(self.name) return self
Make sure the parent directory exists, then touch the file
366,630
def list_modules(root_package = ): pkg = __import__(root_package, fromlist=[]) module_dict = OrderedDict() _server = Server() for imp, module, _ in walk_packages(pkg.__path__, root_package + ): m = __import__(module, fromlist = []) for name, v in vars(m).items(): if v is...
Walk through all the sub modules, find subclasses of vlcp.server.module.Module, list their apis through apidefs
366,631
def authenticate(self, request, username=None, password=None, realm=None): if isinstance(username, basestring): username = username.encode() if isinstance(password, basestring): password = password.encode() server = self.get_server(realm) if not server...
Check credentials against the RADIUS server identified by `realm` and return a User object or None. If no argument is supplied, Django will skip this backend and try the next one (as a TypeError will be raised and caught).
366,632
def _set_types(self): for c in (self.x, self.y): if not ( isinstance(c, int) or isinstance(c, float) ): raise(RuntimeError()) if isinstance(self.x, int) and isinstance(self.y, int): self._dtype = "int" ...
Make sure that x, y have consistent types and set dtype.
366,633
def register(cache): global caches name = cache().name if not caches.has_key(name): caches[name] = cache
Registers a cache.
366,634
def serialize(input, tree="etree", encoding=None, **serializer_opts): walker = treewalkers.getTreeWalker(tree) s = HTMLSerializer(**serializer_opts) return s.render(walker(input), encoding)
Serializes the input token stream using the specified treewalker :arg input: the token stream to serialize :arg tree: the treewalker to use :arg encoding: the encoding to use :arg serializer_opts: any options to pass to the :py:class:`html5lib.serializer.HTMLSerializer` that gets created ...
366,635
def t_MINUS(self, t): r t.endlexpos = t.lexpos + len(t.value) return t
r'-
366,636
def cmd_output_remove(self, args): device = args[0] for i in range(len(self.mpstate.mav_outputs)): conn = self.mpstate.mav_outputs[i] if str(i) == device or conn.address == device: print("Removing output %s" % conn.address) try: ...
remove an output
366,637
def get_core(self): if self.minisat and self.status == False: return pysolvers.minisatgh_core(self.minisat)
Get an unsatisfiable core if the formula was previously unsatisfied.
366,638
def get_token_and_data(self, data): token):data token = for c in data: if c != : token = token + c else: break; return token, data.lstrip(token + )
When we receive this, we have 'token):data'
366,639
def _is_valid_amendment_json(self, json_repr): amendment = self._coerce_json_to_amendment(json_repr) if amendment is None: return False aa = validate_amendment(amendment) errors = aa[0] for e in errors: _LOG.debug(.format(m=e.encode()...
Call the primary validator for a quick test
366,640
def save(self, *args, **kwargs): if self.publication: publication = self.publication if not self.title: self.title = publication.title if not self.subtitle: first_author = publication.first_author if first_author == ...
Before saving, if slide is for a publication, use publication info for slide's title, subtitle, description.
366,641
def load_config(data, *models, **kwargs): * if isinstance(models, tuple) and isinstance(models[0], list): models = models[0] config = get_config(data, *models, **kwargs) test = kwargs.pop(, False) debug = kwargs.pop(, False) commit = kwargs.pop(, True) replace = kwargs.pop(, False) ...
Generate and load the config on the device using the OpenConfig or IETF models and device profiles. data Dictionary structured with respect to the models referenced. models A list of models to be used when generating the config. profiles: ``None`` Use certain profiles to gener...
366,642
def filter_leader_files(cluster_config, broker_files): print("Filtering leaders") leader_of = get_partition_leaders(cluster_config) result = [] for broker, host, files in broker_files: filtered = [] for file_path in files: tp = get_tp_from_file(file_path) if ...
Given a list of broker files, filters out all the files that are in the replicas. :param cluster_config: the cluster :type cluster_config: kafka_utils.utils.config.ClusterConfig :param broker_files: the broker files :type broker_files: list of (b_id, host, [file_path, file_path ...]) tuples :re...
366,643
def identify_and_tag_authors(line, authors_kb): re_auth, re_auth_near_miss = get_author_regexps() for pattern, repl in authors_kb: line = line.replace(pattern, repl) output_line = line line = strip_tags(output_line) matched_authors = list(re_auth.finditer(line)) un...
Given a reference, look for a group of author names, place tags around the author group, return the newly tagged line.
366,644
async def SetFilesystemAttachmentInfo(self, filesystem_attachments): _params = dict() msg = dict(type=, request=, version=3, params=_params) _params[] = filesystem_attachments reply = await self.rpc(msg) r...
filesystem_attachments : typing.Sequence[~FilesystemAttachment] Returns -> typing.Sequence[~ErrorResult]
366,645
def setup(argv): parser = argparse.ArgumentParser( description=, epilog=) parser.add_argument(, , action=, dest=, help= ) parser.add_argument(, , action=, help= ...
Sets up the ArgumentParser. Args: argv: an array of arguments
366,646
def get_ordering(self, request, queryset, view): params = view.get_request_feature(view.SORT) if params: fields = [param.strip() for param in params] valid_ordering, invalid_ordering = self.remove_invalid_fields( queryset, fields, view ) ...
Return an ordering for a given request. DRF expects a comma separated list, while DREST expects an array. This method overwrites the DRF default so it can parse the array.
366,647
def type(self, name: str): for f in self.body: if (hasattr(f, ) and f._ctype._storage == Storages.TYPEDEF and f._name == name): return f
return the first complete definition of type 'name
366,648
def _try_cast(self, result, obj, numeric_only=False): if obj.ndim > 1: dtype = obj._values.dtype else: dtype = obj.dtype if not is_scalar(result): if is_datetime64tz_dtype(dtype): ...
Try to cast the result to our obj original type, we may have roundtripped through object in the mean-time. If numeric_only is True, then only try to cast numerics and not datetimelikes.
366,649
def get_page_url_title(self): cr_tab_id = self.transport._get_cr_tab_meta_for_key(self.tab_id)[] targets = self.Target_getTargets() assert in targets assert in targets[] for tgt in targets[][]: if tgt[] == cr_tab_id: title = tgt[] cur_url = tgt[] re...
Get the title and current url from the remote session. Return is a 2-tuple: (page_title, page_url).
366,650
def get_staged_signatures(vcs): staged_path = _get_staged_history_path(vcs) known_signatures = [] if os.path.exists(staged_path): with open(staged_path, ) as f: known_signatures = f.read().split() return known_signatures
Get the list of staged signatures Args: vcs (easyci.vcs.base.Vcs) Returns: list(basestring) - list of signatures
366,651
def _fancy_replace(self, a, alo, ahi, b, blo, bhi): r for j in xrange(blo, bhi): bj = b[j] cruncher.set_seq2(bj) for i in xrange(alo, ahi): ai = a[i] if ai == bj: if eqi is None: ...
r""" When replacing one block of lines with another, search the blocks for *similar* lines; the best-matching pair (if any) is used as a synch point, and intraline difference marking is done on the similar pair. Lots of work, but often worth it. Example: >>> d = Differ(...
366,652
def lxqstr(string, qchar, first): string = stypes.stringToCharP(string) qchar = ctypes.c_char(qchar.encode(encoding=)) first = ctypes.c_int(first) last = ctypes.c_int() nchar = ctypes.c_int() libspice.lxqstr_c(string, qchar, first, ctypes.byref(last), ctypes.byref(ncha...
Lex (scan) a quoted string. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lxqstr_c.html :param string: String to be scanned. :type string: str :param qchar: Quote delimiter character. :type qchar: char (string of one char) :param first: Character position at which to start scanning. ...
366,653
def validate(func): call = PythonCall(func) @wraps(func) def decorator(*args, **kwargs): parameters = call.bind(args, kwargs) for arg_name, validator in func.__annotations__.items(): if not validator(parameters[arg_name]): raise TypeError( ...
Check if annotated function arguments validate according to spec
366,654
def bgp_summary_parser(bgp_summary): bgp_summary_dict = {} if len(bgp_summary.strip().splitlines()) <= 1: return {} allowed_afi = ["ipv4", "ipv6", "l2vpn"] vrf_regex = r"^BGP summary information for VRF\s+(?P<vrf>\S+)," afi_regex = ( r"^BGP summary information.*address fa...
Parse 'show bgp all summary vrf' output information from NX-OS devices.
366,655
def pivot_query_as_matrix(facet=None, facet_pivot_fields=None, **kwargs): if facet_pivot_fields is None: facet_pivot_fields = [] logging.info("Additional args: {}".format(kwargs)) fp = search_associations(rows=0, facet_fields=[facet], fa...
Pivot query
366,656
def gpu_a_trous(): ker1 = SourceModule(, keep=True) ker2 = SourceModule(, keep=True) return ker1.get_function("gpu_a_trous_row_kernel"), ker2.get_function("gpu_a_trous_col_kernel")
Simple convenience function so that the a trous kernels can be easily accessed by any function.
366,657
def get_artist(self, object_id, relation=None, **kwargs): return self.get_object("artist", object_id, relation=relation, **kwargs)
Get the artist with the provided id :returns: an :class:`~deezer.resources.Artist` object
366,658
def connect(uri): uri = uri if isinstance(uri, ParseResult) else urlparse(uri) if not uri.scheme: raise ValueError("uri has no scheme: " + uri) f = _connect_fns.get(uri.scheme.lower(), None) if not f: err = "No connect function registered for scheme `%s`" % uri.scheme r...
Connects to an nREPL endpoint identified by the given URL/URI. Valid examples include: nrepl://192.168.0.12:7889 telnet://localhost:5000 http://your-app-name.heroku.com/repl This fn delegates to another looked up in that dispatches on the scheme of the URI provided (which can be a stri...
366,659
def validate_submit_args_or_fail(job_descriptor, provider_name, input_providers, output_providers, logging_providers): job_resources = job_descriptor.job_resources job_params = job_descriptor.job_params task_descriptors = job_descriptor.task_descriptors _validate_provider...
Validate that arguments passed to submit_job have valid file providers. This utility function takes resources and task data args from `submit_job` in the base provider. This function will fail with a value error if any of the parameters are not valid. See the following example; >>> job_resources = type('', (o...
366,660
def deserialize(cls, data, content_type=None): deserializer = Deserializer(cls._infer_class_models()) return deserializer(cls.__name__, data, content_type=content_type)
Parse a str using the RestAPI syntax and return a model. :param str data: A str using RestAPI structure. JSON by default. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model :raises: DeserializationError if something went wrong
366,661
def lovasz_hinge(logits, labels, per_image=True, ignore=None): if per_image: loss = mean(lovasz_hinge_flat(*flatten_binary_scores(log.unsqueeze(0), lab.unsqueeze(0), ignore)) for log, lab in zip(logits, labels)) else: loss = lovasz_hinge_flat(*flatten_binary_scores...
Binary Lovasz hinge loss logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty) labels: [B, H, W] Tensor, binary ground truth masks (0 or 1) per_image: compute the loss per image instead of per batch ignore: void class id
366,662
def get_recent_matches(self, card_type="micro_card"): recent_matches_url = self.api_path + "recent_matches/" params = {} params["card_type"] = card_type response = self.get_response(recent_matches_url, params) return response
Calling the Recent Matches API. Arg: card_type: optional, default to micro_card. Accepted values are micro_card & summary_card. Return: json data
366,663
def _kl_divergence(self, other_locs, other_weights, kernel=None, delta=1e-2): if kernel is None: kernel = st.norm(loc=0, scale=1).pdf dist = rescaled_distance_mtx(self, other_locs) / delta K = kernel(dist) return -self.est_entropy() - (1 / delta) * np.sum( ...
Finds the KL divergence between this and another particle distribution by using a kernel density estimator to smooth over the other distribution's particles.
366,664
def extract_tag_metadata(self, el): if self.type == : if el.namespace and el.namespace == self.namespaces[] and el.name == : name = el.attrs.get(, ) self.additional_context = .format(name) super().extract_tag_metadata(el)
Extract meta data.
366,665
def forwards(self, orm): "Write your forwards methods here." for doc in orm[].objects.all(): for title in doc.documenttitle_set.all(): title.is_published = doc.is_published title.save()
Write your forwards methods here.
366,666
def filter_sequences(self, seq_type): return DictList(x for x in self.sequences if isinstance(x, seq_type))
Return a DictList of only specified types in the sequences attribute. Args: seq_type (SeqProp): Object type Returns: DictList: A filtered DictList of specified object type only
366,667
def is_literal_or_name(value): try: ast.literal_eval(value) return True except (SyntaxError, ValueError): pass if value.strip() in [, , ]: return True return re.match(r, value)
Return True if value is a literal or a name.
366,668
def file_data_to_str(data): if not data: return _() res = data[] try: mtime_as_str = time.strftime(, time.localtime(data[])) res += .format(_(), mtime_as_str) res += .format( _(), data[], _()) except KeyError: ...
Convert file data to a string for display. This function takes the file data produced by gather_file_data().
366,669
def makeEndOfPrdvFuncCond(self): s state. NOTE: It might be possible to eliminate this method and replace it with ConsIndShockSolver.makeEndOfPrdvFunc, but the self.X_cond variables must be renamed. Parameters ---------- none Returns ------- ...
Construct the end-of-period value function conditional on next period's state. NOTE: It might be possible to eliminate this method and replace it with ConsIndShockSolver.makeEndOfPrdvFunc, but the self.X_cond variables must be renamed. Parameters ---------- none ...
366,670
def API520_W(Pset, Pback): r gauge_backpressure = (Pback-atm)/(Pset-atm)*100.0 if gauge_backpressure < 15.0: return 1.0 return interp(gauge_backpressure, Kw_x, Kw_y)
r'''Calculates capacity correction due to backpressure on balanced spring-loaded PRVs in liquid service. For pilot operated valves, this is always 1. Applicable up to 50% of the percent gauge backpressure, For use in API 520 relief valve sizing. 1D interpolation among a table with 53 backpressures is pe...
366,671
def dn(self,x,M_change = 12): y = signal.sosfilt(self.sos,x) y = ssd.downsample(y,M_change) return y
Downsample and filter the signal
366,672
def copy(self, extra=None): if extra is None: extra = dict() bestModel = self.bestModel.copy(extra) avgMetrics = self.avgMetrics subModels = self.subModels return CrossValidatorModel(bestModel, avgMetrics, subModels)
Creates a copy of this instance with a randomly generated uid and some extra params. This copies the underlying bestModel, creates a deep copy of the embedded paramMap, and copies the embedded and extra parameters over. It does not copy the extra Params into the subModels. :para...
366,673
def get_node_at_path(query_path, context): if query_path not in context.query_path_to_node: raise AssertionError( u.format( query_path, context)) node = context.query_path_to_node[query_path] return node
Return the SqlNode associated with the query path.
366,674
def draw(canvas, mol): mol.require("ScaleAndCenter") mlb = mol.size2d[2] if not mol.atom_count(): return bond_type_fn = { 1: { 0: single_bond, 1: wedged_single, 2: dashed_wedged_single, 3: wave_single, }, 2: { 0: cw...
Draw molecule structure image. Args: canvas: draw.drawable.Drawable mol: model.graphmol.Compound
366,675
def append(self, filename_in_zip, file_contents): self.in_memory_zip.seek(-1, io.SEEK_END) zf = zipfile.ZipFile(self.in_memory_zip, "a", zipfile.ZIP_DEFLATED, False) zf.writestr(filename_in_zip, file_contents) for zfile in zf.filel...
Appends a file with name filename_in_zip and contents of file_contents to the in-memory zip.
366,676
def _replace_global_vars(xs, global_vars): if isinstance(xs, (list, tuple)): return [_replace_global_vars(x) for x in xs] elif isinstance(xs, dict): final = {} for k, v in xs.items(): if isinstance(v, six.string_types) and v in global_vars: v = global_var...
Replace globally shared names from input header with value. The value of the `algorithm` item may be a pointer to a real file specified in the `global` section. If found, replace with the full value.
366,677
def sample_name(in_bam): with pysam.AlignmentFile(in_bam, "rb", check_sq=False) as in_pysam: try: if "RG" in in_pysam.header: return in_pysam.header["RG"][0]["SM"] except ValueError: return None
Get sample name from BAM file.
366,678
def get_assessment_taken_bank_assignment_session(self, proxy): if not self.supports_assessment_taken_bank_assignment(): raise errors.Unimplemented() return sessions.AssessmentTakenBankAssignmentSession(proxy=proxy, runtime=self._runtime)
Gets the session for assigning taken assessments to bank mappings. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.assessment.AssessmentTakenBankAssignmentSession) - an ``AssessmentTakenBankAssignmentSession`` raise: NullArgument - ``proxy`` is ``null`` raise: ...
366,679
def set_archive_layout(self, archive_id, layout_type, stylesheet=None): payload = { : layout_type, } if layout_type == : if stylesheet is not None: payload[] = stylesheet endpoint = self.endpoints.set_archive_layout_url(archive_id) ...
Use this method to change the layout of videos in an OpenTok archive :param String archive_id: The ID of the archive that will be updated :param String layout_type: The layout type for the archive. Valid values are: 'bestFit', 'custom', 'horizontalPresentation', 'pip' and 'verticalPresentation...
366,680
def _handle_next_export_subtask(self, export_state=None): if export_state is None or export_state.export_task is None: export = self.db.get_next_entity_to_export() if export is not None: export_state = self.ExportState(export_task=export) els...
Process the next export sub-task, if there is one. :param ExportState export_state: If provided, this is used instead of the database queue, in effect directing the exporter to process the previous export again. This is used to avoid having to query the database when we know already wha...
366,681
def exec_rabbitmqctl(self, command, args=[], rabbitmqctl_opts=[]): cmd = [] + rabbitmqctl_opts + [command] + args return self.inner().exec_run(cmd)
Execute a ``rabbitmqctl`` command inside a running container. :param command: the command to run :param args: a list of args for the command :param rabbitmqctl_opts: a list of extra options to pass to ``rabbitmqctl`` :returns: a tuple of the command exit code and output
366,682
def GetChildClassId(self, classId): childList = [] for ch in self.child: if ch.classId.lower() == classId.lower(): childList.append(ch) return childList
Method extracts and returns the child object list same as the given classId
366,683
def is_possible_number(numobj): result = is_possible_number_with_reason(numobj) return (result == ValidationResult.IS_POSSIBLE or result == ValidationResult.IS_POSSIBLE_LOCAL_ONLY)
Convenience wrapper around is_possible_number_with_reason. Instead of returning the reason for failure, this method returns true if the number is either a possible fully-qualified number (containing the area code and country code), or if the number could be a possible local number (with a country code,...
366,684
def set_phases(self, literals=[]): if self.lingeling: pysolvers.lingeling_setphases(self.lingeling, literals)
Sets polarities of a given list of variables.
366,685
def edit_securitygroup(self, group_id, name=None, description=None): successful = False obj = {} if name: obj[] = name if description: obj[] = description if obj: successful = self.security_group.editObject(obj, id=group_id) ...
Edit security group details. :param int group_id: The ID of the security group :param string name: The name of the security group :param string description: The description of the security group
366,686
def get_block_hash(self, height, id=None, endpoint=None): return self._call_endpoint(GET_BLOCK_HASH, params=[height], id=id, endpoint=endpoint)
Get hash of a block by its height Args: height: (int) height of the block to lookup id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: json object of the result or the error encountere...
366,687
def create(self, Name, Subject, HtmlBody=None, TextBody=None, Alias=None): assert TextBody or HtmlBody, "Provide either email TextBody or HtmlBody or both" data = {"Name": Name, "Subject": Subject, "HtmlBody": HtmlBody, "TextBody": TextBody, "Alias": Alias} return self._init_instance(se...
Creates a template. :param Name: Name of template :param Subject: The content to use for the Subject when this template is used to send email. :param HtmlBody: The content to use for the HtmlBody when this template is used to send email. :param TextBody: The content to use for the HtmlB...
366,688
def start_continuous(self, aichans, update_hz=10): self.daq_lock.acquire() self.ngenerated = 0 npts = int(self.aifs/update_hz) nchans = len(aichans) self.aitask = AITask(aichans, self.aifs, npts*5*nchans) self.aitask.register_callback(self._read_continuous, np...
Begins a continuous analog generation, calling a provided function at a rate of 10Hz :param aichans: name of channel(s) to record (analog input) from :type aichans: list<str> :param update_hz: Rate (Hz) at which to read data from the device input buffer :type update_hz: int
366,689
def update(): try: salt.fileserver.reap_fileserver_cache_dir( os.path.join(__opts__[], , ), find_file ) except (IOError, OSError):
When we are asked to update (regular interval) lets reap the cache
366,690
def extract_name_from_job_arn(arn): slash_pos = arn.find() if slash_pos == -1: raise ValueError("Cannot parse invalid ARN: %s" % arn) return arn[(slash_pos + 1):]
Returns the name used in the API given a full ARN for a training job or hyperparameter tuning job.
366,691
def extract_spans(html_string): try: from bs4 import BeautifulSoup except ImportError: print("ERROR: You must have BeautifulSoup to use html2data") return soup = BeautifulSoup(html_string, ) table = soup.find() if not table: return [] trs = table.findAll() ...
Creates a list of the spanned cell groups of [row, column] pairs. Parameters ---------- html_string : str Returns ------- list of lists of lists of int
366,692
def ensure_property_set(host=None, admin_username=None, admin_password=None, property=None, value=None): ret = get_property(host, admin_username, admin_password, property) if ret[] == value: return True ret = set_property(host, admin_username, admin_password, property, value) return ret
.. versionadded:: Fluorine Ensure that property is set to specific value host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. property: The property which should be set. value:...
366,693
def to_bigquery_fields(self, name_case=DdlParseBase.NAME_CASE.original): bq_fields = [] for col in self.values(): bq_fields.append(col.to_bigquery_field(name_case)) return "[{}]".format(",".join(bq_fields))
Generate BigQuery JSON fields define :param name_case: name case type * DdlParse.NAME_CASE.original : Return to no convert * DdlParse.NAME_CASE.lower : Return to lower * DdlParse.NAME_CASE.upper : Return to upper :return: BigQuery JSON fields define
366,694
def p_try_statement_3(self, p): p[0] = ast.Try(statements=p[2], catch=p[3], fin=p[4])
try_statement : TRY block catch finally
366,695
def unicode_iter(val): val_iter = iter(val) while True: try: code_point = next(_next_code_point(val, val_iter, to_int=ord)) except StopIteration: return if code_point is None: raise ValueError( % val) yield code_point
Provides an iterator over the *code points* of the given Unicode sequence. Notes: Before PEP-393, Python has the potential to support Unicode as UTF-16 or UTF-32. This is reified in the property as ``sys.maxunicode``. As a result, naive iteration of Unicode sequences will render non-charac...
366,696
def as_mpl_artists(shape_list, properties_func=None, text_offset=5.0, origin=1): patch_list = [] artist_list = [] if properties_func is None: properties_func = properties_func_default saved_attrs = None for shape in shape_list: pat...
Converts a region list to a list of patches and a list of artists. Optional Keywords: [ text_offset ] - If there is text associated with the regions, add some vertical offset (in pixels) to the text so that it doesn't overlap with the regions. Often, the regions files implicitly assume the lower-...
366,697
def query_all(): recs = TabPost2Tag.select( TabPost2Tag, TabTag.kind.alias(), ).join( TabTag, on=(TabPost2Tag.tag_id == TabTag.uid) ) return recs
Query all the records from TabPost2Tag.
366,698
def add_header(self, name, value): if value is not None: self._headers.append((name, value))
Add an HTTP header to response object. Arguments: name (str): HTTP header field name value (str): HTTP header field value
366,699
def load_file(self, fname, table=None, sep="\t", bins=False, indexes=None): convs = {" "chrom", "pos": "start", "POS": "start", "chromStart": "txStart", "chromEnd": "txEnd"} if table is None: import os.path as op table = op.basename(op.spl...
use some of the machinery in pandas to load a file into a table Parameters ---------- fname : str filename or filehandle to load table : str table to load the file to sep : str CSV separator bins : bool add a "bin" colu...