Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
355,800
def calculate(self, T, method): r if method == STREFPROP: sigma0, n0, sigma1, n1, sigma2, n2, Tc = self.STREFPROP_coeffs sigma = REFPROP(T, Tc=Tc, sigma0=sigma0, n0=n0, sigma1=sigma1, n1=n1, sigma2=sigma2, n2=n2) elif method == VDI_PPDS: ...
r'''Method to calculate surface tension of a liquid at temperature `T` with a given method. This method has no exception handling; see `T_dependent_property` for that. Parameters ---------- T : float Temperature at which to calculate surface tension, [K] ...
355,801
def update_org_users(cls, module): try: cls.module_registry[module]["OrgUserModel"]._meta.get_field("user") except FieldDoesNotExist: cls.module_registry[module]["OrgUserModel"].add_to_class( "user", models.ForeignKey( ...
Adds the `user` field to the organization user model and the link to the specific organization model.
355,802
def get_structure_with_nodes(self, find_min=True, min_dist=0.5, tol=0.2, threshold_frac=None, threshold_abs=None): structure = self.structure.copy() self.get_local_extrema(find_min=find_min, threshold_frac=threshold_frac, threshol...
Get the modified structure with the possible interstitial sites added. The species is set as a DummySpecie X. Args: find_min (bool): True to find local minimum else maximum, otherwise find local maximum. min_dist (float): The minimum distance (in Angstrom) that ...
355,803
def get_dashboard_tags(self, id, **kwargs): kwargs[] = True if kwargs.get(): return self.get_dashboard_tags_with_http_info(id, **kwargs) else: (data) = self.get_dashboard_tags_with_http_info(id, **kwargs) return data
Get all tags associated with a specific dashboard # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_dashboard_tags(id, async_req=True) >>> result = thread.ge...
355,804
def regular_generic_msg(hostname, result, oneline, caption): if not oneline: return "%s | %s >> %s\n" % (hostname, caption, utils.jsonify(result,format=True)) else: return "%s | %s >> %s\n" % (hostname, caption, utils.jsonify(result))
output on the result of a module run that is not command
355,805
def plot_networkx(network, plot_throats=True, labels=None, colors=None, scale=10): r import networkx as nx x, y, z = network[].T x, y = [j for j in [x, y, z] if not sp.allclose(j, j.mean())] G = nx.Graph() pos = {network.Ps[i]: [x[i], y[i]] for i in range(network.Np)} if ...
r''' Returns a pretty 2d plot for 2d OpenPNM networks. Parameters ---------- network : OpenPNM Network object plot_throats : boolean Plots throats as well as pores, if True. labels : list List of OpenPNM labels colors : list List of corresponding colors to the giv...
355,806
def apply_compact(graph_path): with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess: with tf.gfile.GFile(graph_path, "rb") as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) tf.import_graph_def(graph_def) input_...
Run the pruned and frozen inference graph.
355,807
def contourInside(self, otherContour): otherContour = normalizers.normalizeContour(otherContour) return self._contourInside(otherContour)
Determine if ``otherContour`` is in the black or white of this contour. >>> contour.contourInside(otherContour) True ``contour`` must be a :class:`BaseContour`.
355,808
def has_causal_in_edges(graph: BELGraph, node: BaseEntity) -> bool: return any( data[RELATION] in CAUSAL_RELATIONS for _, _, data in graph.in_edges(node, data=True) )
Return true if the node contains any in_edges that are causal.
355,809
def to_representation(self, instance): if self.id_only(): return instance.pk pk = getattr(instance, , None) if not settings.ENABLE_SERIALIZER_OBJECT_CACHE or pk is None: return self._to_representation(instance) else: if pk not in self.obj_cac...
Modified to_representation method. Optionally may cache objects. Arguments: instance: A model instance or data object. Returns: Instance ID if the serializer is meant to represent its ID. Otherwise, a tagged data dict representation.
355,810
def _compose_pair(self, role, base): for attrname in dir(role): transformation = getattr(role, attrname) self._apply_transformation(role, base, transformation, attrname) return base
composes onto base by applying the role
355,811
def mail_handler(self, punchline=None, add_meta=False, add_settings=True, *args, **kwargs): m = Mail(self.m, *args, **kwargs) if punchline: m.text = % (punchline) if add_meta: m.text = self.meta.log if add_setti...
:param punchline: Adds a punchline before further text :param add_meta: Appends current meta to the mail :param add_settings: Appends current settings to the mail :returns: A new mail handler .. seealso:: :ref:`tools_mail`
355,812
def read_flags_from_files(self, argv, force_gnu=True): rest_of_args = argv new_argv = [] while rest_of_args: current_arg = rest_of_args[0] rest_of_args = rest_of_args[1:] if self._is_flag_file_directive(current_arg): if current_arg == or current_arg == : ...
Processes command line args, but also allow args to be read from file. Args: argv: [str], a list of strings, usually sys.argv[1:], which may contain one or more flagfile directives of the form --flagfile="./filename". Note that the name of the program (sys.argv[0]) should be omitted. ...
355,813
def _computeInferenceMode(self, feedforwardInput, lateralInputs): prevActiveCells = self.activeCells overlaps = self.proximalPermanences.rightVecSumAtNZGteThresholdSparse( feedforwardInput, self.connectedPermanenceProximal) feedforwardSupportedCells = numpy.where( overlaps >= self.mi...
Inference mode: if there is some feedforward activity, perform spatial pooling on it to recognize previously known objects, then use lateral activity to activate a subset of the cells with feedforward support. If there is no feedforward activity, use lateral activity to activate a subset of the previous...
355,814
def write_cron_file(user, path): s crontab CLI Example: .. code-block:: bash salt cron.write_cron_file root /tmp/new_cron .. versionchanged:: 2015.8.9 .. note:: Some OS if _check_instance_uid_match(user) or __grains__.get() in (, ): return __salt__[](_get_cron_cmds...
Writes the contents of a file to a user's crontab CLI Example: .. code-block:: bash salt '*' cron.write_cron_file root /tmp/new_cron .. versionchanged:: 2015.8.9 .. note:: Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
355,815
def to_yellow(self, on: bool=False): self._on = on if on: self._load_new(led_yellow_on) if self._toggle_on_click: self._canvas.bind(, lambda x: self.to_yellow(False)) else: self._load_new(led_yellow) ...
Change the LED to yellow (on or off) :param on: True or False :return: None
355,816
def fitness(self, width, height): assert(width > 0 and height > 0) section, rotated = self._select_fittest_section(width, height) if not section: return None if rotated: return self._section_fitness(section, height, wi...
In guillotine algorithm case, returns the min of the fitness of all free sections, for the given dimension, both normal and rotated (if rotation enabled.)
355,817
def _add_ideal_atomic_weights_(elemental_array): for a in elemental_array: this_atomic_weight = elements_data[a["symbol"]]["atomic_weight"] a["weight"] = a["occurances"] * this_atomic_weight return elemental_array
Uses elements.json to find the molar mass of the element in question, and then multiplies that by the occurances of the element. Adds the "weight" property to each of the dictionaries in elemental_array :param elemental_array: an array of dictionaries containing information about the elements in the system ...
355,818
def _get_SConscript_filenames(self, ls, kw): exports = [] if len(ls) == 0: try: dirs = kw["dirs"] except KeyError: raise SCons.Errors.UserError("Invalid SConscript usage - no parameters") if not SCons.Util.is_List(dirs): ...
Convert the parameters passed to SConscript() calls into a list of files and export variables. If the parameters are invalid, throws SCons.Errors.UserError. Returns a tuple (l, e) where l is a list of SConscript filenames and e is a list of exports.
355,819
def suffix(transformers, default=None): transformers = {suffix: auto_kwargs(transformer) if transformer else transformer for suffix, transformer in transformers.items()} default = default and auto_kwargs(default) def transform(data, request): path = request.path tra...
Returns a different transformer depending on the suffix at the end of the requested URL. If none match and no default is given no transformation takes place. should pass in a dict with the following format: {'[suffix]': transformation_action, ... }
355,820
def visit_str(self, node, _): return self.visit_str.re_single_backslash.sub(, node.text[1:-1])
Regex rule for quoted string allowing escaped quotes inside. Arguments --------- node : parsimonious.nodes.Node. _ (children) : list, unused Result ------ str The wanted string, with quoted characters unquoted. Example ------- ...
355,821
def get_pyof_version(module_fullname): ver_module_re = re.compile(r) matched = ver_module_re.match(module_fullname) if matched: version = matched.group(2) return version return None
Get the module pyof version based on the module fullname. Args: module_fullname (str): The fullname of the module (e.g.: pyof.v0x01.common.header) Returns: str: openflow version. The openflow version, on the format 'v0x0?' if any. Or None ...
355,822
def delete_assets(self, service_id, url=None, all=False): self._services_manager.delete_assets(service_id, url, all)
Delete CDN assets Arguments: service_id: The ID of the service to delete from. url: The URL at which to delete assets all: When True, delete all assets associated with the service_id. You cannot specifiy both url and all.
355,823
def predictions(self, route=): apiresponse = self.api.predictions(stpid=self.id, rt=route)[] if type(apiresponse) is list: for prediction in apiresponse: try: pobj = Prediction.fromapi(self.api, prediction) pobj._sto...
Yields predicted bus ETAs for this stop. You can specify a route identifier for ETAs specific to one route, or leave `route` blank (done by default) to get information on all arriving busses.
355,824
def _get_pdf_list(self, input_pdfs): if isinstance(input_pdfs, list): return [pdf for pdf in input_pdfs if self.validate(pdf)] elif os.path.isdir(input_pdfs): return [os.path.join(input_pdfs, pdf) for pdf in os.listdir(input_pdfs) if self.validate(pdf)]
Generate list of PDF documents. :param input_pdfs: List of PDFs or a directory path Directory - Scans directory contents List - Filters list to assert all list items are paths to PDF documents :return: List of PDF paths
355,825
def _cond_s(self, word, suffix_len): return word[-suffix_len - 2 : -suffix_len] == or ( word[-suffix_len - 1] == and word[-suffix_len - 2 : -suffix_len] != )
Return Lovins' condition S. Parameters ---------- word : str Word to check suffix_len : int Suffix length Returns ------- bool True if condition is met
355,826
def generate_sbi_config(num_pbs: int = 3, project: str = , programme_block: str = , pb_config: Union[dict, List[dict]] = None, workflow_config: Union[dict, List[dict]] = None, register_workflows=False...
Generate a SBI configuration dictionary. Args: num_pbs (int, optional): Number of Processing Blocks (default = 3) project (str, optional): Project to associate the SBI with. programme_block (str, optional): SBI programme block pb_config (dict, List[dict], optional): PB configuration...
355,827
async def fetch(self, n, *, timeout=None): r self._check_ready() if n <= 0: raise exceptions.InterfaceError() if self._exhausted: return [] recs = await self._exec(n, timeout) if len(recs) < n: self._exhausted = True return recs
r"""Return the next *n* rows as a list of :class:`Record` objects. :param float timeout: Optional timeout value in seconds. :return: A list of :class:`Record` instances.
355,828
def dependencyOrder(aMap, aList = None): dependencyMap = makeDependencyMap(aMap) outputList = [] if not aList: aList = aMap.keys() items = [] v = BottomUpVisitor() for item in aList: try: v.visit(dependencyMap[item]) except KeyError: outputList.append(item) outputList = [x.item ...
Given descriptions of dependencies in aMap and an optional list of items in aList if not aList, aList = aMap.keys() Returns a list containing each element of aList and all its precursors so that every precursor of any element in the returned list is seen before that dependent element. If aMap contains cycles, s...
355,829
def on_menu(self, event): state = self.state ret = self.menu.find_selected(event) if ret is None: return ret.call_handler() state.child_pipe_send.send(ret)
handle menu selections
355,830
def authenticate(self, *args, **kwargs): username = kwargs.get("username", None) password = kwargs.get("password", None) authorization = self.ldap_link(username, password, mode=) if authorization: user = self.get_or_create_user(usern...
Authenticate the user agains LDAP
355,831
def _create_tree(self, endpoint=None, index=0): tab = ret = if endpoint: name = endpoint.path.split(, 1)[1].replace(, ) + ret += tab + name + ret += endpoint.method_calls( * len(tab + name)) else: endpoint = self for...
This will return a string of the endpoint tree structure :param endpoint: Endpoint's Current path of the source :param index: int number of tabs to space over :return: str
355,832
def build_params(self, params={}): z = params.copy() z.update({: self.edit_id, : self.package_name}) return z
build a params dictionary with current editId and packageName. use optional params parameter to merge additional params into resulting dictionary.
355,833
def connect(self, host, port=1883, keepalive=60, bind_address=""): self.connect_async(host, port, keepalive, bind_address) return self.reconnect()
Connect to a remote broker. host is the hostname or IP address of the remote broker. port is the network port of the server host to connect to. Defaults to 1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you are using tls_set() the port may need providing. k...
355,834
def update_config(self, config_dict, config_file): config_path = path.dirname(config_file) self.config.config_file_path = config_file self.config.path = config_path for config_key, config_value in config_dict.items(): if config_value != self.config.get_config_value(c...
Update the content and reference of the config :param dict config_dict: The new configuration :param str config_file: The new file reference
355,835
def download(ctx, help: bool, symbol: str, namespace: str, agent: str, currency: str): if help: click.echo(ctx.get_help()) ctx.exit() app = PriceDbApplication() app.logger = logger if currency: currency = currency.strip() currency = currency.upper() app.d...
Download the latest prices
355,836
def token(self): if self.tokens_queue: self.last_token = self.tokens_queue.pop(0) else: r = self.lex.token() if isinstance(r, MultiToken): self.tokens_queue.extend(r.tokens) self.last_token = self.tokens_queue.pop(0) ...
Returns the next LexToken. Returns None when all tokens have been exhausted.
355,837
def set_simple_func(self, func, args=()): code = get_function_code(func) npar = code.co_argcount - len(args) pnames = code.co_varnames[:npar] def wrapper(params, *args): return func(*(tuple(params) + args)) return self.set_func(wrapper, pnames, args)
Set the model function to use a simple but somewhat inefficient calling convention. The function should obey the following convention:: def func(param0, param1, ..., paramN, *args): modeled_data = { do something using the parameters } return modeled_data ...
355,838
def methodcall(self, methodname, localobject, Params=None, **params): warnings.warn( "Calling methodcall() directly is deprecated; it will be removed " "in the next pywbem release after 0.12", DeprecationWarning, 2) return self._methodcall(methodname, localob...
**Deprecated:** Low-level method used by the :meth:`~pywbem.WBEMConnection.InvokeMethod` method of this class. *Deprecated since pywbem 0.12.* Calling this function directly has been deprecated and will issue a :term:`DeprecationWarning`. Users should call :meth:`~pywbem.WBEMCo...
355,839
def get_time_server(): * ret = salt.utils.mac_utils.execute_return_result( ) return salt.utils.mac_utils.parse_return(ret)
Display the currently set network time server. :return: the network time server :rtype: str CLI Example: .. code-block:: bash salt '*' timezone.get_time_server
355,840
def get(self, key): check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(replicated_map_get_codec, key_data, key=key_data)
Returns the value for the specified key, or None if this map does not contain this key. **Warning: This method uses hashCode and equals of the binary form of the key, not the actual implementations of hashCode and equals defined in the key's class.** :param key: (object), the specified...
355,841
def kill(self, detach=False): self.ack_callbacks = {} if self.connected: self.state = self.STATE_DISCONNECTING self.server_queue.put_nowait(None) self.client_queue.put_nowait(None) if len(self.active_ns) > 0: log.debug("Ca...
This function must/will be called when a socket is to be completely shut down, closed by connection timeout, connection error or explicit disconnection from the client. It will call all of the Namespace's :meth:`~socketio.namespace.BaseNamespace.disconnect` methods so that you c...
355,842
def _list_tenants(self, admin): resp, resp_body = self.method_get("tenants", admin=admin) if 200 <= resp.status_code < 300: tenants = resp_body.get("tenants", []) return [Tenant(self, tenant) for tenant in tenants] elif resp.status_code in (401, 403): ...
Returns either a list of all tenants (admin=True), or the tenant for the currently-authenticated user (admin=False).
355,843
def allzeros(msg): d = hex2bin(data(msg)) if bin2int(d) > 0: return False else: return True
check if the data bits are all zeros Args: msg (String): 28 bytes hexadecimal message string Returns: bool: True or False
355,844
def diff_move(self,v,new_comm): return _c_leiden._MutableVertexPartition_diff_move(self._partition, v, new_comm)
Calculate the difference in the quality function if node ``v`` is moved to community ``new_comm``. Parameters ---------- v The node to move. new_comm The community to move to. Returns ------- float Difference in quality function. Notes ----- The differen...
355,845
def request_anime(aid: int) -> : anime_info = alib.request_anime(_CLIENT, aid) return Anime._make(anime_info)
Make an anime API request.
355,846
def configure_hipchat_logger( self, hipchat_webhook=None, log_level=, log_format=ReportingFormats.PRETTY_PRINT.value, custom_args= ): hipchat_webhook = self.config.get_option( , , None, hipchat_webhook ...
logger for sending messages to HipChat. Easy way to alert humans of issues Note: Will try to overwrite minimum log level to enable requested log_level Will warn and not attach hipchat logger if missing webhook key Learn more about webhooks: https://yak.crowdstrike.com/addon...
355,847
def c_getprocs(self): getprocs = [] for name, dummy_args in self.funcs: if name == : if callable(self.opts.hash_func): continue getter = elif self.opts.no_structs: getter = else: ...
Get the getprocs of the module.
355,848
def synthesize(self, duration, tick_frequency): sr = self.samplerate.samples_per_second tick = np.random.uniform(low=-1., high=1., size=int(sr * .1)) tick *= np.linspace(1, 0, len(tick)) samples = np.zeros(int(sr * (duration / Seconds(1)))) ticks_per_se...
Synthesize periodic "ticks", generated from white noise and an envelope Args: duration (numpy.timedelta64): The total duration of the sound to be synthesized tick_frequency (numpy.timedelta64): The frequency of the ticking sound
355,849
def _read(self, limit=1000): if (remaining - 4) >= size: responses.append(Response.from_raw( self, buf[(total + 4):(total + size + 4)])) total += (size + 4) remaining -= (size + 4) limit -= 1 ...
Return all the responses read
355,850
def right_margin(self, margin): s width. Returns: None Raises: RuntimeError: Invalid margin parameter QInvalid margin parameter in function rightMargin')
Specify the right margin. Args: margin: The right margin, in character width, must be less than the media's width. Returns: None Raises: RuntimeError: Invalid margin parameter
355,851
def renderHTTP(self, context): if getattr(self.wrappedResource, , False): request = IRequest(context) url = self.urlGenerator.encryptedRoot() if url is not None: for seg in request.prepath: url = url.child(seg) retu...
Check to see if the wrapped resource wants to be rendered over HTTPS and generate a redirect if this is so, if HTTPS is available, and if the request is not already over HTTPS.
355,852
def item(self, item, option=None, **kw): if kw: self._visual_drag.item(item, option, **kw) return ttk.Treeview.item(self, item, option, **kw)
Query or modify the options for the specified item. If no options are given, a dict with options/values for the item is returned. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values as given by `kw`. :param ...
355,853
def getnodes(fnods, up=None, verbose=False): f=open(fnods) l=[int(x) for x in f.readline().split()] npoints,dim,nattrib,nbound=l if dim == 2: ndapp = [0.0] else: ndapp = [] if verbose and up is not None: up.init(npoints) nodes=[] ...
Reads t.1.nodes, returns a list of nodes. Example: >>> self.getnodes("t.1.node", MyBar("nodes:")) [(0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (0.0, 4.0, 0.0), (-4.0, 0.0, 0.0), (0.0, 0.0, 4.0), (0.0, -4.0, 0.0), (0.0, -0.0, -4.0), (-2.0, 0.0, -2.0), (-2.0, 2.0, 0.0), (0.0, 2.0, -2.0), (...
355,854
def add_to_manifest(self, manifest): manifest.add_service(self.service.name) uri = predix.config.get_env_key(self.use_class, ) manifest.add_env_var(uri, self.get_ingest_uri()) zone_id = predix.config.get_env_key(self.use_class, ) manifest.add_env_var(...
Add useful details to the manifest about this service so that it can be used in an application. :param manifest: An predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry app.
355,855
def extract_minors_from_setup_py(filename_setup_py): 2.62.73.33.43.53.6 minors_str = fabric.api.local( flo( ), capture=True) minors = minors_str.split() return minors
Extract supported python minor versions from setup.py and return them as a list of str. Return example: ['2.6', '2.7', '3.3', '3.4', '3.5', '3.6']
355,856
def read_stream(self, file: IO, data_stream: DataStream) -> Reply: yield from data_stream.read_file(file=file) reply = yield from self._control_stream.read_reply() self.raise_if_not_match( , ReplyCodes.closing_data_connection, reply ) ...
Read from the data stream. Args: file: A destination file object or a stream writer. data_stream: The stream of which to read from. Coroutine. Returns: Reply: The final reply.
355,857
def make_key(self, *parts): separator = getattr(self.model_class, , ) parts = map(decode, parts) return % (self._base_key, separator.join(map(str, parts)))
Generate a namespaced key for the given path.
355,858
def as_df(): records = [] for sym, ele in vars(_this).items(): if sym not in ["Element", "Isotope"] and not sym.startswith("_"): for k, v in vars(ele).items(): if k.startswith("_") and k[1].isdigit(): records.append({kk: vv for kk, vv in vars(v).items...
Return a dataframe of isotopes.
355,859
def create_user(resource_root, username, password, roles): apiuser = ApiUser(resource_root, username, password=password, roles=roles) return call(resource_root.post, USERS_PATH, ApiUser, True, data=[apiuser])[0]
Create a user. @param resource_root: The root Resource object @param username: Username @param password: Password @param roles: List of roles for the user. This should be [] or ['ROLE_USER'] for a regular user, ['ROLE_ADMIN'] for an admin, or ['ROLE_LIMITED'] for a limited admin...
355,860
def set_slug(apps, schema_editor, class_name): Cls = apps.get_model(, class_name) for obj in Cls.objects.all(): obj.slug = generate_slug(obj.pk) obj.save(update_fields=[])
Create a slug for each Work already in the DB.
355,861
def handle(self, site=None, **options): if options[]: monkeypatch_remove_pages_site_restrictions() qs = Page.objects.all() if site: for match in (, ): try: s = Site.objects.get(**{match:site}) break ...
Export pages in JSON format. Site may be specified by id or domain. Default: export pages from the current site specified by settings.SITE_ID.
355,862
def acquire(self, blocking=True): sleep = self.sleep timeout = self.timeout while 1: unixtime = time.time() if timeout: timeout_at = unixtime + timeout else: timeout_at = Lock.LOCK_FOREVER timeout_at = float...
Use Redis to hold a shared, distributed lock named ``name``. Returns True once the lock is acquired. If ``blocking`` is False, always return immediately. If the lock was acquired, return True, otherwise return False.
355,863
def get(_class, api, rt): if not _class.all_routes: _class.all_routes = _class.update_list(api, api.routes()[]) return _class.all_routes[str(rt)]
Return a Route object for route `rt` using API instance `api`.
355,864
def tear_down(self): while len(self._temp_directories) > 0: directory = self._temp_directories.pop() shutil.rmtree(directory, ignore_errors=True) while len(self._temp_files) > 0: file = self._temp_files.pop() try: os.remove(file) ...
Tears down all temp files and directories.
355,865
def sorted_dependencies(dist, reverse=False): from .. import baseclass collection = [dist] nodes = [dist] edges = [] pool = [dist] while pool: dist = pool.pop() for key in sorted(dist.prm): value = dist.prm[key] if not isinstance(value, basecla...
Extract all underlying dependencies from a distribution sorted topologically. Uses depth-first algorithm. See more here: Args: dist (Dist): Distribution to extract dependencies from. reverse (bool): If True, place dependencies in reverse order. Returns: ...
355,866
def camelcase_to_underline(param_dict): temp_dict = copy.deepcopy(param_dict) hump_to_underline = re.compile(r) for key in list(param_dict.keys()): underline_sub = re.sub(hump_to_underline, r, key).lower() temp_dict[underline_sub] = temp_dict.pop(key) return temp_...
将驼峰命名的参数字典键转换为下划线参数 :param: * param_dict: (dict) 请求参数字典 :return: * temp_dict: (dict) 转换后的参数字典 举例如下:: print('--- transform_hump_to_underline demo---') hump_param_dict = {'firstName': 'Python', 'Second_Name': 'san', 'right_name': 'name'} underline_param_dict = trans...
355,867
def insert (self, properties, value): assert is_iterable_typed(properties, basestring) assert isinstance(value, basestring) self.__properties.append(properties) self.__values.append(value)
Associate value with properties.
355,868
def save_users(users, path=settings.LOGIN_FILE): with open(path, "w") as fh: for username, data in users.items(): pass_line = username + ":" + ":".join([ data["pass_hash"], data["uid"], data["gid"], data["full_name"], ...
Save dictionary with user data to passwd file (default :attr:`ftp.settings.LOGIN_FILE`). Args: users (dict): dictionary with user data. For details look at dict returned from :func:`load_users`. path (str, default settings.LOGIN_FILE): path of the file, where the ...
355,869
def score_large_straight_yatzy(dice: List[int]) -> int: dice_set = set(dice) if _are_two_sets_equal({2, 3, 4, 5, 6}, dice_set): return sum(dice) return 0
Large straight scoring according to yatzy rules
355,870
def dehydrate(self, comp, broker): if not self.meta_data: raise Exception("Hydration meta_path not set. Can't dehydrate.") if not self.created: fs.ensure_path(self.meta_data, mode=0o770) if self.data: fs.ensure_path(self.data, mode=0o770) ...
Saves a component in the given broker to the file system.
355,871
def collections(context): LOG.info("Running scout view collections") adapter = context.obj[] for collection_name in adapter.collections(): click.echo(collection_name)
Show all collections in the database
355,872
def special_typechecking(value, msg): result = True if msg.DESCRIPTOR.name == TARGET: result &= special_target_typecheck(value) elif msg.DESCRIPTOR.name == PLUGIN: result &= special_plugin_checking(value) return result
Special Typechecking not available via protocol itself :param value: <dict> :param msg: <proto object> :return: <bool>
355,873
def buildData(self, key, default=None): return self._buildData.get(nativestring(key), default)
Returns the build information for the given key. :param key | <str> default | <variant> :return <variant>
355,874
def create_snapshot_chart(self, filename=): try: from pylab import figure, title, xlabel, ylabel, plot, fill, legend, savefig import matplotlib.mlab as mlab except ImportError: return self.nopylab_msg % ("memory allocation") classlist = self.tracked_...
Create chart that depicts the memory allocation over time apportioned to the tracked classes.
355,875
def invoke_hook_bolt_execute(self, heron_tuple, execute_latency_ns): if len(self.task_hooks) > 0: bolt_execute_info = \ BoltExecuteInfo(heron_tuple=heron_tuple, executing_task_id=self.get_task_id(), execute_latency_ms=execute_latency_ns * system_con...
invoke task hooks for every time bolt processes a tuple :type heron_tuple: HeronTuple :param heron_tuple: tuple that is executed :type execute_latency_ns: float :param execute_latency_ns: execute latency in nano seconds
355,876
def parse_env_var(s): parts = s.split(, 1) if len(parts) == 2: k, v = parts return (k, v) k = parts[0] return (k, os.getenv(k, ))
Parse an environment variable string Returns a key-value tuple Apply the same logic as `docker run -e`: "If the operator names an environment variable without specifying a value, then the current value of the named variable is propagated into the container's environment
355,877
def run(self): while True: msg = self._queue.get() if msg is _SHUTDOWN: break event, args, kwargs = msg self._logger(, event) for func in self._callbacks.get(event, []): func(*args, **kwargs)
Process all callbacks, until `stop()` is called. Intended to run in its own thread.
355,878
def execute(opts, data, func, args, kwargs): re dead set on getting the output from the CLI command, then make sure to set the timeout (with the -t flag) to something greater than the splaytime (max splaytime + time to execute job). Otherwise, it[splay, direct_call]*[splay, direct_call]{spla...
Splay a salt function call execution time across minions over a number of seconds (default: 300) .. note:: You *probably* want to use --async here and look up the job results later. If you're dead set on getting the output from the CLI command, then make sure to set the timeout (with th...
355,879
def export(self, location): temp_dir = tempfile.mkdtemp(, ) self.unpack(temp_dir) if os.path.exists(location): rmtree(location) try: self.run_command([, location], cwd=temp_dir, show_stdout=False) finally:...
Export the Bazaar repository at the url to the destination location
355,880
def connected_component(self, ident): a ident = normalize_ident(ident) done = set() todo = set([ident]) labels = set() while todo: ident = todo.pop() done.add(ident) for label in self.directly_connected(ident): if la...
Return a connected component generator for ``ident``. ``ident`` may be a ``content_id`` or a ``(content_id, subtopic_id)``. Given an ``ident``, return the corresponding connected component by following all positive transitivity relationships. For example, if ``(a, b, 1)`` is a...
355,881
def notifications_dismiss(self, id): id = self.__unpack_id(id) params = self.__generate_params(locals()) self.__api_request(, , params)
Deletes a single notification
355,882
def output(context, id): colors = { : , : , : , : } result = job.list_jobstates(context, id=id, sort=) jobstates = result.json()[] for js in jobstates: color = colors.get(js[], ) click.echo( % ( color, js[], js[])...
output(context, id) Show a job output. >>> dcictl job-output [OPTIONS] :param string id: ID of the job to show [required]
355,883
def save(self): e = self.editor self._style = e.current_style self._show_line_numbers = e.show_line_numbers self._highlight_search = e.highlight_search self._show_ruler = e.show_ruler self._relative_number = e.relative_number self._cursorcolumn = e.curso...
Back up current editor state.
355,884
def save_to_path(self, file_path, chunk_size=DOWNLOAD_FILE_CHUNK_SIZE): response = self._get_download_response() with open(file_path, ) as f: for chunk in response.iter_content(chunk_size=chunk_size): if chunk: f.write(chunk)
Save the contents of the remote file to a local path. :param file_path: str: file path :param chunk_size: chunk size used to write local file
355,885
def ari(reference_intervals, reference_labels, estimated_intervals, estimated_labels, frame_size=0.1): validate_structure(reference_intervals, reference_labels, estimated_intervals, estimated_labels) if reference_intervals.size == 0 or estimated_intervals.size =...
Adjusted Rand Index (ARI) for frame clustering segmentation evaluation. Examples -------- >>> (ref_intervals, ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab') >>> (est_intervals, ... est_labels) = mir_eval.io.load_labeled_intervals('est.lab') >>> # Trim or pad the estimate ...
355,886
def save(self): course_id = self.validated_data[] __, created = models.EnterpriseCourseEnrollment.objects.get_or_create( enterprise_customer_user=self.enterprise_customer_user, course_id=course_id, ) if created: track_enrollment(, self.ente...
Save the model with the found EnterpriseCustomerUser.
355,887
def set_axis_color(axis, color, alpha=None): for side in (, , , ): spine = axis.spines[side] spine.set_color(color) if alpha is not None: spine.set_alpha(alpha)
Sets the spine color of all sides of an axis (top, right, bottom, left).
355,888
def lzs (inlist): zscores = [] for item in inlist: zscores.append(z(inlist,item)) return zscores
Returns a list of z-scores, one for each score in the passed list. Usage: lzs(inlist)
355,889
def list(self): queue = self._get_queue() if queue is None: raise QueueDoesntExist output = self.check_output( % shell_escape(queue / )) job_id, info = None, None for line in output.splitlines(): line = line.de...
Lists the jobs on the server.
355,890
def deconv_rl(data, h, Niter=10, mode_conv="fft", log_iter=False): if isinstance(data, np.ndarray): mode_data = "np" elif isinstance(data, OCLArray): mode_data = "gpu" else: raise TypeError("array argument (1) has bad type: %s"%type(arr_obj)) if mode_conv=="fft": r...
richardson lucy deconvolution of data with psf h using spatial convolutions (h should be small then) mode_conv = "fft" or "spatial"
355,891
def _render_conditions(conditions): if not conditions: return "" rendered_conditions = [] for condition in conditions: field = condition.get() field_type = condition.get() comparators = condition.get() if None in (field, field_type, comparators) or not compar...
Render the conditions part of a query. Parameters ---------- conditions : list A list of dictionary items to filter a table. Returns ------- str A string that represents the "where" part of a query See Also -------- render_query : Further clarification of `conditio...
355,892
def _pdf(self, **kwargs): return self._polardist._pdf(**kwargs) * \ self._azimuthaldist._pdf(**kwargs)
Returns the pdf at the given angles. Parameters ---------- \**kwargs: The keyword arguments should specify the value for each angle, using the names of the polar and azimuthal angles as the keywords. Unrecognized arguments are ignored. Returns ...
355,893
def createStateText(self): self.modeText = self.axes.text(self.leftPos+(self.vertSize/10.0),0.97,,color=,size=1.5*self.fontSize,ha=,va=) self.modeText.set_path_effects([PathEffects.withStroke(linewidth=self.fontSize/10.0,foreground=)])
Creates the mode and arm state text.
355,894
def remove_artifacts_from_biom_table(table_filename, fasta_filename, ref_fp, biom_table_dir, ref_db_fp, threads=1, ...
Remove artifacts from a biom table using SortMeRNA Parameters ---------- table : str name of the biom table file fasta_filename : str the fasta file containing all the sequences of the biom table Returns ------- tmp_files : list of str The temp files created during ...
355,895
def run(self): route("/")(self.serve) if self.config.html: route("/<filepath:path>")(self.custom_html) if self.config.fuzz_web: self.request_checker.start() self.httpd.start() self.httpsd.start()
Start the servers
355,896
def value(self): X = self.X return self.scale * (X @ X.T)
Covariance matrix. Returns ------- K : ndarray s⋅XXᵀ.
355,897
def get_header(self): raw_header = yield get_arg(self, 1) if not self.serializer: raise tornado.gen.Return(raw_header) else: header = self.serializer.deserialize_header(raw_header) raise tornado.gen.Return(header)
Get the header value from the response. :return: a future contains the deserialized value of header
355,898
def evaluate_inkml(inkml_file_path): logging.info("Start evaluating ...", inkml_file_path) ret = {: inkml_file_path} recording = inkml.read(inkml_file_path) results = evaluate(json.dumps(recording.get_sorted_pointlist()), result_format=) ret[] = results return ret
Evaluate an InkML file. Parameters ---------- inkml_file_path : string path to an InkML file Returns ------- dictionary The dictionary contains the keys 'filename' and 'results', where 'results' itself is a list of dictionaries. Each of the results has the keys ...
355,899
def set_instance(self, env, instance, previous_instance, cim_class): raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED, "")
Return a newly created or modified instance. Keyword arguments: env -- Provider Environment (pycimmb.ProviderEnvironment) instance -- The new pywbem.CIMInstance. If modifying an existing instance, the properties on this instance have been filtered by the PropertyList fr...