code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def devices(): ''' Get known BTRFS formatted devices on the system. CLI Example: .. code-block:: bash salt '*' btrfs.devices ''' out = __salt__['cmd.run_all']("blkid -o export") salt.utils.fsutils._verify_run(out) return salt.utils.fsutils._blkid_output(out['stdout'], fs_type...
Get known BTRFS formatted devices on the system. CLI Example: .. code-block:: bash salt '*' btrfs.devices
def handle_read(self): """ Accept any incoming connections. """ with self._lock: logger.debug("handle_read()") if self._socket is None: return while True: try: sock, address = self._socket.accept() ...
Accept any incoming connections.
def push(self): """Push tutorials to Transifex.""" tx = Tx(self.tx_project_slug) if self.options.resources: articles = [ self.desk.articles().by_id(r.strip()) for r in self.options.resources.split(',') ] else: articles...
Push tutorials to Transifex.
def load_module_stages(self, mod): '''Add external stages from the Python module `mod`. If `mod` is a string, then it will be interpreted as the name of a module; otherwise it is an actual module object. The module should exist somewhere in :data:`sys.path`. The module must co...
Add external stages from the Python module `mod`. If `mod` is a string, then it will be interpreted as the name of a module; otherwise it is an actual module object. The module should exist somewhere in :data:`sys.path`. The module must contain a `Stages` dictionary, which is a map fr...
def handle_nested_relation(self, line: str, position: int, tokens: ParseResults): """Handle nested statements. If :code:`allow_nested` is False, raises a ``NestedRelationWarning``. :raises: NestedRelationWarning """ if not self.allow_nested: raise NestedRelationWarn...
Handle nested statements. If :code:`allow_nested` is False, raises a ``NestedRelationWarning``. :raises: NestedRelationWarning
def farray(self): """Array of frequencies for the lower-edge of each frequency bin :type: `numpy.ndarray` """ bandwidths = 2 * pi ** (1/2.) * self.frequencies / self.q return self.frequencies - bandwidths / 2.
Array of frequencies for the lower-edge of each frequency bin :type: `numpy.ndarray`
def parse_planar_fault_geometry(node): """ Parses a planar fault geometry node returning both the attributes and parameters in a dictionary """ assert "planarSurface" in node.tag geometry = {"strike": node.attrib["strike"], "dip": node.attrib["dip"]} upper_depth = numpy.inf ...
Parses a planar fault geometry node returning both the attributes and parameters in a dictionary
def replace_spaces(s, replacer): # type: (str, Callable[[int, str], str]) -> str """ >>> replace_spaces('ab', lambda n, l: '_' * n) 'ab' >>> replace_spaces('a b', lambda n, l: '_' * n) 'a_b' >>> replace_spaces(' ab', lambda n, l: '_' * n) '_ab' >>> replace_spaces(' a b ', lambda n, ...
>>> replace_spaces('ab', lambda n, l: '_' * n) 'ab' >>> replace_spaces('a b', lambda n, l: '_' * n) 'a_b' >>> replace_spaces(' ab', lambda n, l: '_' * n) '_ab' >>> replace_spaces(' a b ', lambda n, s: s * n) 'leftleftacenterbright' >>> replace_spaces(' a b ', lambda n, _: '0 0' * n) ...
def log_used_nonce(self, username, iat, nonce): """ Log a nonce as being used, and therefore henceforth invalid. :param username: Username as a string. :param iat: Unix timestamp float or integer of when the nonce was used. :param nonce: Nonce value. """ # TODO: ...
Log a nonce as being used, and therefore henceforth invalid. :param username: Username as a string. :param iat: Unix timestamp float or integer of when the nonce was used. :param nonce: Nonce value.
def _read_channel(channel, stream, start, duration): """ Get channel using lalframe """ channel_type = lalframe.FrStreamGetTimeSeriesType(channel, stream) read_func = _fr_type_map[channel_type][0] d_type = _fr_type_map[channel_type][1] data = read_func(stream, channel, start, duration, 0) return...
Get channel using lalframe
def instance(): """ Creates an EC2 instance from an Ubuntu AMI and configures it as a Django server with nginx + gunicorn """ # Record the starting time and print a starting message start_time = time.time() print(_green("Started...")) # Use boto to create an EC2 instance env.host_st...
Creates an EC2 instance from an Ubuntu AMI and configures it as a Django server with nginx + gunicorn
def generate_algebra_simplify_sample(vlist, ops, min_depth, max_depth): """Randomly generate an algebra simplify dataset sample. Given an input expression, produce the simplified expression. Args: vlist: Variable list. List of chars that can be used in the expression. ops: List of ExprOp instances. The ...
Randomly generate an algebra simplify dataset sample. Given an input expression, produce the simplified expression. Args: vlist: Variable list. List of chars that can be used in the expression. ops: List of ExprOp instances. The allowed operators for the expression. min_depth: Expression trees will no...
def pipe(value, *functions, funcs=None): """pipe(value, f, g, h) == h(g(f(value)))""" if funcs: functions = funcs for function in functions: value = function(value) return value
pipe(value, f, g, h) == h(g(f(value)))
def localization_diff(localizable_file, translated_file, excluded_strings_file, output_translation_file): """ Generates a strings file representing the strings that were yet to be translated. Args: localizable_file (str): The path to the localization strings file, meaning the file that represents the s...
Generates a strings file representing the strings that were yet to be translated. Args: localizable_file (str): The path to the localization strings file, meaning the file that represents the strings that require translation. translated_file (str): The path to the translated strings fil...
def process_keystroke(self, inp, idx, offset): """ Process keystroke ``inp``, adjusting screen parameters. :param inp: return value of Terminal.inkey(). :type inp: blessed.keyboard.Keystroke :param idx: page index. :type idx: int :param offset: scrolling region o...
Process keystroke ``inp``, adjusting screen parameters. :param inp: return value of Terminal.inkey(). :type inp: blessed.keyboard.Keystroke :param idx: page index. :type idx: int :param offset: scrolling region offset of current page. :type offset: int :returns: ...
def IsNTFS(self): """Determines if the file system is NTFS. Returns: bool: True if the file system is NTFS. """ tsk_fs_type = self.GetFsType() return tsk_fs_type in [ pytsk3.TSK_FS_TYPE_NTFS, pytsk3.TSK_FS_TYPE_NTFS_DETECT]
Determines if the file system is NTFS. Returns: bool: True if the file system is NTFS.
def s_connect(self, server, port, r_server=None): """ Link a server. Required arguments: * server - Server to link with. * port - Port to use. Optional arguments: * r_server=None - Link r_server with server. """ with self.lock: if not r...
Link a server. Required arguments: * server - Server to link with. * port - Port to use. Optional arguments: * r_server=None - Link r_server with server.
def cleanup(self): """ Attempt to switch the device off or put into low power mode (this helps prolong the life of the device), clear the screen and close resources associated with the underlying serial interface. If :py:attr:`persist` is ``True``, the device will not be switche...
Attempt to switch the device off or put into low power mode (this helps prolong the life of the device), clear the screen and close resources associated with the underlying serial interface. If :py:attr:`persist` is ``True``, the device will not be switched off. This is a managed funct...
def timefun(fun): """ Timing decorator Timers require you to do some digging. Start wrapping a few of the higher level functions and confirm where the bottleneck is, then drill down into that function, repeating as you go. When you find the disproportionately slow bit of code, fix it, and work your...
Timing decorator Timers require you to do some digging. Start wrapping a few of the higher level functions and confirm where the bottleneck is, then drill down into that function, repeating as you go. When you find the disproportionately slow bit of code, fix it, and work your way back out confirming t...
def read(self, n): """Read data from file segs. Args: n: max bytes to read. Must be positive. Returns: some bytes. May be smaller than n bytes. "" when no more data is left. """ if self._EOF: return "" while self._seg_index <= self._last_seg_index: result = self._read_...
Read data from file segs. Args: n: max bytes to read. Must be positive. Returns: some bytes. May be smaller than n bytes. "" when no more data is left.
def report_usage_to_host(host_ip, vmid): #base value cpu_usage = 0.0 os_mem_usage = 0.0 task_mem_usage = 0.0 io_usage = 0.0 cpu_usage = get_cpu_usage() os_mem_usage = get_os_mem_usage() task_mem_usage = get_task_mem_usage() io_usage = get_io_usage() usage = str(vmid.strip())+' | '+str(cpu_usage)+' | '+str...
cmd = '/bin/ssh -n -q -o StrictHostKeyChecking=no root@host_ip \"/bin/nohup /bin/python /var/lib/virtdc/vmonere/host/vmonere_listener.py '+usage+' &\"' cmd = cmd.replace("host_ip",str(host_ip).strip())
def read_dataset_schema(schema_path: str) -> Dict[str, List[TableColumn]]: """ Reads a schema from the text2sql data, returning a dictionary mapping table names to their columns and respective types. This handles columns in an arbitrary order and also allows either ``{Table, Field}`` or ``{Table, Fi...
Reads a schema from the text2sql data, returning a dictionary mapping table names to their columns and respective types. This handles columns in an arbitrary order and also allows either ``{Table, Field}`` or ``{Table, Field} Name`` as headers, because both appear in the data. It also uppercases table a...
def find_db_instance(self, name, running=True): """ Searches for a db instance named :attr:`name`. :param str name: The name of the target db instance :param bool running: A flag to only look for instances that are actually *running*. :rtype: :class:`dict` ...
Searches for a db instance named :attr:`name`. :param str name: The name of the target db instance :param bool running: A flag to only look for instances that are actually *running*. :rtype: :class:`dict`
def save(file_name, content): """Save content to a file""" with open(file_name, "w", encoding="utf-8") as output_file: output_file.write(content) return output_file.name
Save content to a file
def _scan_smaller(self, seq, threshold=''): """ m._scan_smaller(seq, threshold='') -- Internal utility function for performing sequence scans The sequence is smaller than the PSSM. Are there good matches to regions of the PSSM? """ ll = self.ll #Shortcut for Log-likelih...
m._scan_smaller(seq, threshold='') -- Internal utility function for performing sequence scans The sequence is smaller than the PSSM. Are there good matches to regions of the PSSM?
def edit(self, name=None, description=None, start_date=None, due_date=None, assignees=None, status=None): """Edit the details of an activity. :param name: (optionally) edit the name of the activity :type name: basestring or None :param description: (optionally) edit the description of t...
Edit the details of an activity. :param name: (optionally) edit the name of the activity :type name: basestring or None :param description: (optionally) edit the description of the activity :type description: basestring or None :param start_date: (optionally) edit the start date...
def _is_finished(self, as_of): """Have the specified number of billing cycles been completed? If so, we should not be enacting this RecurringCost. """ if self.is_one_off(): last_billing_cycle = self.get_billing_cycles()[self.total_billing_cycles - 1] return last_...
Have the specified number of billing cycles been completed? If so, we should not be enacting this RecurringCost.
def nom_diam_pipe(self): """The nominal diameter of the LFOM pipe""" ID = pc.diam_circle(self.area_pipe_min) return pipe.ND_SDR_available(ID, self.sdr)
The nominal diameter of the LFOM pipe
def mangle_name(name): """Mangles a column name to a standard form, remoing illegal characters. :param name: :return: """ import re try: return re.sub('_+', '_', re.sub('[^\w_]', '_', name).lower()).rstrip('_') except TypeError: r...
Mangles a column name to a standard form, remoing illegal characters. :param name: :return:
def get_problem_name(base_name, was_reversed=False, was_copy=False): """Construct a problem name from base and reversed/copy options. Inverse of `parse_problem_name`. Args: base_name: base problem name. Should not end in "_rev" or "_copy" was_reversed: if the problem is to be reversed was_copy: if t...
Construct a problem name from base and reversed/copy options. Inverse of `parse_problem_name`. Args: base_name: base problem name. Should not end in "_rev" or "_copy" was_reversed: if the problem is to be reversed was_copy: if the problem is to be copied Returns: string name consistent with use...
def categories(self, value): """ Setter for **self.__categories** attribute. :param value: Attribute value. :type value: dict """ if value is not None: assert type(value) is dict, "'{0}' attribute: '{1}' type is not 'dict'!".format("categories", value) ...
Setter for **self.__categories** attribute. :param value: Attribute value. :type value: dict
def get_agents(self, addr=True, agent_cls=None, as_coro=False): """Get agents from the slave environments. :param bool addr: If ``True``, returns only addresses of the agents, otherwise returns a :class:`Proxy` object for each agent. :param agent_cls: If spe...
Get agents from the slave environments. :param bool addr: If ``True``, returns only addresses of the agents, otherwise returns a :class:`Proxy` object for each agent. :param agent_cls: If specified, returns only agents that are members of that particular...
def pretty_print(input_word, anagrams, by_length=False): """Prints the anagram results sorted by score to stdout. Args: input_word: the base word we searched on anagrams: generator of (word, score) from anagrams_in_word by_length: a boolean to declare printing by length instead of score...
Prints the anagram results sorted by score to stdout. Args: input_word: the base word we searched on anagrams: generator of (word, score) from anagrams_in_word by_length: a boolean to declare printing by length instead of score
def html(self): """ Return an HTML representation of the snippet. """ formatter = HtmlFormatter( cssclass=self.DIV_CSS_CLASS, linenos=True, linenostart=self._start_line, hl_lines=self._shift_lines( self._violation_lines, ...
Return an HTML representation of the snippet.
def get_view_mode_id(self, view_mode): '''Attempts to return a view_mode_id for a given view_mode taking into account the current skin. If not view_mode_id can be found, None is returned. 'thumbnail' is currently the only suppported view_mode. ''' view_mode_ids = VIEW_MOD...
Attempts to return a view_mode_id for a given view_mode taking into account the current skin. If not view_mode_id can be found, None is returned. 'thumbnail' is currently the only suppported view_mode.
def stop_webserver(server): """ Stop server """ #TODO - distinguish between a warning and a error on apache if server == 'apache2': with settings(warn_only=True): if env.verbosity: print env.host,"STOPPING apache2" a = sudo("/etc/init.d/apache2 stop") ...
Stop server
def addinputfile(project, filename, credentials=None): #pylint: disable=too-many-return-statements """Add a new input file, this invokes the actual uploader""" printdebug('Addinputfile: Initialising' ) user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable ...
Add a new input file, this invokes the actual uploader
def _disable_access_key(self, force_disable_self=False): """This function first checks to see if the key is already disabled\ if not then it goes to disabling """ client = self.client if self.validate is True: return else: try: cli...
This function first checks to see if the key is already disabled\ if not then it goes to disabling
def setup_file_list(self, filter_text, current_path): """Setup list widget content for file list display.""" short_paths = shorten_paths(self.paths, self.save_status) paths = self.paths icons = self.icons results = [] trying_for_line_number = ':' in filter_text #...
Setup list widget content for file list display.
def _CanProcessKeyWithPlugin(self, registry_key, plugin): """Determines if a plugin can process a Windows Registry key or its values. Args: registry_key (dfwinreg.WinRegistryKey): Windows Registry key. plugin (WindowsRegistryPlugin): Windows Registry plugin. Returns: bool: True if the Re...
Determines if a plugin can process a Windows Registry key or its values. Args: registry_key (dfwinreg.WinRegistryKey): Windows Registry key. plugin (WindowsRegistryPlugin): Windows Registry plugin. Returns: bool: True if the Registry key can be processed with the plugin.
def xml_import(self, filepath="", xml_content=None, markings=None, identifier_ns_uri=None, **kwargs): """ Import a STIX or CybOX xml from file <filepath> or a string passed as ``xml_content`` You c...
Import a STIX or CybOX xml from file <filepath> or a string passed as ``xml_content`` You can furhter provide: - a list of InfoObjects as markings with which all generated Information Objects will be associated (e.g., in order to provide provenance function) - a default identif...
def flow_pipeline(diameters, lengths, k_minors, target_headloss, nu=con.WATER_NU, pipe_rough=mats.PVC_PIPE_ROUGH): """ This function takes a single pipeline with multiple sections, each potentially with different diameters, lengths and minor loss coefficients and determines the flow rate f...
This function takes a single pipeline with multiple sections, each potentially with different diameters, lengths and minor loss coefficients and determines the flow rate for a given headloss. :param diameters: list of diameters, where the i_th diameter corresponds to the i_th pipe section :type diameters: ...
def fnmatch_pathname_to_regex(pattern): """ Implements fnmatch style-behavior, as though with FNM_PATHNAME flagged; the path seperator will not match shell-style '*' and '.' wildcards. """ i, n = 0, len(pattern) nonsep = ''.join(['[^', os.sep, ']']) res = [] while i < n: c = pattern[i] i = i + 1 if c == '...
Implements fnmatch style-behavior, as though with FNM_PATHNAME flagged; the path seperator will not match shell-style '*' and '.' wildcards.
def _call_to(self, from_node, to_func, ret_node, stmt_idx=None, ins_addr=None, return_to_outside=False): """ Registers an edge between the caller basic block and callee function. :param from_addr: The basic block that control flow leaves during the transition. :type from_addr: angr...
Registers an edge between the caller basic block and callee function. :param from_addr: The basic block that control flow leaves during the transition. :type from_addr: angr.knowledge.CodeNode :param to_func: The function that we are calling :type to_func: Function ...
def get_version( here_path, default_version=DEFAULT_VERSION, ): """tries to resolve version number Args: here_path (str): path to project local dir default_version (str): what version to return if all else fails Returns: str: semantic_version information for library...
tries to resolve version number Args: here_path (str): path to project local dir default_version (str): what version to return if all else fails Returns: str: semantic_version information for library
def compute_srcprob(self,xmlfile=None, overwrite=False): """Run the gtsrcprob app with the current model or a user provided xmlfile""" for i,c in enumerate(self.components): # compute diffuse response, necessary for srcprob c._diffrsp_app(xmlfile=xmlfile) # compute s...
Run the gtsrcprob app with the current model or a user provided xmlfile
def has_custom_image(user_context, app_id): """Returns True if there exists a custom image for app_id.""" possible_paths = _valid_custom_image_paths(user_context, app_id) return any(map(os.path.exists, possible_paths))
Returns True if there exists a custom image for app_id.
def send_mail_template(subject, template, addr_from, addr_to, context=None, attachments=None, fail_silently=None, addr_bcc=None, headers=None): """ Send email rendering text and html versions for the specified template name using the context dictionary passed in...
Send email rendering text and html versions for the specified template name using the context dictionary passed in.
def action(self, column=None, value=None, **kwargs): """ The underlying GICS table provides codes and descriptions identifying the current status or disposition of a grant project. >>> GICS().action('action_code', 'A') """ return self._resolve_call('GIC_ACTION', column, ...
The underlying GICS table provides codes and descriptions identifying the current status or disposition of a grant project. >>> GICS().action('action_code', 'A')
def pretty_render(data, format='text', indent=0): """ Render a dict based on a format """ if format == 'json': return render_json(data) elif format == 'html': return render_html(data) elif format == 'xml': return render_xml(data) else: return dict_to_plaintext...
Render a dict based on a format
def filelist_prune(self, at_data, *args, **kwargs): """ Given a list of files, possibly prune list by extension. """ b_status = True l_file = [] str_path = at_data[0] al_file = at_data[1] if len(self.str_extension): al_...
Given a list of files, possibly prune list by extension.
def get_url(cls, ticket): """ 通过ticket换取二维码地址 详情请参考 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1443433542 :param ticket: 二维码 ticket 。可以通过 :func:`create` 获取到 :return: 返回的二维码地址 使用示例:: from wechatpy import WeChatClient client =...
通过ticket换取二维码地址 详情请参考 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1443433542 :param ticket: 二维码 ticket 。可以通过 :func:`create` 获取到 :return: 返回的二维码地址 使用示例:: from wechatpy import WeChatClient client = WeChatClient('appid', 'secret') u...
def decorate(self, output_tree, output_tax, unique_names): ''' Decorate a tree with taxonomy. This code does not allow inconsistent taxonomy within a clade. If one sequence in a clade has a different annotation to the rest, it will split the clade. Paraphyletic group names are di...
Decorate a tree with taxonomy. This code does not allow inconsistent taxonomy within a clade. If one sequence in a clade has a different annotation to the rest, it will split the clade. Paraphyletic group names are distinguished if unique_names = True using a simple tally of each group (...
def parse_info(response): '''Parse the response of Redis's INFO command into a Python dict. In doing so, convert byte data into unicode.''' info = {} response = response.decode('utf-8') def get_value(value): if ',' and '=' not in value: return value sub_dict = {} ...
Parse the response of Redis's INFO command into a Python dict. In doing so, convert byte data into unicode.
def transcode(self, source, destinations, **kwargs): """ Changes the compression characteristics of an audio and/or video stream. Allows you to change the resolution of a source stream, change the bitrate of a stream, change a VP8 or MPEG2 stream into H.264 and much more. Allow u...
Changes the compression characteristics of an audio and/or video stream. Allows you to change the resolution of a source stream, change the bitrate of a stream, change a VP8 or MPEG2 stream into H.264 and much more. Allow users to create overlays on the final stream as well as crop strea...
def velocity(adata, var_names=None, basis=None, groupby=None, groups=None, mode=None, fits='all', layers='all', color=None, color_map='RdBu_r', colorbar=False, perc=[2,98], use_raw=False, size=None, alpha=.5, fontsize=None, figsize=None, dpi=None, show=True, save=None, ax=None, ncols=None, **k...
Phase and velocity plot for set of genes. The phase plot shows spliced against unspliced expressions with steady-state fit. Further the embedding is shown colored by velocity and expression. Arguments --------- adata: :class:`~anndata.AnnData` Annotated data matrix. var_names: `str` or...
def rho(self): r'''Mass density of the chemical at its current phase and temperature and pressure, in units of [kg/m^3]. Utilizes the object oriented interfaces :obj:`thermo.volume.VolumeSolid`, :obj:`thermo.volume.VolumeLiquid`, and :obj:`thermo.volume.VolumeGas` to per...
r'''Mass density of the chemical at its current phase and temperature and pressure, in units of [kg/m^3]. Utilizes the object oriented interfaces :obj:`thermo.volume.VolumeSolid`, :obj:`thermo.volume.VolumeLiquid`, and :obj:`thermo.volume.VolumeGas` to perform the actual...
def update_session(self, alias, headers=None, cookies=None): """Update Session Headers: update a HTTP Session Headers ``alias`` Robot Framework alias to identify the session ``headers`` Dictionary of headers merge into session """ session = self._cache.switch(alias) ses...
Update Session Headers: update a HTTP Session Headers ``alias`` Robot Framework alias to identify the session ``headers`` Dictionary of headers merge into session
def get_thread_id_for_variable_reference(self, variable_reference): ''' We can't evaluate variable references values on any thread, only in the suspended thread (the main reason for this is that in UI frameworks inspecting a UI object from a different thread can potentially crash the app...
We can't evaluate variable references values on any thread, only in the suspended thread (the main reason for this is that in UI frameworks inspecting a UI object from a different thread can potentially crash the application). :param int variable_reference: The variable reference (c...
def filter_broker_list(brokers, filter_by): """Returns sorted list, a subset of elements from brokers in the form [(id, host)]. Passing empty list for filter_by will return empty list. :param brokers: list of brokers to filter, assumes the data is in so`rted order :type brokers: list of (id, host) ...
Returns sorted list, a subset of elements from brokers in the form [(id, host)]. Passing empty list for filter_by will return empty list. :param brokers: list of brokers to filter, assumes the data is in so`rted order :type brokers: list of (id, host) :param filter_by: the list of ids of brokers to kee...
def _do_scale_fit(freqs, signal, model, w=None): """ Perform a round of fitting to deal with over or under-estimation. Scales curve on y-axis but preserves shape. Parameters ---------- freqs : array signal : array The signal that the model is being fit to model : array The model bei...
Perform a round of fitting to deal with over or under-estimation. Scales curve on y-axis but preserves shape. Parameters ---------- freqs : array signal : array The signal that the model is being fit to model : array The model being scaled w : array weighting function Returns...
def getReqId(self) -> int: """ Get new request ID. """ if not self.isReady(): raise ConnectionError('Not connected') newId = self._reqIdSeq self._reqIdSeq += 1 return newId
Get new request ID.
def _prepare_wsdl_objects(self): """ Create the data structure and get it ready for the WSDL request. """ self.CarrierCode = 'FDXE' self.RoutingCode = 'FDSD' self.Address = self.client.factory.create('Address') self.ShipDateTime = datetime.datetime.now().isoformat...
Create the data structure and get it ready for the WSDL request.
def _add_gradient_scalar(self, name:str, scalar_value)->None: "Writes a single scalar value for a gradient statistic to Tensorboard." tag = self.name + '/gradients/' + name self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=self.iteration)
Writes a single scalar value for a gradient statistic to Tensorboard.
def _parse_bands(lines, n_start): """Parse band structure from cp2k output""" kpoints = [] labels = [] bands_s1 = [] bands_s2 = [] known_kpoints = {} pattern = re.compile(".*?Nr.*?Spin.*?K-Point.*?", re.DOTALL) selected_lines = lines[n_start:] for...
Parse band structure from cp2k output
def create(self, id, fd, filename='attachment-name'): # pylint: disable=invalid-name,redefined-builtin """Add an attachment to a device. :param id: Device ID as an int. :param fd: File-like object to upload. :param filename: (optional) Name to use for new attachment as a string. ...
Add an attachment to a device. :param id: Device ID as an int. :param fd: File-like object to upload. :param filename: (optional) Name to use for new attachment as a string. :return: :class:`attachments.Attachment <attachments.Attachment>` object :rtype: attachments.Attachment
def add_all_exchange_reactions(model, compartment, allow_duplicates=False): """Add all exchange reactions to database and to model. Args: model: :class:`psamm.metabolicmodel.MetabolicModel`. """ all_reactions = {} if not allow_duplicates: # TODO: Avoid adding reactions that already...
Add all exchange reactions to database and to model. Args: model: :class:`psamm.metabolicmodel.MetabolicModel`.
def _pop_translated_data(self): """ Separate data of translated fields from other data. """ translated_data = {} for meta in self.Meta.model._parler_meta: translations = self.validated_data.pop(meta.rel_name, {}) if translations: translated...
Separate data of translated fields from other data.
def load(self, callables_fname): r""" Load traced modules information from a `JSON <http://www.json.org/>`_ file. The loaded module information is merged with any existing module information :param callables_fname: File name :type callables_fname: :ref:`FileNameExists` ...
r""" Load traced modules information from a `JSON <http://www.json.org/>`_ file. The loaded module information is merged with any existing module information :param callables_fname: File name :type callables_fname: :ref:`FileNameExists` :raises: * OSError (File *[fna...
def build_combined_label(sl, idxs, sep=' ', label_format=None): """ Generate a combined label from a list of indexes into sl, by joining them with `sep` (str). :param sl: Strings to combine :type sl: dict of str :param idxs: Indexes into sl :type idxs: list of sl keys :param sep: :...
Generate a combined label from a list of indexes into sl, by joining them with `sep` (str). :param sl: Strings to combine :type sl: dict of str :param idxs: Indexes into sl :type idxs: list of sl keys :param sep: :return: `str` of combined label
def remove_item(name, system_wide=False): '''Removes a program from startup. Removes a program from startup. Args: name (str) : The name of the program (as known to the system) to remove. See :func:``list_items``. system_wide (bool): Remove it from system-wide startup. Note: ``system_wide`` require...
Removes a program from startup. Removes a program from startup. Args: name (str) : The name of the program (as known to the system) to remove. See :func:``list_items``. system_wide (bool): Remove it from system-wide startup. Note: ``system_wide`` requires superuser/admin privileges.
def sun_utc(self, date, latitude, longitude, observer_elevation=0): """Calculate all the info for the sun at once. All times are returned in the UTC timezone. :param date: Date to calculate for. :type date: :class:`datetime.date` :param latitude: Latitude - Northe...
Calculate all the info for the sun at once. All times are returned in the UTC timezone. :param date: Date to calculate for. :type date: :class:`datetime.date` :param latitude: Latitude - Northern latitudes should be positive :type latitude: float :param...
def validate_resource(self, value): """Validate the network resource with exponential backoff""" def do_backoff(*args, **kwargs): """Call self._test_connection with exponential backoff, for self._max_tries attempts""" attempts = 0 while True: try: ...
Validate the network resource with exponential backoff
def make_otp_response(vres, client_key): """ Create validation response (signed, if a client key is supplied). """ if client_key is not None: sig = make_signature(vres, client_key) vres['h'] = sig # produce "key=value" pairs from vres pairs = [x + "=" + ''.join(vres[x]) for x in ...
Create validation response (signed, if a client key is supplied).
def guid(self): ''' Use elements from this hash set to create a unique (re)identifier. ''' iden = hashlib.md5() props = {'size': self.size} for name, item in self.hashes: iden.update(item.digest()) props[name] = item.hexdigest() r...
Use elements from this hash set to create a unique (re)identifier.
def add_corpus(self, name, description): '''Add a corpus to your account''' corpora_url = self.base_url + self.CORPORA_PAGE data = {'name': name, 'description': description} result = self.session.post(corpora_url, data=data) if result.status_code == 201: return Corpus...
Add a corpus to your account
def sort_by_distance_percentage(cls, consumer_offsets_metadata): """Receives a dict of (topic_name: ConsumerPartitionOffset) and returns an similar dict where the topics are sorted by average offset distance in percentage.""" sorted_offsets = sorted( list(consumer_offsets_met...
Receives a dict of (topic_name: ConsumerPartitionOffset) and returns an similar dict where the topics are sorted by average offset distance in percentage.
def get_internet_gateway(vpc, **conn): """Gets the Internet Gateway details about a VPC""" result = {} ig_result = describe_internet_gateways(Filters=[{"Name": "attachment.vpc-id", "Values": [vpc["id"]]}], **conn) if ig_result: # Only 1 IG can be attached to a VPC: result.update({ ...
Gets the Internet Gateway details about a VPC
def delete_cookies(): """Deletes cookie(s) as provided by the query string and redirects to cookie list. --- tags: - Cookies parameters: - in: query name: freeform explode: true allowEmptyValue: true schema: type: object additionalPropertie...
Deletes cookie(s) as provided by the query string and redirects to cookie list. --- tags: - Cookies parameters: - in: query name: freeform explode: true allowEmptyValue: true schema: type: object additionalProperties: type: string ...
def _check_index(self, key: Union[slice, int]) -> (int, int): """Return adjusted start and stop index as tuple. Used in __setitem__ and __delitem__. """ ss, se = self._span if isinstance(key, int): if key < 0: key += se - ss if key < ...
Return adjusted start and stop index as tuple. Used in __setitem__ and __delitem__.
def balance_of(self, b58_address: str) -> int: """ This interface is used to call the BalanceOf method in ope4 that query the ope4 token balance of the given base58 encode address. :param b58_address: the base58 encode address. :return: the oep4 token balance of the base58 encod...
This interface is used to call the BalanceOf method in ope4 that query the ope4 token balance of the given base58 encode address. :param b58_address: the base58 encode address. :return: the oep4 token balance of the base58 encode address.
def with_slots(cls): """ Decorator for a class with _slots_. It automatically defines the methods __eq__, __ne__, assert_equal. """ def _compare(self, other): for slot in self.__class__._slots_: attr = operator.attrgetter(slot) source = attr(self) target =...
Decorator for a class with _slots_. It automatically defines the methods __eq__, __ne__, assert_equal.
def create_path(path, is_dir=False): """ Check if path exists, if not create it :param path: path or file to create directory for :param is_dir: pass True if we are passing in a directory, default = False :return: os safe path from `path` """ path = norm_path(path) path_check = path ...
Check if path exists, if not create it :param path: path or file to create directory for :param is_dir: pass True if we are passing in a directory, default = False :return: os safe path from `path`
def starting_at(self, datetime_or_str): """ Set the starting time for the cron job. If not specified, the starting time will always be the beginning of the interval that is current when the cron is started. :param datetime_or_str: a datetime object or a string that dateutil.parser can ...
Set the starting time for the cron job. If not specified, the starting time will always be the beginning of the interval that is current when the cron is started. :param datetime_or_str: a datetime object or a string that dateutil.parser can understand :return: self
def make_tensor_value_info( name, # type: Text elem_type, # type: int shape, # type: Optional[Sequence[Union[Text, int]]] doc_string="", # type: Text shape_denotation=None, # type: Optional[List[Text]] ): # type: (...) -> ValueInfoProto """Makes a ValueInfoProto based o...
Makes a ValueInfoProto based on the data type and shape.
def _proc_node_stmt(self, toks): """ Return (ADD_NODE, node_name, options) """ opts = toks[1] dummy_node = Node("dummy") # Coerce attribute types. for key, value in opts.iteritems(): trait = dummy_node.trait(key) if trait is not None: ...
Return (ADD_NODE, node_name, options)
def read_from_endpoint(self, endpoint, timeout=15): """ Blocking read from an endpoint. Will block until a message is received, or it times out. Also see :meth:`get_endpoint_queue` if you are considering calling this in a loop. .. warning:: Avoid calling this method from an e...
Blocking read from an endpoint. Will block until a message is received, or it times out. Also see :meth:`get_endpoint_queue` if you are considering calling this in a loop. .. warning:: Avoid calling this method from an endpoint callback; doing so is likely to lead to deadlock. .. no...
def neurons(self): """ Return list of neuron indices. Parameters ---------- None Returns ------- list list of neuron indices See also -------- sqlite3.connect.cursor """ ...
Return list of neuron indices. Parameters ---------- None Returns ------- list list of neuron indices See also -------- sqlite3.connect.cursor
def tab_should_insert_whitespace(): """ When the 'tab' key is pressed with only whitespace character before the cursor, do autocompletion. Otherwise, insert indentation. Except for the first character at the first line. Then always do a completion. It doesn't make sense to start the first line with...
When the 'tab' key is pressed with only whitespace character before the cursor, do autocompletion. Otherwise, insert indentation. Except for the first character at the first line. Then always do a completion. It doesn't make sense to start the first line with indentation.
def add_node(self, node): """add a node class of HomieNode to this device""" self.nodes.append(node) # add node_ids try: if node.node_id != b"$stats": self.node_ids.append(node.node_id) except NotImplementedError: raise except Exce...
add a node class of HomieNode to this device
def extract_agg_losses(dstore, what): """ Aggregate losses of the given loss type and tags. Use it as /extract/agg_losses/structural?taxonomy=RC&zipcode=20126 /extract/agg_losses/structural?taxonomy=RC&zipcode=* :returns: an array of shape (T, R) if one of the tag names has a `*` value ...
Aggregate losses of the given loss type and tags. Use it as /extract/agg_losses/structural?taxonomy=RC&zipcode=20126 /extract/agg_losses/structural?taxonomy=RC&zipcode=* :returns: an array of shape (T, R) if one of the tag names has a `*` value an array of shape (R,), being R the number of ...
def process_key(processor, fn): """ :param processor: a function to process the key returned by the supplied key function :param fn: a key function :return: a function that wraps around the supplied key function to further process the key before returning. """ d...
:param processor: a function to process the key returned by the supplied key function :param fn: a key function :return: a function that wraps around the supplied key function to further process the key before returning.
def create_service(self, service_type, plan_name, service_name, params, async=False, **kwargs): """ Create a service instance. """ if self.space.has_service_with_name(service_name): logging.warning("Service already exists with that name.") return self....
Create a service instance.
def letter_scales(counts): """Convert letter counts to frequencies, sorted increasing.""" try: scale = 1.0 / sum(counts.values()) except ZeroDivisionError: # This logo is all gaps, nothing can be done return [] freqs = [(aa, cnt*scale) for aa, cnt in counts.iteritems() if cnt] ...
Convert letter counts to frequencies, sorted increasing.
def get_redirect_url(request): """Redirects to referring page, or CAS_REDIRECT_URL if no referrer is set. """ next_ = request.GET.get(REDIRECT_FIELD_NAME) if not next_: redirect_url = resolve_url(django_settings.CAS_REDIRECT_URL) if django_settings.CAS_IGNORE_REFERER: ne...
Redirects to referring page, or CAS_REDIRECT_URL if no referrer is set.
def _get_fields_for_model(model): """ Gets all of the fields on the model. :param DeclarativeModel model: A SQLAlchemy ORM Model :return: A tuple of the fields on the Model corresponding to the columns on the Model. :rtype: tuple """ fields = [] for name in model._sa_class_manag...
Gets all of the fields on the model. :param DeclarativeModel model: A SQLAlchemy ORM Model :return: A tuple of the fields on the Model corresponding to the columns on the Model. :rtype: tuple
def draw_edges(self): """ Renders edges to the figure. """ for i, (start, end) in enumerate(self.graph.edges()): start_theta = node_theta(self.nodes, start) end_theta = node_theta(self.nodes, end) verts = [ get_cartesian(self.plot_radiu...
Renders edges to the figure.
def _is_valid_inherit_element(self, element): """ Check that the children of element can be manipulated to apply the CSS properties. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement :return: True if the children of element can ...
Check that the children of element can be manipulated to apply the CSS properties. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement :return: True if the children of element can be manipulated to apply the CSS properties or Fal...
def peer_retrieve_by_prefix(prefix, relation_name='cluster', delimiter='_', inc_list=None, exc_list=None): """ Retrieve k/v pairs given a prefix and filter using {inc,exc}_list """ inc_list = inc_list if inc_list else [] exc_list = exc_list if exc_list else [] peerdb_settings...
Retrieve k/v pairs given a prefix and filter using {inc,exc}_list
def _normalize_attrs(attrs, null=None): """Returns an OrderedDict of attirbutes with the keys normalized by _normalize_name and the values normalized by _normalize_value. The value of :null: is passed to _normalize_value. However, if :null: is None, any values that are None are left out of the returned dict. A...
Returns an OrderedDict of attirbutes with the keys normalized by _normalize_name and the values normalized by _normalize_value. The value of :null: is passed to _normalize_value. However, if :null: is None, any values that are None are left out of the returned dict. An OrderedDict is returned so that the attribu...