code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def is_unary_operator(oper): """returns True, if operator is unary operator, otherwise False""" # definition: # member in class # ret-type operator symbol() # ret-type operator [++ --](int) # globally # ret-type operator symbol( arg ) # ret-type operator [++ --](X&, int) symbols = ['...
returns True, if operator is unary operator, otherwise False
def Power(base: vertex_constructor_param_types, exponent: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex: """ Raises a vertex to the power of another :param base: the base vertex :param exponent: the exponent vertex """ return Double(context.jvm_view().PowerVertex, lab...
Raises a vertex to the power of another :param base: the base vertex :param exponent: the exponent vertex
def word(self, value): """Property of the DigitWord returning (or setting) the DigitWord as a list of integers (or string representations) of DigitModel. The property is called during instantiation as the property validates the value passed and ensures that all digits are valid. The values can ...
Property of the DigitWord returning (or setting) the DigitWord as a list of integers (or string representations) of DigitModel. The property is called during instantiation as the property validates the value passed and ensures that all digits are valid. The values can be passed as ANY iterable
def set(self, id, value): """ 根据 id 写入数据。 :param id: 要写入的 id :param value: 要写入的数据,可以是一个 ``dict`` 对象 """ id = self.key_name(id) self.redis.set(id, json_dumps(value))
根据 id 写入数据。 :param id: 要写入的 id :param value: 要写入的数据,可以是一个 ``dict`` 对象
def _make_stream_handler_nodes(self, dsk_graph, array, iteration_order, masked): """ Produce task graph entries for an array that comes from a biggus StreamsHandler. This is essentially every type of array that isn't already a thing on disk/in-...
Produce task graph entries for an array that comes from a biggus StreamsHandler. This is essentially every type of array that isn't already a thing on disk/in-memory. StreamsHandler arrays include all aggregations and elementwise operations.
def upload(self, local_fn: str, remote_fn: str = '', dont_overwrite: bool = False): """Uploads given file to the task. If remote_fn is not specified, dumps it into task current directory with the same name. Args: local_fn: location of file locally remote_fn: location of file on tas...
Uploads given file to the task. If remote_fn is not specified, dumps it into task current directory with the same name. Args: local_fn: location of file locally remote_fn: location of file on task dont_overwrite: if True, will be no-op if target file exists
def context_teardown(func: Callable): """ Wrap an async generator function to execute the rest of the function at context teardown. This function returns an async function, which, when called, starts the wrapped async generator. The wrapped async function is run until the first ``yield`` statement ...
Wrap an async generator function to execute the rest of the function at context teardown. This function returns an async function, which, when called, starts the wrapped async generator. The wrapped async function is run until the first ``yield`` statement (``await async_generator.yield_()`` on Python 3.5)...
async def say(self, body, user, options): """ say something to user :param body: :param user: :return: """ return await self.send_text_message_to_all_interfaces( recipient=user, text=body, options=options)
say something to user :param body: :param user: :return:
def write_observation_zone(self, num, **kw): """ Write observation zone information for a taskpoint:: writer.write_task_options( start_time=time(12, 34, 56), task_time=timedelta(hours=1, minutes=45, seconds=12), waypoint_distance=False, ...
Write observation zone information for a taskpoint:: writer.write_task_options( start_time=time(12, 34, 56), task_time=timedelta(hours=1, minutes=45, seconds=12), waypoint_distance=False, distance_tolerance=(0.7, 'km'), altitud...
async def update_champs(self): """A method which updates ``self.rune_links``. This is useful because runeforge.gg is frequently updating. Raises ------ RuneConnectionError If the request does not return with a status of 200. """ html = await self._get...
A method which updates ``self.rune_links``. This is useful because runeforge.gg is frequently updating. Raises ------ RuneConnectionError If the request does not return with a status of 200.
def _handle_response(self, response): """ Handles the response received from Scrapyd. """ if not response.ok: raise ScrapydResponseError( "Scrapyd returned a {0} error: {1}".format( response.status_code, response.text)) ...
Handles the response received from Scrapyd.
def add_organism(self, common_name, directory, blatdb=None, genus=None, species=None, public=False): """ Add an organism :type common_name: str :param common_name: Organism common name :type directory: str :param directory: Server-side directory ...
Add an organism :type common_name: str :param common_name: Organism common name :type directory: str :param directory: Server-side directory :type blatdb: str :param blatdb: Server-side Blat directory for the organism :type genus: str :param genus: Gen...
def get_best_fit_parameters_translated_grouped(self): """Returns the parameters as a dictionary of the 'real units' for the best fit.""" result_dict = dict() result_dict['ocv'] = [parameters['ocv'] for parameters in self.best_fit_parameters_translated] resul...
Returns the parameters as a dictionary of the 'real units' for the best fit.
def _send_command(self, cmd=""): """ Handle reading/writing channel directly. It is also sanitizing the output received. Parameters ---------- cmd : str, optional The command to send to the remote device (default : "", just send a new line) Returns -...
Handle reading/writing channel directly. It is also sanitizing the output received. Parameters ---------- cmd : str, optional The command to send to the remote device (default : "", just send a new line) Returns ------- output : str The output fr...
def find_matches(self, content, file_to_handle): """Find all matches of an expression in a file """ # look for all match groups in the content groups = [match.groupdict() for match in self.match_expression.finditer(content)] # filter out content not in the match...
Find all matches of an expression in a file
def backfill_fields(self, fields, forms): """ Properly backfill fields to explicitly request specific keys. The issue is that >6.X servers *only* return requested fields so to improve backwards compatiblity for PyCap clients, add specific fields when required. Parameters...
Properly backfill fields to explicitly request specific keys. The issue is that >6.X servers *only* return requested fields so to improve backwards compatiblity for PyCap clients, add specific fields when required. Parameters ---------- fields: list requested...
def replace_seqres(self, pdb, update_atoms = True): """Replace SEQRES lines with a new sequence, optionally removing mutated sidechains""" newpdb = PDB() inserted_seqres = False entries_before_seqres = set(["HEADER", "OBSLTE", "TITLE", "CAVEAT", "COMPND", "SOURCE", ...
Replace SEQRES lines with a new sequence, optionally removing mutated sidechains
def loguniform(low, high, random_state): ''' low: an float that represent an lower bound high: an float that represent an upper bound random_state: an object of numpy.random.RandomState ''' assert low > 0, 'Lower bound must be positive' return np.exp(uniform(np.log(low), np.log(high), random...
low: an float that represent an lower bound high: an float that represent an upper bound random_state: an object of numpy.random.RandomState
def read(self, filename): """Reads the file specified by filename This method will load the eapi.conf file specified by filename into the instance object. It will also add the default connection localhost if it was not defined in the eapi.conf file Args: filename (...
Reads the file specified by filename This method will load the eapi.conf file specified by filename into the instance object. It will also add the default connection localhost if it was not defined in the eapi.conf file Args: filename (str): The full path to the file to lo...
def get_output(self): """ Retrieve the stored data in full. This call may block if the reading thread has not yet terminated. """ self._closing = True if not self.has_finished(): if self._debug: # Main thread overtook stream reading thread. ...
Retrieve the stored data in full. This call may block if the reading thread has not yet terminated.
def periodic_service_rpcs(self): """Check if any RPC has expired and remove it from the in flight list. This function should be called periodically to expire any RPCs that never complete. """ to_remove = [] now = monotonic() for rpc_tag, rpc in self.in_flight_rpcs.item...
Check if any RPC has expired and remove it from the in flight list. This function should be called periodically to expire any RPCs that never complete.
def setup_menu(self): """Setup context menu""" self.copy_action = create_action(self, _('Copy'), shortcut=keybinding('Copy'), icon=ima.icon('editcopy'), triggered=self.copy, ...
Setup context menu
def transmit(self, payload, **kwargs): """ Send a completion status call to Degreed using the client. Args: payload: The learner completion data payload to send to Degreed """ kwargs['app_label'] = 'degreed' kwargs['model_name'] = 'DegreedLearnerDataTransmiss...
Send a completion status call to Degreed using the client. Args: payload: The learner completion data payload to send to Degreed
def write_tabular(obj, filepath): """Write tabular object in HDF5 or pickle format Args: obj (array or DataFrame): tabular object to write filepath (path-like): path to write to; must end in '.h5' or '.pkl' """ _, fn, ext = splitext2(filepath) if ext == '.h5': _write_tabular...
Write tabular object in HDF5 or pickle format Args: obj (array or DataFrame): tabular object to write filepath (path-like): path to write to; must end in '.h5' or '.pkl'
def include(prop): '''Replicate property that is normally not replicated. Right now it's meaningful for one-to-many relations only.''' if isinstance(prop, QueryableAttribute): prop = prop.property assert isinstance(prop, (Column, ColumnProperty, RelationshipProperty)) #assert isinstance(prop...
Replicate property that is normally not replicated. Right now it's meaningful for one-to-many relations only.
def do(self): """Executes the request represented by this object. The requests library will be used for this purpose. Returns an instance of requests.Response. """ data = None if self.body is not None and self.body != b'': data = self.body return requests.requ...
Executes the request represented by this object. The requests library will be used for this purpose. Returns an instance of requests.Response.
def deserialize(cls, target_class, array): """ :type target_class: core.Installation|type :type array: list :rtype: core.Installation """ installation = target_class.__new__(target_class) server_public_key_wrapped = array[cls._INDEX_SERVER_PUBLIC_KEY] in...
:type target_class: core.Installation|type :type array: list :rtype: core.Installation
def train_epoch(self, epoch_info: EpochInfo, interactive=True): """ Train model on an epoch of a fixed number of batch updates """ epoch_info.on_epoch_begin() if interactive: iterator = tqdm.trange(epoch_info.batches_per_epoch, file=sys.stdout, desc="Training", unit="batch") ...
Train model on an epoch of a fixed number of batch updates
def clean_path_middleware(environ, start_response=None): '''Clean url from double slashes and redirect if needed.''' path = environ['PATH_INFO'] if path and '//' in path: url = re.sub("/+", '/', path) if not url.startswith('/'): url = '/%s' % url qs = environ['QUERY_STRIN...
Clean url from double slashes and redirect if needed.
def crl(self): """ Returns up to date CRL of this CA """ revoked_certs = self.get_revoked_certs() crl = crypto.CRL() now_str = timezone.now().strftime(generalized_time) for cert in revoked_certs: revoked = crypto.Revoked() revoked.set_seria...
Returns up to date CRL of this CA
def resolve_page(self, request, context, is_staff): """Return the appropriate page according to the path.""" path = context['path'] lang = context['lang'] page = Page.objects.from_path( path, lang, exclude_drafts=(not is_staff)) if page: return...
Return the appropriate page according to the path.
def start_engines(opts, proc_mgr, proxy=None): ''' Fire up the configured engines! ''' utils = salt.loader.utils(opts, proxy=proxy) if opts['__role'] == 'master': runners = salt.loader.runner(opts, utils=utils) else: runners = [] funcs = salt.loader.minion_mods(opts, utils=ut...
Fire up the configured engines!
def list_gebouwen_by_huisnummer(self, huisnummer): ''' List all `gebouwen` for a :class:`Huisnummer`. :param huisnummer: The :class:`Huisnummer` for which the \ `gebouwen` are wanted. :rtype: A :class:`list` of :class:`Gebouw` ''' try: id = huisnu...
List all `gebouwen` for a :class:`Huisnummer`. :param huisnummer: The :class:`Huisnummer` for which the \ `gebouwen` are wanted. :rtype: A :class:`list` of :class:`Gebouw`
def cmd(binary, subcommand, *args, **kwargs): """ Construct a command line for a "modern UNIX" command. Modern UNIX command do a closely-related-set-of-things and do it well. Examples include :code:`apt-get` or :code:`git`. :param binary: the name of the command :param subcommand: the subcomma...
Construct a command line for a "modern UNIX" command. Modern UNIX command do a closely-related-set-of-things and do it well. Examples include :code:`apt-get` or :code:`git`. :param binary: the name of the command :param subcommand: the subcommand used :param args: positional arguments (put last) ...
def mouse_click(self, widget, event=None): """Triggered when mouse click is pressed in the history tree. The method shows all scoped data for an execution step as tooltip or fold and unfold the tree by double-click and select respective state for double clicked element. """ if ev...
Triggered when mouse click is pressed in the history tree. The method shows all scoped data for an execution step as tooltip or fold and unfold the tree by double-click and select respective state for double clicked element.
def info( self, page: 'WikipediaPage' ) -> 'WikipediaPage': """ https://www.mediawiki.org/w/api.php?action=help&modules=query%2Binfo https://www.mediawiki.org/wiki/API:Info """ params = { 'action': 'query', 'prop': 'info', ...
https://www.mediawiki.org/w/api.php?action=help&modules=query%2Binfo https://www.mediawiki.org/wiki/API:Info
def hash_from_func(cls, func): """Return a hashlib-compatible object for the multihash `func`. If the `func` is registered but no hashlib-compatible constructor is available for it, `None` is returned. If the `func` is not registered, a `KeyError` is raised. >>> h = FuncReg.ha...
Return a hashlib-compatible object for the multihash `func`. If the `func` is registered but no hashlib-compatible constructor is available for it, `None` is returned. If the `func` is not registered, a `KeyError` is raised. >>> h = FuncReg.hash_from_func(Func.sha2_256) >>> h....
def data(self, value): """The data property. Args: value (object). the property value. """ if value == self._defaults['data'] and 'data' in self._values: del self._values['data'] else: self._values['data'] = value
The data property. Args: value (object). the property value.
def _ConvertFloat(value): """Convert an floating point number.""" if value == 'nan': raise ParseError('Couldn\'t parse float "nan", use "NaN" instead.') try: # Assume Python compatible syntax. return float(value) except ValueError: # Check alternative spellings. if value == _NEG_INFINITY: ...
Convert an floating point number.
def _unique_constrains(cls): """Get all (single column and multi column) unique constraints""" unique = [{c.name for c in u.columns} for u in cls.__table_args__ if isinstance(u, UniqueConstraint)] unique.extend({c.name} for c in cls.__table__.columns if c.unique) return...
Get all (single column and multi column) unique constraints
def Subclasses(cls, sort_by=None, reverse=False): """Get all nested Constant class and it's name pair. :param sort_by: the attribute name used for sorting. :param reverse: if True, return in descend order. :returns: [(attr, value),...] pairs. :: >>> class MyClass(Const...
Get all nested Constant class and it's name pair. :param sort_by: the attribute name used for sorting. :param reverse: if True, return in descend order. :returns: [(attr, value),...] pairs. :: >>> class MyClass(Constant): ... a = 1 # non-class attributre .....
def parse_uri(config_uri): """ Parse the ``config_uri`` into a :class:`plaster.PlasterURL` object. ``config_uri`` can be a relative or absolute file path such as ``development.ini`` or ``/path/to/development.ini``. The file must have an extension that can be handled by a :class:`plaster.ILoader` ...
Parse the ``config_uri`` into a :class:`plaster.PlasterURL` object. ``config_uri`` can be a relative or absolute file path such as ``development.ini`` or ``/path/to/development.ini``. The file must have an extension that can be handled by a :class:`plaster.ILoader` registered with the system. Alte...
def set_plain_text(self, text, is_code): """Set plain text docs""" # text is coming from utils.dochelpers.getdoc if type(text) is dict: name = text['name'] if name: rst_title = ''.join(['='*len(name), '\n', name, '\n', ...
Set plain text docs
def organisation_logo_path(feature, parent): """Retrieve the full path of used specified organisation logo.""" _ = feature, parent # NOQA organisation_logo_file = setting( inasafe_organisation_logo_path['setting_key']) if os.path.exists(organisation_logo_file): return organisation_logo_...
Retrieve the full path of used specified organisation logo.
def warp(self, order): """对order/market的封装 [description] Arguments: order {[type]} -- [description] Returns: [type] -- [description] """ # 因为成交模式对时间的封装 if order.order_model == ORDER_MODEL.MARKET: if order.frequence is FREQ...
对order/market的封装 [description] Arguments: order {[type]} -- [description] Returns: [type] -- [description]
def disveclayers(self, x, y, layers, aq=None): '''Returns two arrays of size len(layers) only used in building equations''' if aq is None: aq = self.model.aq.find_aquifer_data(x, y) qxqy = self.disvec(x, y, aq) rv = np.sum(qxqy[:,np.newaxis,:] * aq.eigvec, 2) return rv[:,...
Returns two arrays of size len(layers) only used in building equations
def option_present(name, value, reload=False): ''' Ensure the state of a particular option/setting in csf. name The option name in csf.conf value The value it should be set to. reload Boolean. If set to true, csf will be reloaded after. ''' ret = {'name': 'testing ...
Ensure the state of a particular option/setting in csf. name The option name in csf.conf value The value it should be set to. reload Boolean. If set to true, csf will be reloaded after.
def reader(ltsvfile, labels=None): """Make LTSV Reader for reading selected labels. :param ltsvfile: iterable of lines. :param labels: sequence of labels. (optional) :return: generator of record in [[label, value], ...] form. """ label_pattern = re.compile(r"^[0-9A-Za-z_.-]+:") if labels...
Make LTSV Reader for reading selected labels. :param ltsvfile: iterable of lines. :param labels: sequence of labels. (optional) :return: generator of record in [[label, value], ...] form.
def append(self, value): """Appends an item to the list. Similar to list.append().""" self._values.append(self._type_checker.CheckValue(value)) if not self._message_listener.dirty: self._message_listener.Modified()
Appends an item to the list. Similar to list.append().
def get_cpds(self, node=None, time_slice=0): """ Returns the CPDs that have been associated with the network. Parameters ---------- node: tuple (node_name, time_slice) The node should be in the following form (node_name, time_slice). Here, node_name is th...
Returns the CPDs that have been associated with the network. Parameters ---------- node: tuple (node_name, time_slice) The node should be in the following form (node_name, time_slice). Here, node_name is the node that is inserted while the time_slice is an in...
def snapshot_identifier(prefix, db_identifier): """Return an identifier for a snapshot of a database or cluster. """ now = datetime.now() return '%s-%s-%s' % (prefix, db_identifier, now.strftime('%Y-%m-%d-%H-%M'))
Return an identifier for a snapshot of a database or cluster.
def refresh_access_information(self, refresh_token): """Return updated access information for an OAuth2 authorization grant. :param refresh_token: the refresh token used to obtain the updated information :returns: A dictionary with the key/value pairs for access_token, r...
Return updated access information for an OAuth2 authorization grant. :param refresh_token: the refresh token used to obtain the updated information :returns: A dictionary with the key/value pairs for access_token, refresh_token and scope. The refresh_token value will be done whe...
def move(self, u_function): """ Move a mesh by using an external function which prescribes the displacement at any point in space. Useful for manipulating ``dolfin`` meshes. """ if self.mesh: self.u = u_function delta = [u_function(p) for p in self...
Move a mesh by using an external function which prescribes the displacement at any point in space. Useful for manipulating ``dolfin`` meshes.
def output(self, message, color=None): """ A helper to used like print() or click's secho() tunneling all the outputs to sys.stdout or sys.stderr :param message: (str) :param color: (str) check click.secho() documentation :return: (None) prints to sys.stdout or sys.stderr...
A helper to used like print() or click's secho() tunneling all the outputs to sys.stdout or sys.stderr :param message: (str) :param color: (str) check click.secho() documentation :return: (None) prints to sys.stdout or sys.stderr
def copy_and_move_messages(from_channel, to_channel): """ While splitting channel and moving chosen subscribers to new channel, old channel's messages are copied and moved to new channel. Args: from_channel (Channel object): move messages from channel to_chann...
While splitting channel and moving chosen subscribers to new channel, old channel's messages are copied and moved to new channel. Args: from_channel (Channel object): move messages from channel to_channel (Channel object): move messages to channel
def get_domain_template(distro, libvirt_ver, **kwargs): """ Get a rendered Jinja2 domain template Args: distro(str): domain distro libvirt_ver(int): libvirt version kwargs(dict): args for template render Returns: str: rendered template """ env = Environment( ...
Get a rendered Jinja2 domain template Args: distro(str): domain distro libvirt_ver(int): libvirt version kwargs(dict): args for template render Returns: str: rendered template
def _from_dict(cls, _dict): """Initialize a Word object from a json dictionary.""" args = {} if 'word' in _dict: args['word'] = _dict.get('word') else: raise ValueError( 'Required property \'word\' not present in Word JSON') if 'sounds_like...
Initialize a Word object from a json dictionary.
def merge_trd_mkt_stock_str(trd_mkt, partial_stock_str): """ Merge the string of stocks :param market: market code :param partial_stock_str: original stock code string. i.e. "AAPL","00700", "000001" :return: unified representation of a stock code. i.e. "US.AAPL", "HK.00700", "SZ.000001" """ ...
Merge the string of stocks :param market: market code :param partial_stock_str: original stock code string. i.e. "AAPL","00700", "000001" :return: unified representation of a stock code. i.e. "US.AAPL", "HK.00700", "SZ.000001"
def gen_radio_list(sig_dic): ''' For generating List view HTML file for RADIO. for each item. ''' view_zuoxiang = '''<span class="iga_pd_val">''' dic_tmp = sig_dic['dic'] for key in dic_tmp.keys(): tmp_str = '''{{% if postinfo.extinfo['{0}'][0] == "{1}" %}} {2} {{% end %}} '...
For generating List view HTML file for RADIO. for each item.
def fileUpd(self, buffer=None, filename=None, ufilename=None, desc=None): """Update annotation attached file.""" CheckParent(self) return _fitz.Annot_fileUpd(self, buffer, filename, ufilename, desc)
Update annotation attached file.
def __add_images_to_manifest(self): """Add entries for py3o images into the manifest file.""" xpath_expr = "//manifest:manifest[1]" for content_tree in self.content_trees: # Find manifest:manifest tags. manifest_e = content_tree.xpath( xpath_expr, ...
Add entries for py3o images into the manifest file.
def line_to(self, x, y): """Adds a line to the path from the current point to position ``(x, y)`` in user-space coordinates. After this call the current point will be ``(x, y)``. If there is no current point before the call to :meth:`line_to` this method will behave as ``context...
Adds a line to the path from the current point to position ``(x, y)`` in user-space coordinates. After this call the current point will be ``(x, y)``. If there is no current point before the call to :meth:`line_to` this method will behave as ``context.move_to(x, y)``. :param x:...
def convert_tensor_float_to_float16(tensor): ''' Convert tensor float to float16. :param tensor: TensorProto object :return tensor_float16: converted TensorProto object Example: :: from onnxmltools.utils.float16_converter import convert_tensor_float_to_float16 new_tensor = co...
Convert tensor float to float16. :param tensor: TensorProto object :return tensor_float16: converted TensorProto object Example: :: from onnxmltools.utils.float16_converter import convert_tensor_float_to_float16 new_tensor = convert_tensor_float_to_float16(tensor)
def delete_files_within_dir(directory: str, filenames: List[str]) -> None: """ Delete files within ``directory`` whose filename *exactly* matches one of ``filenames``. """ for dirpath, dirnames, fnames in os.walk(directory): for f in fnames: if f in filenames: ful...
Delete files within ``directory`` whose filename *exactly* matches one of ``filenames``.
def process_rewards(self, rewards): """Clips, rounds, and changes to integer type. Args: rewards: numpy array of raw (float) rewards. Returns: processed_rewards: numpy array of np.int64 """ min_reward, max_reward = self.reward_range # Clips at min and max reward. rewards = np...
Clips, rounds, and changes to integer type. Args: rewards: numpy array of raw (float) rewards. Returns: processed_rewards: numpy array of np.int64
def stix_embedding_pred(self, parent, child, ns_mapping): """ Predicate for recognizing inlined content in an XML; to be used for DINGO's xml-import hook 'embedded_predicate'. The question this predicate must answer is whether the child should be extracted into a separate object....
Predicate for recognizing inlined content in an XML; to be used for DINGO's xml-import hook 'embedded_predicate'. The question this predicate must answer is whether the child should be extracted into a separate object. The function returns either - False (the child is not to be ...
def summary(self, title, sentences=0, chars=0, auto_suggest=True, redirect=True): """ Get the summary for the title in question Args: title (str): Page title to summarize sentences (int): Number of sentences to return in summary chars (int): Number of...
Get the summary for the title in question Args: title (str): Page title to summarize sentences (int): Number of sentences to return in summary chars (int): Number of characters to return in summary auto_suggest (bool): Run auto-suggest on titl...
def plot_cpu_mem_keypoints(self): """绘制CPU/Mem/特征点数量.""" plt.figure(1) # 开始绘制子图: plt.subplot(311) title = self._get_graph_title() plt.title(title, loc="center") # 设置绘图的标题 mem_ins = plt.plot(self.time_axis, self.mem_axis, "-", label="Mem(MB)", color='deepskyblue',...
绘制CPU/Mem/特征点数量.
def best_periods(self): """Compute the scores under the various models Parameters ---------- periods : array_like array of periods at which to compute scores Returns ------- best_periods : dict Dictionary of best periods. Dictionary keys ...
Compute the scores under the various models Parameters ---------- periods : array_like array of periods at which to compute scores Returns ------- best_periods : dict Dictionary of best periods. Dictionary keys are the unique filter n...
def hash(value, algorithm='sha512'): ''' .. versionadded:: 2014.7.0 Encodes a value with the specified encoder. value The value to be hashed. algorithm : sha512 The algorithm to use. May be any valid algorithm supported by hashlib. CLI Example: .. code-block:: ba...
.. versionadded:: 2014.7.0 Encodes a value with the specified encoder. value The value to be hashed. algorithm : sha512 The algorithm to use. May be any valid algorithm supported by hashlib. CLI Example: .. code-block:: bash salt '*' random.hash 'I am a string' ...
def semcor_to_offset(sensekey): """ Converts SemCor sensekey IDs to synset offset. >>> print semcor_to_offset('live%2:42:06::') 02614387-v """ synset = wn.lemma_from_key(sensekey).synset offset = '%08d-%s' % (synset.offset, synset.pos) return offset
Converts SemCor sensekey IDs to synset offset. >>> print semcor_to_offset('live%2:42:06::') 02614387-v
def status_human(self): """ Human readable status :return: * `DOWNLOADING`: the task is downloading files * `BEING TRANSFERRED`: the task is being transferred * `TRANSFERRED`: the task has been transferred to downloads \ directory ...
Human readable status :return: * `DOWNLOADING`: the task is downloading files * `BEING TRANSFERRED`: the task is being transferred * `TRANSFERRED`: the task has been transferred to downloads \ directory * `SEARCHING RESOURCES`: the task is se...
def show_fields(self, block=None): """Retrieve and return the mapping for the given metadata block. Arguments: block (str): The top-level field to fetch the mapping for (for example, ``"mdf"``), or the special values ``None`` for everything or ``"top"`` for just the ...
Retrieve and return the mapping for the given metadata block. Arguments: block (str): The top-level field to fetch the mapping for (for example, ``"mdf"``), or the special values ``None`` for everything or ``"top"`` for just the top-level fields. ...
def dataoneTypes(request): """Return the PyXB binding to use when handling a request.""" if is_v1_api(request): return d1_common.types.dataoneTypes_v1_1 elif is_v2_api(request) or is_diag_api(request): return d1_common.types.dataoneTypes_v2_0 else: raise d1_common.types.exception...
Return the PyXB binding to use when handling a request.
def tzname(self, dt): """ http://docs.python.org/library/datetime.html#datetime.tzinfo.tzname """ if self.__is_daylight_time(dt): return time.tzname[1] else: return time.tzname[0]
http://docs.python.org/library/datetime.html#datetime.tzinfo.tzname
def xlim(min, max): """ This function will set the x axis range for all time series plots Parameters: min : flt The time to start all time series plots. Can be given in seconds since epoch, or as a string in the format "YYYY-MM-DD HH:MM:SS" max : flt ...
This function will set the x axis range for all time series plots Parameters: min : flt The time to start all time series plots. Can be given in seconds since epoch, or as a string in the format "YYYY-MM-DD HH:MM:SS" max : flt The time to end all time series...
def memoize_single_arg(f): """ Decorator memoizing a single-argument function """ memo = {} @wraps(f) def memoized_f(arg): try: return memo[arg] except KeyError: result = memo[arg] = f(arg) return result return memoized_f
Decorator memoizing a single-argument function
def route(self, uri, *args, **kwargs): """Create a plugin route from a decorated function. :param uri: endpoint at which the route will be accessible. :type uri: str :param args: captures all of the positional arguments passed in :type args: tuple(Any) :param kwargs: capt...
Create a plugin route from a decorated function. :param uri: endpoint at which the route will be accessible. :type uri: str :param args: captures all of the positional arguments passed in :type args: tuple(Any) :param kwargs: captures the keyword arguments passed in :type...
def variantcall_sample(data, region=None, align_bams=None, out_file=None): """Parallel entry point for doing genotyping of a region of a sample. """ if out_file is None or not os.path.exists(out_file) or not os.path.lexists(out_file): utils.safe_makedir(os.path.dirname(out_file)) ref_file = ...
Parallel entry point for doing genotyping of a region of a sample.
def expanduser(self, filepath, ssh=False): """Replaces the user root ~ with the full path on the file system. Works for local disks and remote servers. For remote servers, set ssh=True.""" if ssh: self._check_ssh() stdin, stdout, stderr = self.ssh.exec_command("cd...
Replaces the user root ~ with the full path on the file system. Works for local disks and remote servers. For remote servers, set ssh=True.
def GetValues(self, table_names, column_names, condition): """Retrieves values from a table. Args: table_names (list[str]): table names. column_names (list[str]): column names. condition (str): query condition such as "log_source == 'Application Error'". Yields: sqlite3.r...
Retrieves values from a table. Args: table_names (list[str]): table names. column_names (list[str]): column names. condition (str): query condition such as "log_source == 'Application Error'". Yields: sqlite3.row: row. Raises: RuntimeError: if the database is not o...
def top_level(self): """ Print just the top level of an object, being sure to show where it goes deeper """ output = {} if isinstance(self.obj, dict): for name, item in self.obj.items(): if isinstance(item, dict): if item: ...
Print just the top level of an object, being sure to show where it goes deeper
def _initialize_policy(self): """Initialize the policy. Run the policy network on dummy data to initialize its parameters for later reuse and to analyze the policy distribution. Initializes the attributes `self._network` and `self._policy_type`. Raises: ValueError: Invalid policy distributio...
Initialize the policy. Run the policy network on dummy data to initialize its parameters for later reuse and to analyze the policy distribution. Initializes the attributes `self._network` and `self._policy_type`. Raises: ValueError: Invalid policy distribution. Returns: Parameters of ...
def __get_blob_dimensions(self, chunk_dim): """ Sets the blob dimmentions, trying to read around 1024 MiB at a time. This is assuming a chunk is about 1 MiB. """ #Taking the size into consideration, but avoiding having multiple blobs within a single time bin. if self.selecti...
Sets the blob dimmentions, trying to read around 1024 MiB at a time. This is assuming a chunk is about 1 MiB.
async def wait_until_serving(self) -> None: """ Await until the ``Endpoint`` is ready to receive events. """ await asyncio.gather( self._receiving_loop_running.wait(), self._internal_loop_running.wait(), loop=self.event_loop )
Await until the ``Endpoint`` is ready to receive events.
def is_valid(self): """Validates the username and password in the form.""" form = super(AuthenticateForm, self).is_valid() for f, error in self.errors.items(): if f != "__all__": self.fields[f].widget.attrs.update({"class": "error", "placeholder": ", ".join(list(error...
Validates the username and password in the form.
def delete(method, hmc, uri, uri_parms, logon_required): """Operation: Delete <resource>.""" try: resource = hmc.lookup_by_uri(uri) except KeyError: raise InvalidResourceError(method, uri) resource.manager.remove(resource.oid)
Operation: Delete <resource>.
def cmd_link_list(self): '''list links''' print("%u links" % len(self.mpstate.mav_master)) for i in range(len(self.mpstate.mav_master)): conn = self.mpstate.mav_master[i] print("%u: %s" % (i, conn.address))
list links
def plot(self, value=None, pixel=None): """ Plot the ROI """ # DEPRECATED import ugali.utils.plotting map_roi = np.array(hp.UNSEEN \ * np.ones(hp.nside2npix(self.config.params['coords']['nside_pixel']))) if value is None: ...
Plot the ROI
def staff_member(view_func): """Performs user authentication check. Similar to Django's `login_required` decorator, except that this throws :exc:`~leonardo.exceptions.NotAuthenticated` exception if the user is not signed-in. """ @functools.wraps(view_func, assigned=available_attrs(view_func)) ...
Performs user authentication check. Similar to Django's `login_required` decorator, except that this throws :exc:`~leonardo.exceptions.NotAuthenticated` exception if the user is not signed-in.
def _get_available_choices(self, queryset, value): """ get possible choices for selection """ item = queryset.filter(pk=value).first() if item: try: pk = getattr(item, self.chained_model_field + "_id") filter = {self.chained_model_field...
get possible choices for selection
def update_abbreviations(apps, schema_editor): """ Migrate to new FR committee abbreviations """ # Get model managers Group = apps.get_model("representatives", "Group") # Abbreviation mapping amap = { u'SenComCult': u'Culture', u'SenComEco': u'Économie', u'SenComDef...
Migrate to new FR committee abbreviations
def to_end_tag(self, tag_func): """ Creates a tag that parses until it finds the corresponding end tag, eg: for a tag named ``mytag`` it will parse until ``endmytag``. The decorated func's return value is used to render the parsed content and takes three arguments - the p...
Creates a tag that parses until it finds the corresponding end tag, eg: for a tag named ``mytag`` it will parse until ``endmytag``. The decorated func's return value is used to render the parsed content and takes three arguments - the parsed content between the start and end tags, the te...
def QueryHowDoI(Query, num_answers, full_text, window:sg.Window): ''' Kicks off a subprocess to send the 'Query' to HowDoI Prints the result, which in this program will route to a gooeyGUI window :param Query: text english question to ask the HowDoI web engine :return: nothing ''' howdoi_com...
Kicks off a subprocess to send the 'Query' to HowDoI Prints the result, which in this program will route to a gooeyGUI window :param Query: text english question to ask the HowDoI web engine :return: nothing
def main(): """ main """ arguments = IArguments(__doc__) content = open(arguments.filepath).read() open(arguments.filepath + ".bak", "w").write(content) try: newcontent = transliterate(content) write_newcontent(arguments.filepath, newcontent) except UnicodeEncodeError as ...
main
def _rename_full_name(self, full_name, other_trajectory, used_runs=None, new_run_idx=None): """Renames a full name based on the wildcards and a particular run""" split_name = full_name.split('.') for idx, name in enumerate(split_name): if name in other_trajectory._reversed_wildcards:...
Renames a full name based on the wildcards and a particular run
def get_dialog(self): """Return FormDialog instance""" dialog = self.parent() while not isinstance(dialog, QDialog): dialog = dialog.parent() return dialog
Return FormDialog instance
def layout_circle(self): '''Position vertices evenly around a circle.''' n = self.num_vertices() t = np.linspace(0, 2*np.pi, n+1)[:n] return np.column_stack((np.cos(t), np.sin(t)))
Position vertices evenly around a circle.
def validate(raw_schema, target=None, **kwargs): """ Given the python representation of a JSONschema as defined in the swagger spec, validate that the schema complies to spec. If `target` is provided, that target will be validated against the provided schema. """ schema = schema_validator(raw_s...
Given the python representation of a JSONschema as defined in the swagger spec, validate that the schema complies to spec. If `target` is provided, that target will be validated against the provided schema.
async def sendPhoto(self, chat_id, photo, caption=None, parse_mode=None, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ See: https://core.telegram.org/bot...
See: https://core.telegram.org/bots/api#sendphoto :param photo: - string: ``file_id`` for a photo existing on Telegram servers - string: HTTP URL of a photo from the Internet - file-like object: obtained by ``open(path, 'rb')`` - tuple: (filename, file-like objec...