code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def parseService(self, yadis_url, uri, type_uris, service_element): """Set the state of this object based on the contents of the service element.""" self.type_uris = type_uris self.server_url = uri self.used_yadis = True if not self.isOPIdentifier(): # XXX: T...
Set the state of this object based on the contents of the service element.
def set_subparsers_args(self, *args, **kwargs): """ Sets args and kwargs that are passed when creating a subparsers group in an argparse.ArgumentParser i.e. when calling argparser.ArgumentParser.add_subparsers """ self.subparsers_args = args self.subparsers_kwargs...
Sets args and kwargs that are passed when creating a subparsers group in an argparse.ArgumentParser i.e. when calling argparser.ArgumentParser.add_subparsers
def add_thermodynamic(self, em=1000): """Apply thermodynamic constraints to the model. Adding these constraints restricts the solution space to only contain solutions that have no internal loops [Schilling00]_. This is solved as a MILP problem as described in [Muller13]_. The time to so...
Apply thermodynamic constraints to the model. Adding these constraints restricts the solution space to only contain solutions that have no internal loops [Schilling00]_. This is solved as a MILP problem as described in [Muller13]_. The time to solve a problem with thermodynamic constrai...
async def async_get_current_program(channel, no_cache=False): ''' Get the current program info ''' chan = await async_determine_channel(channel) guide = await async_get_program_guide(chan, no_cache) if not guide: _LOGGER.warning('Could not retrieve TV program for %s', channel) re...
Get the current program info
def setItemPolicy(self, item, policy): """Sets the policy of the given item""" index = item._combobox_indices[self.ColAction].get(policy, 0) self._updateItemComboBoxIndex(item, self.ColAction, index) combobox = self.itemWidget(item, self.ColAction) if combobox: combob...
Sets the policy of the given item
def get_users(profile='grafana'): ''' List all users. profile Configuration profile used to connect to the Grafana instance. Default is 'grafana'. CLI Example: .. code-block:: bash salt '*' grafana4.get_users ''' if isinstance(profile, string_types): profi...
List all users. profile Configuration profile used to connect to the Grafana instance. Default is 'grafana'. CLI Example: .. code-block:: bash salt '*' grafana4.get_users
def make_qr(content, error=None, version=None, mode=None, mask=None, encoding=None, eci=False, boost_error=True): """\ Creates a QR Code (never a Micro QR Code). See :py:func:`make` for a description of the parameters. :rtype: QRCode """ return make(content, error=error, version=ve...
\ Creates a QR Code (never a Micro QR Code). See :py:func:`make` for a description of the parameters. :rtype: QRCode
def get_or_create_model_key(self): """ Get or create key for the model. Returns ~~~~~~~ (model_key, boolean) tuple """ model_cache_info = model_cache_backend.retrieve_model_cache_info(self.model._meta.db_table) if not model_cache_info: return...
Get or create key for the model. Returns ~~~~~~~ (model_key, boolean) tuple
def compile_pycos(toc): """Given a TOC or equivalent list of tuples, generates all the required pyc/pyo files, writing in a local directory if required, and returns the list of tuples with the updated pathnames. """ global BUILDPATH # For those modules that need to be rebuilt, use the build dir...
Given a TOC or equivalent list of tuples, generates all the required pyc/pyo files, writing in a local directory if required, and returns the list of tuples with the updated pathnames.
def contents(self): """Get svg string """ c = self._header[:] c.append(' font-weight="{}"'.format(self.font_weight)) c.append(' font-family="{}"'.format(self.font_family)) c.append(' width="{}" height="{}"'.format(*self.screen_size)) sclw = self.original_size[0] *...
Get svg string
def _seg(chars): """按是否是汉字进行分词""" s = '' # 保存一个词 ret = [] # 分词结果 flag = 0 # 上一个字符是什么? 0: 汉字, 1: 不是汉字 for n, c in enumerate(chars): if RE_HANS.match(c): # 汉字, 确定 flag 的初始值 if n == 0: # 第一个字符 flag = 0 if flag == 0: s += c ...
按是否是汉字进行分词
def delete(ctx, short_name): """Delete a specific subscription by short name""" wva = get_wva(ctx) subscription = wva.get_subscription(short_name) subscription.delete()
Delete a specific subscription by short name
def transform_audio(self, y): '''Apply the scale transform to the tempogram Parameters ---------- y : np.ndarray The audio buffer Returns ------- data : dict data['temposcale'] : np.ndarray, shape=(n_frames, n_fmt) The sca...
Apply the scale transform to the tempogram Parameters ---------- y : np.ndarray The audio buffer Returns ------- data : dict data['temposcale'] : np.ndarray, shape=(n_frames, n_fmt) The scale transform magnitude coefficients
def default_namespace(self, value): """ Setter for **self.__default_namespace** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format( ...
Setter for **self.__default_namespace** attribute. :param value: Attribute value. :type value: unicode
def handle_msg(self, msg): """BGP message handler. BGP message handling is shared between protocol instance and peer. Peer only handles limited messages under suitable state. Here we handle KEEPALIVE, UPDATE and ROUTE_REFRESH messages. UPDATE and ROUTE_REFRESH messages are handl...
BGP message handler. BGP message handling is shared between protocol instance and peer. Peer only handles limited messages under suitable state. Here we handle KEEPALIVE, UPDATE and ROUTE_REFRESH messages. UPDATE and ROUTE_REFRESH messages are handled only after session is established.
def get_price(item): """Finds the price with the default locationGroupId""" the_price = "No Default Pricing" for price in item.get('prices', []): if not price.get('locationGroupId'): the_price = "%0.4f" % float(price['hourlyRecurringFee']) return the_price
Finds the price with the default locationGroupId
def gevent_monkey_patch_report(self): """ Report effective gevent monkey patching on the logs. """ try: import gevent.socket import socket if gevent.socket.socket is socket.socket: self.log("gevent monkey patching is active") ...
Report effective gevent monkey patching on the logs.
def _format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': salt.utils.json.loads(job.get('arg', '[]')), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-targe...
Format the job instance correctly
def size(self, source): '''Get the size component of the given s3url. If it is a directory, combine the sizes of all the files under that directory. Subdirectories will not be counted unless --recursive option is set. ''' result = [] for src in self.source_expand(source): size...
Get the size component of the given s3url. If it is a directory, combine the sizes of all the files under that directory. Subdirectories will not be counted unless --recursive option is set.
def trace(function, *args, **k) : """Decorates a function by tracing the begining and end of the function execution, if doTrace global is True""" if doTrace : print ("> "+function.__name__, args, k) result = function(*args, **k) if doTrace : print ("< "+function.__name__, args, k, "->", result) return result
Decorates a function by tracing the begining and end of the function execution, if doTrace global is True
def list(self, *args, **kwargs): """ List networks. Similar to the ``docker networks ls`` command. Args: names (:py:class:`list`): List of names to filter by. ids (:py:class:`list`): List of ids to filter by. filters (dict): Filters to be processed on the net...
List networks. Similar to the ``docker networks ls`` command. Args: names (:py:class:`list`): List of names to filter by. ids (:py:class:`list`): List of ids to filter by. filters (dict): Filters to be processed on the network list. Available filters: ...
def step1ab(self): """step1ab() gets rid of plurals and -ed or -ing. e.g. caresses -> caress ponies -> poni ties -> ti caress -> caress cats -> cat feed -> feed agreed -> agree disabled -> ...
step1ab() gets rid of plurals and -ed or -ing. e.g. caresses -> caress ponies -> poni ties -> ti caress -> caress cats -> cat feed -> feed agreed -> agree disabled -> disable matting ...
def _compute_zs_mat(sz:TensorImageSize, scale:float, squish:float, invert:bool, row_pct:float, col_pct:float)->AffineMatrix: "Utility routine to compute zoom/squish matrix." orig_ratio = math.sqrt(sz[1]/sz[0]) for s,r,i in zip(scale,squish, invert): s,r = 1/math.sqrt(s),math.sqrt(...
Utility routine to compute zoom/squish matrix.
def _set_data(self, data, offset=None, copy=False): """Internal method for set_data. """ # Copy if needed, check/normalize shape data = np.array(data, copy=copy) data = self._normalize_shape(data) # Maybe resize to purge DATA commands? if offset ...
Internal method for set_data.
def _generate_struct_deserializer(self, struct): """Emits the deserialize method for the serialization object for the given struct.""" struct_name = fmt_class_prefix(struct) with self.block_func( func='deserialize', args=fmt_func_args_declaration([('valueDict', ...
Emits the deserialize method for the serialization object for the given struct.
def read_string(self, len): """Reads a string of a given length from the packet""" format = '!' + str(len) + 's' length = struct.calcsize(format) info = struct.unpack(format, self.data[self.offset:self.offset + length]) self.offset += length return info[0]
Reads a string of a given length from the packet
def __dtw_calc_accu_cost(C, D, D_steps, step_sizes_sigma, weights_mul, weights_add, max_0, max_1): # pragma: no cover '''Calculate the accumulated cost matrix D. Use dynamic programming to calculate the accumulated costs. Parameters ---------- C : np.ndarray [shape=(N, M)...
Calculate the accumulated cost matrix D. Use dynamic programming to calculate the accumulated costs. Parameters ---------- C : np.ndarray [shape=(N, M)] pre-computed cost matrix D : np.ndarray [shape=(N, M)] accumulated cost matrix D_steps : np.ndarray [shape=(N, M)] ...
def split_grads_by_size(threshold_size, device_grads): """Break gradients into two sets according to tensor size. Args: threshold_size: int size cutoff for small vs large tensor. device_grads: List of lists of (gradient, variable) tuples. The outer list is over devices. The inner list is over in...
Break gradients into two sets according to tensor size. Args: threshold_size: int size cutoff for small vs large tensor. device_grads: List of lists of (gradient, variable) tuples. The outer list is over devices. The inner list is over individual gradients. Returns: small_grads: Subset of dev...
def fuse_batchnorm_weights(gamma, beta, mean, var, epsilon): # https://github.com/Tencent/ncnn/blob/master/src/layer/batchnorm.cpp """ float sqrt_var = sqrt(var_data[i]); a_data[i] = bias_data[i] - slope_data[i] * mean_data[i] / sqrt_var; b_data[i] = slope_data[i] / sqrt_var; ... ...
float sqrt_var = sqrt(var_data[i]); a_data[i] = bias_data[i] - slope_data[i] * mean_data[i] / sqrt_var; b_data[i] = slope_data[i] / sqrt_var; ... ptr[i] = b * ptr[i] + a;
def _unpickle_channel(raw): """Try and unpickle a channel with sensible error handling """ try: return pickle.loads(raw) except (ValueError, pickle.UnpicklingError, EOFError, TypeError, IndexError) as exc: # maybe not pickled if isinstance(raw, bytes): raw...
Try and unpickle a channel with sensible error handling
def getCert(username, password, certHost=_SERVER, certfile=None, certQuery=_PROXY): """Access the cadc certificate server.""" if certfile is None: certfile = tempfile.NamedTemporaryFile() # Add the username and password. # If we knew the realm, we could use ...
Access the cadc certificate server.
def _process_health_pill_value(self, wall_time, step, device_name, output_slot, node_name, tensor_proto, ...
Creates a HealthPillEvent containing various properties of a health pill. Args: wall_time: The wall time in seconds. step: The session run step of the event. device_name: The name of the node's device. output_slot: The numeric output slot. node_name: The name of the node (without the ...
def iplot_histogram(data, figsize=None, number_to_keep=None, sort='asc', legend=None): """ Create a histogram representation. Graphical representation of the input array using a vertical bars style graph. Args: data (list or dict): This is either a list of ...
Create a histogram representation. Graphical representation of the input array using a vertical bars style graph. Args: data (list or dict): This is either a list of dicts or a single dict containing the values to represent (ex. {'001' : 130}) figsize (...
def new_data(self, mem, addr, data): """Callback for when new memory data has been fetched""" done = False if mem.id == self.id: if addr == LocoMemory.MEM_LOCO_INFO: self.nr_of_anchors = data[0] if self.nr_of_anchors == 0: done = Tr...
Callback for when new memory data has been fetched
def nvmlDeviceSetEccMode(handle, mode): r""" /** * Set the ECC mode for the device. * * For Kepler &tm; or newer fully supported devices. * Only applicable to devices with ECC. * Requires \a NVML_INFOROM_ECC version 1.0 or higher. * Requires root/admin permissions. * * Th...
r""" /** * Set the ECC mode for the device. * * For Kepler &tm; or newer fully supported devices. * Only applicable to devices with ECC. * Requires \a NVML_INFOROM_ECC version 1.0 or higher. * Requires root/admin permissions. * * The ECC mode determines whether the GPU enable...
def opened(self, block_identifier: BlockSpecification) -> bool: """ Returns if the channel is opened. """ return self.token_network.channel_is_opened( participant1=self.participant1, participant2=self.participant2, block_identifier=block_identifier, channe...
Returns if the channel is opened.
def buildcontent(self): """Build HTML content only, no header or body tags. To be useful this will usually require the attribute `juqery_on_ready` to be set which will wrap the js in $(function(){<regular_js>};) """ self.buildcontainer() # if the subclass has a method bui...
Build HTML content only, no header or body tags. To be useful this will usually require the attribute `juqery_on_ready` to be set which will wrap the js in $(function(){<regular_js>};)
def basic_stats(self): """Return a markdown representation of simple statistics.""" comment_score = sum(comment.score for comment in self.comments) if self.comments: comment_duration = (self.comments[-1].created_utc - self.comments[0].created_utc) ...
Return a markdown representation of simple statistics.
def _create_ring(self, nodes): """Generate a ketama compatible continuum/ring. """ for node_name, node_conf in nodes: for w in range(0, node_conf['vnodes'] * node_conf['weight']): self._distribution[node_name] += 1 self._ring[self.hashi('%s-%s' % (node...
Generate a ketama compatible continuum/ring.
def visualRect(self, index): """ Returns the visual rectangle for the inputed index. :param index | <QModelIndex> :return <QtCore.QRect> """ rect = super(XTreeWidget, self).visualRect(index) item = self.itemFromIndex(index) ...
Returns the visual rectangle for the inputed index. :param index | <QModelIndex> :return <QtCore.QRect>
def zero_level_calibrate(self, duration, t0=0.0): """Performs zero-level calibration from the chosen time interval. This changes the previously lodaded data in-place. Parameters -------------------- duration : float Number of timeunits to use for...
Performs zero-level calibration from the chosen time interval. This changes the previously lodaded data in-place. Parameters -------------------- duration : float Number of timeunits to use for calibration t0 : float Starting tim...
def inference(self, observed_arr): ''' Draws samples from the `true` distribution. Args: observed_arr: `np.ndarray` of observed data points. Returns: `np.ndarray` of inferenced. ''' if observed_arr.ndim < 4: # A...
Draws samples from the `true` distribution. Args: observed_arr: `np.ndarray` of observed data points. Returns: `np.ndarray` of inferenced.
def start(self, *args, **kwargs): """Start the task. This is: * not threadsave * assumed to be called in the gtk mainloop """ args = (self.counter,) + args thread = threading.Thread( target=self._work_callback, args=args, k...
Start the task. This is: * not threadsave * assumed to be called in the gtk mainloop
def orient_directed_graph(self, data, graph): """Run the algorithm on a directed_graph. Args: data (pandas.DataFrame): DataFrame containing the data graph (networkx.DiGraph): Skeleton of the graph to orient Returns: networkx.DiGraph: Solution on the given sk...
Run the algorithm on a directed_graph. Args: data (pandas.DataFrame): DataFrame containing the data graph (networkx.DiGraph): Skeleton of the graph to orient Returns: networkx.DiGraph: Solution on the given skeleton. .. warning:: The algorithm is...
def nvmlUnitGetHandleByIndex(index): r""" /** * Acquire the handle for a particular unit, based on its index. * * For S-class products. * * Valid indices are derived from the \a unitCount returned by \ref nvmlUnitGetCount(). * For example, if \a unitCount is 2 the valid indices a...
r""" /** * Acquire the handle for a particular unit, based on its index. * * For S-class products. * * Valid indices are derived from the \a unitCount returned by \ref nvmlUnitGetCount(). * For example, if \a unitCount is 2 the valid indices are 0 and 1, corresponding to UNIT 0 and U...
def figure_tensor(func, **tf_pyfunc_kwargs): '''Decorate matplotlib drawing routines. This dectorator is meant to decorate functions that return matplotlib figures. The decorated function has to have the following signature def decorated(*args, **kwargs) -> figure or iterable of figures w...
Decorate matplotlib drawing routines. This dectorator is meant to decorate functions that return matplotlib figures. The decorated function has to have the following signature def decorated(*args, **kwargs) -> figure or iterable of figures where `*args` can be any positional argument and `**k...
def _check_feature_types(self): """ Checks that feature types are a subset of allowed feature types. (`None` is handled :raises: ValueError """ if self.default_feature_type is not None and self.default_feature_type not in self.allowed_feature_types: raise ValueError('D...
Checks that feature types are a subset of allowed feature types. (`None` is handled :raises: ValueError
def update(self): """Update the AMP list.""" # Init new stats stats = self.get_init_value() if self.input_method == 'local': for k, v in iteritems(self.glances_amps.update()): stats.append({'key': k, 'name': v.NAME, ...
Update the AMP list.
def sync_objects_out(self, force=False): """Synchronize from objects to records, and records to files""" self.log('---- Sync Objects Out ----') from ambry.bundle.files import BuildSourceFile self.dstate = self.STATES.BUILDING for f in self.build_source_files.list_records(): ...
Synchronize from objects to records, and records to files
def to_example_dict(encoder, inputs, mask, outputs): """Convert single h5 record to an example dict.""" # Inputs bases = [] input_ids = [] last_idx = -1 for row in np.argwhere(inputs): idx, base_id = row idx, base_id = int(idx), int(base_id) assert idx > last_idx # if not, means 2 True values i...
Convert single h5 record to an example dict.
def add_rednoise(psr,A,gamma,components=10,seed=None): """Add red noise with P(f) = A^2 / (12 pi^2) (f year)^-gamma, using `components` Fourier bases. Optionally take a pseudorandom-number-generator seed.""" if seed is not None: N.random.seed(seed) t = psr.toas() minx, maxx = N.min...
Add red noise with P(f) = A^2 / (12 pi^2) (f year)^-gamma, using `components` Fourier bases. Optionally take a pseudorandom-number-generator seed.
def get_getter(cls, prop_name, # @NoSelf user_getter=None, getter_takes_name=False): """Returns a function wich is a getter for a property. prop_name is the name off the property. user_getter is an optional function doing the work. If specified, that function will be...
Returns a function wich is a getter for a property. prop_name is the name off the property. user_getter is an optional function doing the work. If specified, that function will be called instead of getting the attribute whose name is in 'prop_name'. If user_getter is specified ...
def validate(self, **kwargs): """ Validates a data file :param file_path: path to file to be loaded. :param data: pre loaded YAML object (optional). :return: Bool to indicate the validity of the file. """ default_data_schema = json.load(open(self.default_schema_...
Validates a data file :param file_path: path to file to be loaded. :param data: pre loaded YAML object (optional). :return: Bool to indicate the validity of the file.
def apply(self, data, path=None, applicator=None): """ Apply permissions in this set to the provided data, effectively removing all keys from it are not permissioned to be viewed Arguments: data -- dict of data Returns: Cleaned data """ if app...
Apply permissions in this set to the provided data, effectively removing all keys from it are not permissioned to be viewed Arguments: data -- dict of data Returns: Cleaned data
def parse_iso8601(text): """ ISO 8601 compliant parser. :param text: The string to parse :type text: str :rtype: datetime.datetime or datetime.time or datetime.date """ parsed = _parse_iso8601_duration(text) if parsed is not None: return parsed m = ISO8601_DT.match(text) ...
ISO 8601 compliant parser. :param text: The string to parse :type text: str :rtype: datetime.datetime or datetime.time or datetime.date
def config(filename): """ Construct `Config` object and return a list. :parse filename: A string containing the path to YAML file. :return: list """ Config = collections.namedtuple('Config', [ 'git', 'lock_file', 'version', 'name', 'src', 'dst', ...
Construct `Config` object and return a list. :parse filename: A string containing the path to YAML file. :return: list
def process_pure_python(self, content): """ content is a list of strings. it is unedited directive conent This runs it line by line in the InteractiveShell, prepends prompts as needed capturing stderr and stdout, then returns the content as a list as if it were ipython code ...
content is a list of strings. it is unedited directive conent This runs it line by line in the InteractiveShell, prepends prompts as needed capturing stderr and stdout, then returns the content as a list as if it were ipython code
def config_unset(name, value_regex=None, repo=None, user=None, password=None, output_encoding=None, **kwargs): r''' .. versionadded:: 2015.8.0 Ensure that the named config key is not present name ...
r''' .. versionadded:: 2015.8.0 Ensure that the named config key is not present name The name of the configuration key to unset. This value can be a regex, but the regex must match the entire key name. For example, ``foo\.`` would not match all keys in the ``foo`` section, it would...
def simple_memoize(callable_object): """Simple memoization for functions without keyword arguments. This is useful for mapping code objects to module in this context. inspect.getmodule() requires a number of system calls, which may slow down the tracing considerably. Caching the mapping from code objec...
Simple memoization for functions without keyword arguments. This is useful for mapping code objects to module in this context. inspect.getmodule() requires a number of system calls, which may slow down the tracing considerably. Caching the mapping from code objects (there is *one* code object for each ...
def _get_friends_count(session, user_id): """ https://vk.com/dev/friends.get """ response = session.fetch('friends.get', user_id=user_id, count=1) return response["count"]
https://vk.com/dev/friends.get
def get_properties(self, mode, name_list=None): """Return properties as list of 2-tuples (name, value). If mode is 'name', then None is returned for the value. name the property name in Clark notation. value may have different types, depending on the status: ...
Return properties as list of 2-tuples (name, value). If mode is 'name', then None is returned for the value. name the property name in Clark notation. value may have different types, depending on the status: - string or unicode: for standard property values....
def handle_pkg_optional_fields(self, package, package_node): """ Write package optional fields. """ self.handle_package_literal_optional(package, package_node, self.spdx_namespace.versionInfo, 'version') self.handle_package_literal_optional(package, package_node, self.spdx_namesp...
Write package optional fields.
def check_num_columns_in_param_list_arrays(param_list): """ Ensure that each array in param_list, that is not None, has the same number of columns. Raises a helpful ValueError if otherwise. Parameters ---------- param_list : list of ndarrays or None. Returns ------- None. """ ...
Ensure that each array in param_list, that is not None, has the same number of columns. Raises a helpful ValueError if otherwise. Parameters ---------- param_list : list of ndarrays or None. Returns ------- None.
def reverse(self, search: str): """Return reverse DNS lookup information we have for the given IPv{4,6} address with history of changes. Multiple reverse DNS entries may match. We return all of them. """ url_path = "/api/reverse/{search}".format(search=search) return self._request(path=u...
Return reverse DNS lookup information we have for the given IPv{4,6} address with history of changes. Multiple reverse DNS entries may match. We return all of them.
def delete_folder(self, folder_id, folder_etag=None, recursive=None): '''Delete specified folder. Pass folder_etag to avoid race conditions (raises error 412). recursive keyword does just what it says on the tin.''' return self( join('folders', folder_id), dict(recursive=recursive), method='delete', hea...
Delete specified folder. Pass folder_etag to avoid race conditions (raises error 412). recursive keyword does just what it says on the tin.
def sieve(self, name=None, sample_rate=None, sample_range=None, exact_match=False, **others): """Find all `Channels <Channel>` in this list matching the specified criteria. Parameters ---------- name : `str`, or regular expression any part of the channe...
Find all `Channels <Channel>` in this list matching the specified criteria. Parameters ---------- name : `str`, or regular expression any part of the channel name against which to match (or full name if `exact_match=False` is given) sample_rate : `float` ...
def _on_connection_close(self, connection, reply_code_or_reason, reply_text=None): """ Callback invoked when a previously-opened connection is closed. Args: connection (pika.connection.SelectConnection): The connection that was just closed. reply_code_or_...
Callback invoked when a previously-opened connection is closed. Args: connection (pika.connection.SelectConnection): The connection that was just closed. reply_code_or_reason (int|Exception): The reason why the channel was closed. In older versions of pik...
def filepattern(self, *args, **kwargs): """Returns a list of filepatterns, one for each problem.""" return [p.filepattern(*args, **kwargs) for p in self.problems]
Returns a list of filepatterns, one for each problem.
def main(argv=None): """ Call transliterator from a command line. python transliterator.py text inputFormat outputFormat ... writes the transliterated text to stdout text -- the text to be transliterated OR the name of a file containing the text inputFormat -- the name of the characte...
Call transliterator from a command line. python transliterator.py text inputFormat outputFormat ... writes the transliterated text to stdout text -- the text to be transliterated OR the name of a file containing the text inputFormat -- the name of the character block or transliteration sc...
def get_commits(self, repo, organization='llnl'): """ Retrieves the number of commits to a repo in the organization. If it is the first time getting commits for a repo, it will get all commits and save them to JSON. If there are previous commits saved, it will only get commits th...
Retrieves the number of commits to a repo in the organization. If it is the first time getting commits for a repo, it will get all commits and save them to JSON. If there are previous commits saved, it will only get commits that have not been saved to disk since the last date of commits.
def get(self, request, path): """Return HTML (or other related content) for Meteor.""" if path == 'meteor_runtime_config.js': config = { 'DDP_DEFAULT_CONNECTION_URL': request.build_absolute_uri('/'), 'PUBLIC_SETTINGS': self.meteor_settings.get('public', {}), ...
Return HTML (or other related content) for Meteor.
def send_to_azure(instance, data, thread_number, sub_commit, table_info, nb_threads): """ data = { "table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist, "columns_name" : [first_column_name,second_column_name,...,last_column_name], "rows" : [[...
data = { "table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist, "columns_name" : [first_column_name,second_column_name,...,last_column_name], "rows" : [[first_raw_value,second_raw_value,...,last_raw_value],...] }
def get_function(self, name): """ Get a ValueRef pointing to the function named *name*. NameError is raised if the symbol isn't found. """ p = ffi.lib.LLVMPY_GetNamedFunction(self, _encode_string(name)) if not p: raise NameError(name) return ValueRef(p...
Get a ValueRef pointing to the function named *name*. NameError is raised if the symbol isn't found.
def handle_ChannelClose(self, frame): """ AMQP server closed the channel with an error """ # By docs: # The response to receiving a Close after sending Close must be to # send Close-Ok. # # No need for additional checks self.sender.send_CloseOK() exc = ex...
AMQP server closed the channel with an error
def factory(ec, code=None, token=None, refresh=None, **kwargs): """ Create a token handler :param code: :param token: :param refresh: :return: TokenHandler instance """ TTYPE = {'code': 'A', 'token': 'T', 'refresh': 'R'} args = {} if code: args['code_handler'] = init_...
Create a token handler :param code: :param token: :param refresh: :return: TokenHandler instance
def __get_untitled_file_name(self): """ Returns an untitled file name. :return: Untitled file name. :rtype: unicode """ untitledNameId = Editor._Editor__untitled_name_id for file in self.list_files(): if not os.path.dirname(file) == self.__default_se...
Returns an untitled file name. :return: Untitled file name. :rtype: unicode
def create_dataset(self, name, **kwargs): """Create an array. Parameters ---------- name : string Array name. data : array_like, optional Initial data. shape : int or tuple of ints Array shape. chunks : int or tuple of ints, op...
Create an array. Parameters ---------- name : string Array name. data : array_like, optional Initial data. shape : int or tuple of ints Array shape. chunks : int or tuple of ints, optional Chunk shape. If not provided, will...
def _verify(function): """decorator to ensure pin is properly set up""" # @functools.wraps def wrapped(pin, *args, **kwargs): pin = int(pin) if pin not in _open: ppath = gpiopath(pin) if not os.path.exists(ppath): log.debug("Creating Pin {0}".f...
decorator to ensure pin is properly set up
def get_type(self): """ Return the type of the field :rtype: string """ if self.type_idx_value == None: self.type_idx_value = self.CM.get_type(self.type_idx) return self.type_idx_value
Return the type of the field :rtype: string
async def issue_cmd(self, cmd, value, retry=3): """ Issue a command, then await and return the return value. This method is a coroutine """ async with self._cmd_lock: if not self.connected: _LOGGER.debug( "Serial transport closed, ...
Issue a command, then await and return the return value. This method is a coroutine
def respond(self, text, sessionID = "general"): """ Generate a response to the user input. :type text: str :param text: The string to be mapped :rtype: str """ text = self.__normalize(text) previousText = self.__normalize(self.conversation[sessionID][-2]...
Generate a response to the user input. :type text: str :param text: The string to be mapped :rtype: str
def read_igor_D_gene_parameters(params_file_name): """Load genD from file. genD is a list of genomic D information. Each element is a list of the name of the D allele and the germline sequence. Parameters ---------- params_file_name : str File name for a IGOR parameter file. R...
Load genD from file. genD is a list of genomic D information. Each element is a list of the name of the D allele and the germline sequence. Parameters ---------- params_file_name : str File name for a IGOR parameter file. Returns ------- genD : list List of genomic...
def _scaled_int(s): r"""Convert a 3 byte string to a signed integer value.""" s = bytearray(s) # For Python 2 # Get leftmost bit (sign) as 1 (if 0) or -1 (if 1) sign = 1 - ((s[0] & 0x80) >> 6) # Combine remaining bits int_val = (((s[0] & 0x7f) << 16) | (s[1] << 8) | s[2]) log.debug('Sourc...
r"""Convert a 3 byte string to a signed integer value.
def emit_java_headers(target, source, env): """Create and return lists of Java stub header files that will be created from a set of class files. """ class_suffix = env.get('JAVACLASSSUFFIX', '.class') classdir = env.get('JAVACLASSDIR') if not classdir: try: s = source[0] ...
Create and return lists of Java stub header files that will be created from a set of class files.
def use_astropy_helpers(**kwargs): """ Ensure that the `astropy_helpers` module is available and is importable. This supports automatic submodule initialization if astropy_helpers is included in a project as a git submodule, or will download it from PyPI if necessary. Parameters ---------- ...
Ensure that the `astropy_helpers` module is available and is importable. This supports automatic submodule initialization if astropy_helpers is included in a project as a git submodule, or will download it from PyPI if necessary. Parameters ---------- path : str or None, optional A fil...
def compare_values(values0, values1): """Compares all the values of a single registry key.""" values0 = {v[0]: v[1:] for v in values0} values1 = {v[0]: v[1:] for v in values1} created = [(k, v[0], v[1]) for k, v in values1.items() if k not in values0] deleted = [(k, v[0], v[1]) for k, v in values0....
Compares all the values of a single registry key.
def calculate_mvgd_stats(nw): """ MV Statistics for an arbitrary network Parameters ---------- nw: :any:`list` of NetworkDing0 The MV grid(s) to be studied Returns ------- mvgd_stats : pandas.DataFrame Dataframe containing several statistical numbers about the MVGD ...
MV Statistics for an arbitrary network Parameters ---------- nw: :any:`list` of NetworkDing0 The MV grid(s) to be studied Returns ------- mvgd_stats : pandas.DataFrame Dataframe containing several statistical numbers about the MVGD
def extract_atoms(molecule): """Return a string with all atoms in molecule""" if molecule == '': return molecule try: return float(molecule) except BaseException: pass atoms = '' if not molecule[0].isalpha(): i = 0 while not molecule[i].isalpha(): ...
Return a string with all atoms in molecule
def last_insert_id(self, cursor, table_name, pk_name): """ Given a cursor object that has just performed an INSERT statement into a table that has an auto-incrementing ID, returns the newly created ID. This method also receives the table name and the name of the primary-key colu...
Given a cursor object that has just performed an INSERT statement into a table that has an auto-incrementing ID, returns the newly created ID. This method also receives the table name and the name of the primary-key column.
def is_module_on_std_lib_path(cls, module): """ Sometimes .py files are symlinked to the real python files, such as the case of virtual env. However the .pyc files are created under the virtual env directory rather than the path in cls.STANDARD_LIB_PATH. Hence this function checks for both. :param ...
Sometimes .py files are symlinked to the real python files, such as the case of virtual env. However the .pyc files are created under the virtual env directory rather than the path in cls.STANDARD_LIB_PATH. Hence this function checks for both. :param module: a module :return: True if module is on inter...
def format_cert_name(env='', account='', region='', certificate=None): """Format the SSL certificate name into ARN for ELB. Args: env (str): Account environment name account (str): Account number for ARN region (str): AWS Region. certificate (str): Name of SSL certificate R...
Format the SSL certificate name into ARN for ELB. Args: env (str): Account environment name account (str): Account number for ARN region (str): AWS Region. certificate (str): Name of SSL certificate Returns: str: Fully qualified ARN for SSL certificate None: Cer...
def _annotate_validations(eval_files, data): """Add annotations about potential problem regions to validation VCFs. """ for key in ["tp", "tp-calls", "fp", "fn"]: if eval_files.get(key): eval_files[key] = annotation.add_genome_context(eval_files[key], data) return eval_files
Add annotations about potential problem regions to validation VCFs.
def sine(w, A=1, phi=0, offset=0): ''' Return a driver function that can advance a sequence of sine values. .. code-block:: none value = A * sin(w*i + phi) + offset Args: w (float) : a frequency for the sine driver A (float) : an amplitude for the sine driver phi (float) :...
Return a driver function that can advance a sequence of sine values. .. code-block:: none value = A * sin(w*i + phi) + offset Args: w (float) : a frequency for the sine driver A (float) : an amplitude for the sine driver phi (float) : a phase offset to start the sine driver wi...
def store_text_log_summary_artifact(job, text_log_summary_artifact): """ Store the contents of the text log summary artifact """ step_data = json.loads( text_log_summary_artifact['blob'])['step_data'] result_map = {v: k for (k, v) in TextLogStep.RESULTS} with transaction.atomic(): ...
Store the contents of the text log summary artifact
def change_attributes(self, bounds, radii, colors): """Reinitialize the buffers, to accomodate the new attributes. This is used to change the number of cylinders to be displayed. """ self.n_cylinders = len(bounds) self.is_empty = True if self.n_cylinders == 0 el...
Reinitialize the buffers, to accomodate the new attributes. This is used to change the number of cylinders to be displayed.
def buffer_read(library, session, count): """Reads data from device or interface through the use of a formatted I/O read buffer. Corresponds to viBufRead function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param...
Reads data from device or interface through the use of a formatted I/O read buffer. Corresponds to viBufRead function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param count: Number of bytes to be read. :return: ...
def strsettings(self, indent=0, maxindent=25, width=0): """Return user friendly help on positional arguments. indent is the number of spaces preceeding the text on each line. The indent of the documentation is dependent on the length of the longest label that is short...
Return user friendly help on positional arguments. indent is the number of spaces preceeding the text on each line. The indent of the documentation is dependent on the length of the longest label that is shorter than maxindent. A label longer than maxindent will be p...
def get(self, field_paths=None, transaction=None): """Retrieve a snapshot of the current document. See :meth:`~.firestore_v1beta1.client.Client.field_path` for more information on **field paths**. If a ``transaction`` is used and it already has write operations added, this meth...
Retrieve a snapshot of the current document. See :meth:`~.firestore_v1beta1.client.Client.field_path` for more information on **field paths**. If a ``transaction`` is used and it already has write operations added, this method cannot be used (i.e. read-after-write is not allowe...
def revise(csp, Xi, Xj, removals): "Return true if we remove a value." revised = False for x in csp.curr_domains[Xi][:]: # If Xi=x conflicts with Xj=y for every possible y, eliminate Xi=x if every(lambda y: not csp.constraints(Xi, x, Xj, y), csp.curr_domains[Xj]): ...
Return true if we remove a value.
def get_eventhub_info(self): """ Get details on the specified EventHub. Keys in the details dictionary include: -'name' -'type' -'created_at' -'partition_count' -'partition_ids' :rtype: dict """ alt_creds = { ...
Get details on the specified EventHub. Keys in the details dictionary include: -'name' -'type' -'created_at' -'partition_count' -'partition_ids' :rtype: dict