code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _deleteRangeFromKNN(self, start=0, end=None): """ This method will remove any stored records within the range from start to end. Noninclusive of end. parameters ------------ start - integer representing the ROWID of the start of the deletion range, end - integer representing the ROWID o...
This method will remove any stored records within the range from start to end. Noninclusive of end. parameters ------------ start - integer representing the ROWID of the start of the deletion range, end - integer representing the ROWID of the end of the deletion range, if None, it will defaul...
def from_files(path_dir, dos_spin=1): """ get a BoltztrapAnalyzer object from a set of files Args: path_dir: directory where the boltztrap files are dos_spin: in DOS mode, set to 1 for spin up and -1 for spin down Returns: a BoltztrapAnalyzer object ...
get a BoltztrapAnalyzer object from a set of files Args: path_dir: directory where the boltztrap files are dos_spin: in DOS mode, set to 1 for spin up and -1 for spin down Returns: a BoltztrapAnalyzer object
def context_setting(self): """ API trading and quote context setting :returns: trade context, quote context """ if self.unlock_password == "": raise Exception("请先配置交易解锁密码! password: {}".format( self.unlock_password)) quote_ctx = ft.OpenQuoteCo...
API trading and quote context setting :returns: trade context, quote context
def show_inline_matplotlib_plots(): """Show matplotlib plots immediately if using the inline backend. With ipywidgets 6.0, matplotlib plots don't work well with interact when using the inline backend that comes with ipykernel. Basically, the inline backend only shows the plot after the entire cell exec...
Show matplotlib plots immediately if using the inline backend. With ipywidgets 6.0, matplotlib plots don't work well with interact when using the inline backend that comes with ipykernel. Basically, the inline backend only shows the plot after the entire cell executes, which does not play well with dra...
def get_strain(cryst, refcell=None): '''Calculate strain tensor in the Voight notation Computes the strain tensor in the Voight notation as a conventional 6-vector. The calculation is done with respect to the crystal geometry passed in refcell parameter. :param cryst: deformed structure :param...
Calculate strain tensor in the Voight notation Computes the strain tensor in the Voight notation as a conventional 6-vector. The calculation is done with respect to the crystal geometry passed in refcell parameter. :param cryst: deformed structure :param refcell: reference, undeformed structure ...
def set_position(cls, resource_id, to_position, db_session=None, *args, **kwargs): """ Sets node position for new node in the tree :param resource_id: resource to move :param to_position: new position :param db_session: :return:def count_children(cls, resource_id, db_ses...
Sets node position for new node in the tree :param resource_id: resource to move :param to_position: new position :param db_session: :return:def count_children(cls, resource_id, db_session=None):
def ContentFilesRelative(self): """ Returns a generator iterating over the each file in :attr:`ContentFiles` relative to :attr:`ProjectHome` directory. """ return (os.path.relpath(path, self.ProjectHome) for path in sorted(self.ContentFiles, key=self.lower))
Returns a generator iterating over the each file in :attr:`ContentFiles` relative to :attr:`ProjectHome` directory.
def translate(self, text): """ Translate text, returns the modified text. """ # Reset substitution counter self.count = 0 # Process text return self._make_regex().sub(self, text)
Translate text, returns the modified text.
def n1ql_index_build_deferred(self, other_buckets=False): """ Instruct the server to begin building any previously deferred index definitions. This method will gather a list of all pending indexes in the cluster (including those created using the `defer` option with :met...
Instruct the server to begin building any previously deferred index definitions. This method will gather a list of all pending indexes in the cluster (including those created using the `defer` option with :meth:`create_index`) and start building them in an efficient manner. :pa...
def _unpack_bin(self, packed): """ Internal. Decodes 16 bit RGB565 into python list [R,G,B] """ output = struct.unpack('H', packed) bits16 = output[0] r = (bits16 & 0xF800) >> 11 g = (bits16 & 0x7E0) >> 5 b = (bits16 & 0x1F) return [int(r << 3), i...
Internal. Decodes 16 bit RGB565 into python list [R,G,B]
def get_slug(self, language_code, lang_name): """ Notes: - slug must be unique! - slug is used to check if page already exists! :return: 'slug' string for cms.api.create_page() """ title = self.get_title(language_code, lang_name) assert title != ""...
Notes: - slug must be unique! - slug is used to check if page already exists! :return: 'slug' string for cms.api.create_page()
def get_normalized_terms(term_id: str) -> dict: """Get normalized terms - canonical/decanonical forms""" canonical = term_id decanonical = term_id canonical_namespace_targets = config["bel"]["lang"]["canonical"] decanonical_namespace_targets = config["bel"]["lang"]["decanonical"] results = get...
Get normalized terms - canonical/decanonical forms
def files_in_directory(db, user_id, db_dirname): """ Return files in a directory. """ fields = _file_default_fields() rows = db.execute( select( fields, ).where( _is_in_directory(files, user_id, db_dirname), ).order_by( files.c.user_id, ...
Return files in a directory.
def to_madeline(self): """ Return the individual info in a madeline formated string """ #Convert sex to madeleine type self.logger.debug("Returning madeline info") if self.sex == 1: madeline_gender = 'M' elif self.sex == 2: madeline_gender ...
Return the individual info in a madeline formated string
def tee(self, *args): ''' get/set the tee flag. The tee flag toggles any output that is directed to non-console destinations to also appear on the console. Tee'd console output is still verbosity filtered tee(): returns the current syslog flag ...
get/set the tee flag. The tee flag toggles any output that is directed to non-console destinations to also appear on the console. Tee'd console output is still verbosity filtered tee(): returns the current syslog flag tee(True|False): sets the fl...
def has_name_in(cls, names): """Build a filter if the author has any of the given names.""" return cls.sha512.in_({ cls.hash_name(name) for name in names })
Build a filter if the author has any of the given names.
def dump(obj, root_file, proto=0, key=None): """Dump an object into a ROOT TFile. `root_file` may be an open ROOT file or directory, or a string path to an existing ROOT file. """ if isinstance(root_file, string_types): root_file = root_open(root_file, 'recreate') own_file = True ...
Dump an object into a ROOT TFile. `root_file` may be an open ROOT file or directory, or a string path to an existing ROOT file.
def _str_to_ord(content, weights): """Converts a string to its lexicographical order. Args: content: the string to convert. Of type str. weights: weights from _get_weights. Returns: an int or long that represents the order of this string. "" has order 0. """ ordinal = 0 for i, c in enumerate(c...
Converts a string to its lexicographical order. Args: content: the string to convert. Of type str. weights: weights from _get_weights. Returns: an int or long that represents the order of this string. "" has order 0.
def GetMACBRepresentationFromDescriptions(self, timestamp_descriptions): """Determines the MACB representation from the timestamp descriptions. MACB representation is a shorthand for representing one or more of modification, access, change, birth timestamp descriptions as the letters "MACB" or a "." if...
Determines the MACB representation from the timestamp descriptions. MACB representation is a shorthand for representing one or more of modification, access, change, birth timestamp descriptions as the letters "MACB" or a "." if the corresponding timestamp is not set. Note that this is an output format...
def checkbox(message: Text, choices: List[Union[Text, Choice, Dict[Text, Any]]], default: Optional[Text] = None, qmark: Text = DEFAULT_QUESTION_PREFIX, style: Optional[Style] = None, **kwargs: Any) -> Question: """Ask the user to select from a list of...
Ask the user to select from a list of items. This is a multiselect, the user can choose one, none or many of the items. Args: message: Question text choices: Items shown in the selection, this can contain `Choice` or or `Separator` objects or simple items as strings. Pass...
def example3(): """ Example 3: Using TF dataset API to load and process image for training """ n_data = 100 imgs_file_list = ['tiger.jpeg'] * n_data train_targets = [np.ones(1)] * n_data def generator(): if len(imgs_file_list) != len(train_targets): raise RuntimeError('len(imgs_...
Example 3: Using TF dataset API to load and process image for training
def value(self): """Returns the current value of this slot. Returns: The value of the slot (a serializable Python type). Raises: SlotNotFilledError if the value hasn't been filled yet. """ if not self.filled: raise SlotNotFilledError('Slot with name "%s", key "%s" not yet filled....
Returns the current value of this slot. Returns: The value of the slot (a serializable Python type). Raises: SlotNotFilledError if the value hasn't been filled yet.
def retrieve_split_adjustment_data_for_sid(self, dates, sid, split_adjusted_asof_idx): """ dates : pd.DatetimeIndex The calendar dates. sid : i...
dates : pd.DatetimeIndex The calendar dates. sid : int The sid for which we want to retrieve adjustments. split_adjusted_asof_idx : int The index in `dates` as-of which the data is split adjusted. Returns ------- pre_adjustments : tuple(list(f...
def _clean_message(message): '''Internal helper to sanitize message output''' message = message.replace('zonecfg: ', '') message = message.splitlines() for line in message: if line.startswith('On line'): message.remove(line) return "\n".join(message)
Internal helper to sanitize message output
def timeseries(self): """ Load time series It returns the actual time series used in power flow analysis. If :attr:`_timeseries` is not :obj:`None`, it is returned. Otherwise, :meth:`timeseries()` looks for time series of the according sector in :class:`~.grid.network.Ti...
Load time series It returns the actual time series used in power flow analysis. If :attr:`_timeseries` is not :obj:`None`, it is returned. Otherwise, :meth:`timeseries()` looks for time series of the according sector in :class:`~.grid.network.TimeSeries` object. Returns ...
def __update_binding( self, dependency, service, reference, old_properties, new_value ): # type: (Any, Any, ServiceReference, dict, bool) -> None """ Calls back component binding and field binding methods when the properties of an injected dependency have been updated. ...
Calls back component binding and field binding methods when the properties of an injected dependency have been updated. :param dependency: The dependency handler :param service: The injected service :param reference: The reference of the injected service :param old_properties: P...
def use_plenary_objective_bank_view(self): """Pass through to provider ObjectiveObjectiveBankSession.use_plenary_objective_bank_view""" self._objective_bank_view = PLENARY # self._get_provider_session('objective_objective_bank_session') # To make sure the session is tracked for session i...
Pass through to provider ObjectiveObjectiveBankSession.use_plenary_objective_bank_view
def _get_triplets_reciprocal_mesh_at_q(fixed_grid_number, mesh, rotations, is_time_reversal=True, swappable=True): """Search symmetry reduced triplets fixing on...
Search symmetry reduced triplets fixing one q-point Triplets of (q0, q1, q2) are searched. Parameters ---------- fixed_grid_number : int Grid point of q0 mesh : array_like Mesh numbers dtype='intc' shape=(3,) rotations : array_like Rotation matrices in r...
async def get_or_create(cls, lang: str, *, client_token: str = None, mounts: Iterable[str] = None, envs: Mapping[str, str] = None, resources: Mapping[str, int] = None, cluster_size...
Get-or-creates a compute session. If *client_token* is ``None``, it creates a new compute session as long as the server has enough resources and your API key has remaining quota. If *client_token* is a valid string and there is an existing compute session with the same token and the same...
def fill_value(dtype): '''Get a fill-value for a given dtype Parameters ---------- dtype : type Returns ------- `np.nan` if `dtype` is real or complex 0 otherwise ''' if np.issubdtype(dtype, np.floating) or np.issubdtype(dtype, np.complexfloating): return dtype(np.nan)...
Get a fill-value for a given dtype Parameters ---------- dtype : type Returns ------- `np.nan` if `dtype` is real or complex 0 otherwise
def _revcheck(self, func, version): ''' Internal function to see if a version is func than what we have determined to be talking to. This is very useful for newer API calls to make sure we don't accidentally make a call to something that doesnt exist. ''' current...
Internal function to see if a version is func than what we have determined to be talking to. This is very useful for newer API calls to make sure we don't accidentally make a call to something that doesnt exist.
def is_executable(command): """Returns if a command matches an executable on the PATH""" paths = os.environ.get("PATH", "").split(os.path.pathsep) candidates = [command] + [os.path.join(p, command) for p in paths] return any(os.access(path, os.X_OK) for path in candidates)
Returns if a command matches an executable on the PATH
def draw_capitan_score_bitmap(self, export_path: ExportPath) -> None: """ Draws the 30x30 symbol into the given file :param export_path: The path, where the symbols should be created on disk """ with Image.fromarray(self.image_data, mode='L') as image: image.save(expo...
Draws the 30x30 symbol into the given file :param export_path: The path, where the symbols should be created on disk
def new(params, num_components, event_shape=(), validate_args=False, name=None): """Create the distribution instance from a `params` vector.""" return MixtureSameFamily.new( params, num_components, IndependentLogistic( event_shape, validate_args=validate_args, name=...
Create the distribution instance from a `params` vector.
def n_day(date_string): """ date_string string in format "(number|a) day(s) ago" """ today = datetime.date.today() match = re.match(r'(\d{1,3}|a) days? ago', date_string) groups = match.groups() if groups: decrement = groups[0] if decrement...
date_string string in format "(number|a) day(s) ago"
def scaleBy(self, value, origin=None, width=False, height=False): """ %s **width** indicates if the glyph's width should be scaled. **height** indicates if the glyph's height should be scaled. The origin must not be specified when scaling the width or height. """ ...
%s **width** indicates if the glyph's width should be scaled. **height** indicates if the glyph's height should be scaled. The origin must not be specified when scaling the width or height.
def _get_ds_descriptions_unsorted( cls, data, ignore_keys=['attrs', 'plotter'], nums=None): """Recursive method to get all the file names or datasets out of a dictionary `data` created with the :meth`array_info` method""" ds_description = {'ds', 'fname', 'num', 'arr', 'store'} ...
Recursive method to get all the file names or datasets out of a dictionary `data` created with the :meth`array_info` method
def from_fp(self, file_pointer, comment_lead=['c']): """ Read a WCNF+ formula from a file pointer. A file pointer should be specified as an argument. The only default argument is ``comment_lead``, which can be used for parsing specific comment lines. ...
Read a WCNF+ formula from a file pointer. A file pointer should be specified as an argument. The only default argument is ``comment_lead``, which can be used for parsing specific comment lines. :param file_pointer: a file pointer to read the formula from. :pa...
async def _get(self, url: str) -> str: """A small wrapper method which makes a quick GET request Parameters ---------- url : str The URL to get. Returns ------- str The raw html of the requested page. Raises ------ ...
A small wrapper method which makes a quick GET request Parameters ---------- url : str The URL to get. Returns ------- str The raw html of the requested page. Raises ------ RuneConnectionError If the GET respo...
def parseAttributes(self, attributes=None, **kwAttributes): """Parses CSS attribute source strings, and return as an inline stylesheet. Use to parse a tag's highly CSS-based attributes like 'font'. See also: parseSingleAttr """ attributes = attributes if attributes is not None e...
Parses CSS attribute source strings, and return as an inline stylesheet. Use to parse a tag's highly CSS-based attributes like 'font'. See also: parseSingleAttr
def r2_score(df, col_true, col_pred=None): """ Compute determination coefficient (R2) of a predicted DataFrame. Note that this method will trigger the defined flow to execute. :param df: predicted data frame :type df: DataFrame :param col_true: column name of true value :type col_true: str...
Compute determination coefficient (R2) of a predicted DataFrame. Note that this method will trigger the defined flow to execute. :param df: predicted data frame :type df: DataFrame :param col_true: column name of true value :type col_true: str :param col_true: column name of predicted value, '...
def find_teradata_home(): """ Attempts to find the Teradata install directory with the defaults for a given platform. Should always return `None` when the defaults are not present and the TERADATA_HOME environment variable wasn't explicitly set to the correct install location. """ if platfo...
Attempts to find the Teradata install directory with the defaults for a given platform. Should always return `None` when the defaults are not present and the TERADATA_HOME environment variable wasn't explicitly set to the correct install location.
def stream_by_method_name(name): """ Given the name of a Mitogen connection method, import its implementation module and return its Stream subclass. """ if name == u'local': name = u'parent' module = mitogen.core.import_module(u'mitogen.' + name) return module.Stream
Given the name of a Mitogen connection method, import its implementation module and return its Stream subclass.
def is_installed(self): """ Check if the tool is installed. Returns ------- is_installed : bool True if the tool is installed. """ return self.is_configured() and os.access(self.bin(), os.X_OK)
Check if the tool is installed. Returns ------- is_installed : bool True if the tool is installed.
def _getattr_path(obj, path): """ getattr for a dot separated path If an AttributeError is raised, it will return None. """ if not path: return None for attr in path.split('.'): obj = getattr(obj, attr, None) return obj
getattr for a dot separated path If an AttributeError is raised, it will return None.
def save(diff, stream=sys.stdout, compact=False): "Serialize a patch object." flags = {'sort_keys': True} if not compact: flags['indent'] = 2 json.dump(diff, stream, **flags)
Serialize a patch object.
def preemphasis(signal, shift=1, cof=0.98): """preemphasising on the signal. Args: signal (array): The input signal. shift (int): The shift step. cof (float): The preemphasising coefficient. 0 equals to no filtering. Returns: array: The pre-emphasized signal. """ ...
preemphasising on the signal. Args: signal (array): The input signal. shift (int): The shift step. cof (float): The preemphasising coefficient. 0 equals to no filtering. Returns: array: The pre-emphasized signal.
def getGenoIndex(self,pos0=None,pos1=None,chrom=None,pos_cum0=None,pos_cum1=None): """computes 0-based genotype index from position of cumulative position. Positions can be given in one out of two ways: - position (pos0-pos1 on chrom) - cumulative position (pos_cum0-pos_cum1) I...
computes 0-based genotype index from position of cumulative position. Positions can be given in one out of two ways: - position (pos0-pos1 on chrom) - cumulative position (pos_cum0-pos_cum1) If all these are None (default), then all genotypes are returned Args: pos...
def execute_async(self, output_options=None, sampling=None, context=None, query_params=None): """ Initiate the query and return a QueryJob. Args: output_options: a QueryOutput object describing how to execute the query sampling: sampling function to use. No sampling is done if None. See bigquery.Sa...
Initiate the query and return a QueryJob. Args: output_options: a QueryOutput object describing how to execute the query sampling: sampling function to use. No sampling is done if None. See bigquery.Sampling context: an optional Context object providing project_id and credentials. If a specific ...
def transitions(self, return_matrix=True): """Returns the routing probabilities for each vertex in the graph. Parameters ---------- return_matrix : bool (optional, the default is ``True``) Specifies whether an :class:`~numpy.ndarray` is returned. If ``Fal...
Returns the routing probabilities for each vertex in the graph. Parameters ---------- return_matrix : bool (optional, the default is ``True``) Specifies whether an :class:`~numpy.ndarray` is returned. If ``False``, a dict is returned instead. Returns ...
def pipe_strregex(context=None, _INPUT=None, conf=None, **kwargs): """A string module that replaces text using regexes. Each has the general format: "In [field] replace [regex pattern] with [text]". Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : iterable of items or s...
A string module that replaces text using regexes. Each has the general format: "In [field] replace [regex pattern] with [text]". Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : iterable of items or strings conf : { 'RULE': [ { 'match...
def set_tweights_all(self, tweights): r""" Set all t-weights at once. Parameters ---------- tweights : iterable Containing a pair of numeric values for each of the graphs nodes. Notes ----- Since this method overrides already ...
r""" Set all t-weights at once. Parameters ---------- tweights : iterable Containing a pair of numeric values for each of the graphs nodes. Notes ----- Since this method overrides already existing t-weights, it is strongly rec...
def _shapeletOutput(self, x, y, beta, shapelets, precalc=True): """ returns the the numerical values of a set of shapelets at polar coordinates :param shapelets: set of shapelets [l=,r=,a_lr=] :type shapelets: array of size (n,3) :param coordPolar: set of coordinates in polar uni...
returns the the numerical values of a set of shapelets at polar coordinates :param shapelets: set of shapelets [l=,r=,a_lr=] :type shapelets: array of size (n,3) :param coordPolar: set of coordinates in polar units :type coordPolar: array of size (n,2) :returns: array of same si...
def set_fan_timer(self, timer): """ :param timer: an int between fan_timer_range :return: nothing """ desired_state = {"timer": timer} resp = self.api_interface.set_device_state(self, { "desired_state": desired_state }) self._update_state_fro...
:param timer: an int between fan_timer_range :return: nothing
def prepare_grant_uri(uri, client_id, response_type, redirect_uri=None, scope=None, state=None, **kwargs): """Prepare the authorization grant request URI. The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI ...
Prepare the authorization grant request URI. The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI using the ``application/x-www-form-urlencoded`` format as defined by [`W3C.REC-html401-19991224`_]: :param uri: :param ...
def aux_moveTree(offset, tree): """This a private recursive (You shouldn't have to call it) function that translates tree(and it's children) to a given x1""" if tree.x1 != None and tree.x2 != None : tree.x1, tree.x2 = tree.x1+offset, tree.x2+offset for c in tree.children: aux_moveTree(offset, c)
This a private recursive (You shouldn't have to call it) function that translates tree(and it's children) to a given x1
def download(fname, input_dir, dl_dir=None): """Download the resource from the storage.""" try: manager = _get_storage_manager(fname) except ValueError: return fname return manager.download(fname, input_dir, dl_dir)
Download the resource from the storage.
def collinear(args): """ %prog collinear a.b.anchors Reduce synteny blocks to strictly collinear, use dynamic programming in a procedure similar to DAGchainer. """ p = OptionParser(collinear.__doc__) p.set_beds() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(...
%prog collinear a.b.anchors Reduce synteny blocks to strictly collinear, use dynamic programming in a procedure similar to DAGchainer.
def _load_gui_setting(self, key, d=None): """ Safely reads the header setting and sets the appropriate control value. Parameters ---------- key Key string of the format 'self.controlname'. d = None Databox instance or dictionary, ...
Safely reads the header setting and sets the appropriate control value. Parameters ---------- key Key string of the format 'self.controlname'. d = None Databox instance or dictionary, presumably containing the aforementioned key. If d...
def reload(self, message): """恢复方法 Arguments: message {[type]} -- [description] """ self.phone = message.get('phone') self.level = message.get('level') self.utype = message.get('utype') self.coins = message.get('coins') self.wechat_id = messa...
恢复方法 Arguments: message {[type]} -- [description]
def find_log_dir(log_dir=None): """Returns the most suitable directory to put log files into. Args: log_dir: str|None, if specified, the logfile(s) will be created in that directory. Otherwise if the --log_dir command-line flag is provided, the logfile will be created in that directory. Other...
Returns the most suitable directory to put log files into. Args: log_dir: str|None, if specified, the logfile(s) will be created in that directory. Otherwise if the --log_dir command-line flag is provided, the logfile will be created in that directory. Otherwise the logfile will be crea...
def add_group(group, user=None): """Add the user to the group """ user = get_user(user) if user is None: raise ValueError("User '{}' not found".format(repr(user))) if isinstance(group, basestring): group = [group] elif isinstance(group, GroupData): group = [group] ...
Add the user to the group
def _expand(self, explore_iterable): """Explores the parameter according to the iterable and appends to the exploration range. Raises ParameterLockedException if the parameter is locked. Raises TypeError if the parameter does not support the data, the types of the data in the iterable a...
Explores the parameter according to the iterable and appends to the exploration range. Raises ParameterLockedException if the parameter is locked. Raises TypeError if the parameter does not support the data, the types of the data in the iterable are not the same as the type of the default value...
def make_bar(percentage): """ Draws a bar made of unicode box characters. :param percentage: A value between 0 and 100 :returns: Bar as a string """ bars = [' ', '▏', '▎', '▍', '▌', '▋', '▋', '▊', '▊', '█'] tens = int(percentage / 10) ones = int(percentage) - tens * 10 result = ten...
Draws a bar made of unicode box characters. :param percentage: A value between 0 and 100 :returns: Bar as a string
def get_record_rdd_from_rdd( self, rdd: 'RDD', data_processor: DataProcessor = SimpleDictionaryDataProcessor(), ) -> 'RDD': """ Converts a RDD of raw events into the `Record`s format for processing. `data_processor` is used to process the per row data to c...
Converts a RDD of raw events into the `Record`s format for processing. `data_processor` is used to process the per row data to convert them into `Record`. :param rdd: RDD containing the raw events. :param data_processor: `DataProcessor` to process each row in the given `rdd`. :return: R...
def _at_import(self, calculator, rule, scope, block): """ Implements @import Load and import mixins and functions and rules """ # TODO it would be neat to opt into warning that you're using # values/functions from a file you didn't explicitly import # TODO base-le...
Implements @import Load and import mixins and functions and rules
async def from_href(self): """Get the full object from spotify with a `href` attribute.""" if not hasattr(self, 'href'): raise TypeError('Spotify object has no `href` attribute, therefore cannot be retrived') elif hasattr(self, 'http'): return await self.http.request(('G...
Get the full object from spotify with a `href` attribute.
def fix_keys(self): """ Remove the _ from the keys of the results """ if not self.valid: return for hit in self._results['hits']['hits']: for key, item in list(hit.items()): if key.startswith("_"): hit[key[1:]] = item ...
Remove the _ from the keys of the results
def write_byte(self, address, data): """Write a single byte to the weather station. :param address: address to write to. :type address: int :param data: the value to write. :type data: int :return: success status. :rtype: bool """ buf = [ ...
Write a single byte to the weather station. :param address: address to write to. :type address: int :param data: the value to write. :type data: int :return: success status. :rtype: bool
def _wrap_type_instantiation(self, type_cls): """Wrap the creation of the type so that we can provide a null-stream to initialize it""" def wrapper(*args, **kwargs): # use args for struct arguments?? return type_cls(stream=self._null_stream) return wrapper
Wrap the creation of the type so that we can provide a null-stream to initialize it
def default_jardiff_options(updates=None): """ generate an options object with the appropriate default values in place for API usage of jardiff features. overrides is an optional dictionary which will be used to update fields on the options object. """ parser = create_optparser() option...
generate an options object with the appropriate default values in place for API usage of jardiff features. overrides is an optional dictionary which will be used to update fields on the options object.
def connect(self, keyspace=None, wait_for_all_pools=False): """ Creates and returns a new :class:`~.Session` object. If `keyspace` is specified, that keyspace will be the default keyspace for operations on the ``Session``. """ with self._lock: if self.is_shut...
Creates and returns a new :class:`~.Session` object. If `keyspace` is specified, that keyspace will be the default keyspace for operations on the ``Session``.
def object_links(self, multihash, **kwargs): """Returns the links pointed to by the specified object. .. code-block:: python >>> c.object_links('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDx … ca7D') {'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D', 'Links': [ ...
Returns the links pointed to by the specified object. .. code-block:: python >>> c.object_links('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDx … ca7D') {'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D', 'Links': [ {'Hash': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ug...
def run_scheduler(args): """Runs the scheduler on the local machine. To stop it, please use Ctrl-C.""" if not args.local: raise ValueError("The execute command can only be used with the '--local' command line option") jm = setup(args) jm.run_scheduler(parallel_jobs=args.parallel, job_ids=get_ids(args.job_id...
Runs the scheduler on the local machine. To stop it, please use Ctrl-C.
def importcmd(self, image_path, input_source): '''import will import (stdin) to the image Parameters ========== image_path: path to image to import to. input_source: input source or file import_type: if not specified, imports whatever function is given ''' from s...
import will import (stdin) to the image Parameters ========== image_path: path to image to import to. input_source: input source or file import_type: if not specified, imports whatever function is given
def disable_requiretty_on_sudoers(log=False): """ allow sudo calls through ssh without a tty """ if log: bookshelf2.logging_helpers.log_green( 'disabling requiretty on sudo calls') comment_line('/etc/sudoers', '^Defaults.*requiretty', use_sudo=True) return True
allow sudo calls through ssh without a tty
def group_norm(x, filters=None, num_groups=8, epsilon=1e-5): """Group normalization as in https://arxiv.org/abs/1803.08494.""" x_shape = shape_list(x) if filters is None: filters = x_shape[-1] assert len(x_shape) == 4 assert filters % num_groups == 0 # Prepare variables. scale = tf.get_variable( ...
Group normalization as in https://arxiv.org/abs/1803.08494.
def _handle_book(self, dtype, data, ts): """Updates the order book stored in self.books[chan_id]. :param dtype: :param data: :param ts: :return: """ self.log.debug("_handle_book: %s - %s - %s", dtype, data, ts) channel_id, *data = data log.debug("...
Updates the order book stored in self.books[chan_id]. :param dtype: :param data: :param ts: :return:
def prepare_input(self, extracted_str): """ Input raw string and do transformations, as set in template file. """ # Remove withspace if self.options['remove_whitespace']: optimized_str = re.sub(' +', '', extracted_str) else: optimized_str = extrac...
Input raw string and do transformations, as set in template file.
def init_validator(required, cls, *additional_validators): """ Create an attrs validator based on the cls provided and required setting. :param bool required: whether the field is required in a given model. :param cls: the expected class type of object value. :return: attrs validator chained correct...
Create an attrs validator based on the cls provided and required setting. :param bool required: whether the field is required in a given model. :param cls: the expected class type of object value. :return: attrs validator chained correctly (e.g. optional(instance_of))
def print_lh(self, joint=True): """ Print the total likelihood of the tree given the constrained leaves Parameters ---------- joint : bool If true, print joint LH, else print marginal LH """ try: u_lh = self.tree.unconstrained_sequence_...
Print the total likelihood of the tree given the constrained leaves Parameters ---------- joint : bool If true, print joint LH, else print marginal LH
def onKeyInCommandEntry(self, event): '''Called when a key is pressed when the command entry box has focus.''' if event.char == '\r': self.onSendCommand() self.canvas.focus_set()
Called when a key is pressed when the command entry box has focus.
def _emit(self, event): """ If the given event is a stat event, send a I{StatUpdate} command. """ if (event.get('interface') is not iaxiom.IStatEvent and 'athena_send_messages' not in event and 'athena_received_messages' not in event): return ...
If the given event is a stat event, send a I{StatUpdate} command.
def wrap_with_try(self, node): """Wrap an ast node in a 'try' node to enter debug on exception.""" handlers = [] if self.ignore_exceptions is None: handlers.append(ast.ExceptHandler(type=None, name=None, ...
Wrap an ast node in a 'try' node to enter debug on exception.
def _generate_full_recipe_message(self, destination, message, add_path_step): """Factory function to generate independent message objects for downstream recipients with different destinations.""" if add_path_step and self.recipe_pointer: recipe_path = self.recipe_path + [self.recipe_...
Factory function to generate independent message objects for downstream recipients with different destinations.
def from_frame_summary(cls, f): """ :param FrameSummary f: :rtype: DummyFrame """ return cls(filename=f.filename, lineno=f.lineno, name=f.name, f_locals=f.locals)
:param FrameSummary f: :rtype: DummyFrame
def is_equal_type(type_a: GraphQLType, type_b: GraphQLType): """Check whether two types are equal. Provided two types, return true if the types are equal (invariant).""" # Equivalent types are equal. if type_a is type_b: return True # If either type is non-null, the other must also be non-...
Check whether two types are equal. Provided two types, return true if the types are equal (invariant).
def create_backends_from_settings(self): """ Expects the Django setting "EVENT_TRACKING_BACKENDS" to be defined and point to a dictionary of backend engine configurations. Example:: EVENT_TRACKING_BACKENDS = { 'default': { 'ENGINE': 'some...
Expects the Django setting "EVENT_TRACKING_BACKENDS" to be defined and point to a dictionary of backend engine configurations. Example:: EVENT_TRACKING_BACKENDS = { 'default': { 'ENGINE': 'some.arbitrary.Backend', 'OPTIONS': { ...
def run_bot(bot_class, host, port, nick, channels=None, ssl=None): """\ Convenience function to start a bot on the given network, optionally joining some channels """ conn = IRCConnection(host, port, nick, ssl) bot_instance = bot_class(conn) while 1: if not conn.connect(): ...
\ Convenience function to start a bot on the given network, optionally joining some channels
def _set_redistribute_isis(self, v, load=False): """ Setter method for redistribute_isis, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_ipv6_uc_and_vrf_cmds_call_point_holder/redistribute/redistribute_isis (container) If this variable is read-onl...
Setter method for redistribute_isis, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_ipv6_uc_and_vrf_cmds_call_point_holder/redistribute/redistribute_isis (container) If this variable is read-only (config: false) in the source YANG file, then _set_redi...
def _merge_by_type(lhs, rhs, type_): """Helper for '_merge_chunk'.""" merger = _MERGE_BY_TYPE[type_.code] return merger(lhs, rhs, type_)
Helper for '_merge_chunk'.
def post(self, pid, record): """Handle POST deposit files. Permission required: `update_permission_factory`. :param pid: Pid object (from url). :param record: Record object resolved from the pid. """ # load the file uploaded_file = request.files['file'] ...
Handle POST deposit files. Permission required: `update_permission_factory`. :param pid: Pid object (from url). :param record: Record object resolved from the pid.
def printFieldsHeader(self, f, d): """ Prints out table header based on the size of the data in columns """ fstr = "Field Name" dstr = "Description" f = max(f, len(fstr)) d = max(d, len(dstr)) print('|{0}{1}|{2}{3}|'.format(fstr, ' ' * (f - len(fstr)), ds...
Prints out table header based on the size of the data in columns
def vm_diskstats(vm_=None): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: .. code-block:: python [ 'your-vm': { 'io_read_kbs' : 0, 'io_write_kbs' : 0 }, ... ] If you p...
Return disk usage counters used by the vms on this hyper in a list of dicts: .. code-block:: python [ 'your-vm': { 'io_read_kbs' : 0, 'io_write_kbs' : 0 }, ... ] If you pass a VM name in as an argument then it ...
def setup_prjs_page(self, ): """Create and set the model on the projects page :returns: None :rtype: None :raises: None """ self.prjs_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents) log.debug("Loading projects for projects page.") ...
Create and set the model on the projects page :returns: None :rtype: None :raises: None
def check_output_variable(self, variable): """Check to see if output variable was requested by downstream app. Using the auto generated dictionary of output variables check to see if provided variable was requested by downstream app. Args: variable (string): The variable na...
Check to see if output variable was requested by downstream app. Using the auto generated dictionary of output variables check to see if provided variable was requested by downstream app. Args: variable (string): The variable name, not the full variable. Returns: ...
def set(self, instance, value, **kw): """Converts the value into a DateTime object before setting. """ if value: try: value = DateTime(value) except SyntaxError: logger.warn("Value '{}' is not a valid DateTime string" ...
Converts the value into a DateTime object before setting.
def name(self): """ Returns a name for this defect """ poss_deflist = sorted( self.bulk_structure.get_sites_in_sphere(self.site.coords, 2, include_index=True), key=lambda x: x[1]) defindex = poss_deflist[0][2] return "Sub_{}_on_{}_mult{}".format(self.site.spec...
Returns a name for this defect
def getEstTraitCovar(self,term_i=None): """ Returns explicitly the estimated trait covariance matrix Args: term_i: index of the term we are interested in """ assert self.P>1, 'Trait covars not defined for single trait analysis' if term_i==None: ...
Returns explicitly the estimated trait covariance matrix Args: term_i: index of the term we are interested in
def rollback(self, date): """Roll date backward to nearest start of year""" if self.onOffset(date): return date else: return date - YearBegin(month=self.month)
Roll date backward to nearest start of year