text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_plugin_actions(self):
"""Return a list of actions related to plugin"""
# ---- File menu and toolbar ----
self.new_action = create_action(
self,
_("&New file..."),
icon=ima.icon('filenew'), tip=_("New file"),
triggered... | 0.001866 |
def wind_shear(shear: str, unit_alt: str = 'ft', unit_wind: str = 'kt') -> str:
"""
Format wind shear string into a spoken word string
"""
unit_alt = SPOKEN_UNITS.get(unit_alt, unit_alt)
unit_wind = SPOKEN_UNITS.get(unit_wind, unit_wind)
return translate.wind_shear(shear, unit_alt, unit_wind, sp... | 0.00565 |
def get_SAM(self,min_intron_size=68):
"""Get a SAM object representation of the alignment.
:returns: SAM representation
:rtype: SAM
"""
from seqtools.format.sam import SAM
#ar is target then query
qname = self.alignment_ranges[0][1].chr
flag = 0
if self.strand == '-': flag = 16
... | 0.015531 |
def _append_record(test_data, results, test_path):
"""Adds data of single testcase results to results database."""
statuses = test_data.get("statuses")
jenkins_data = test_data.get("jenkins") or {}
data = [
("title", test_data.get("test_name") or _get_testname(test_path)),
("verdict", s... | 0.0022 |
def apply_network(network, x, chunksize=None):
"""
Apply a pytorch network, potentially in chunks
"""
network_is_cuda = next(network.parameters()).is_cuda
x = torch.from_numpy(x)
with torch.no_grad():
if network_is_cuda:
x = x.cuda()
if chunksize is None:
... | 0.002058 |
def wrap_existing_process(self, pid, stdout_read_fd, stderr_read_fd, port=None):
"""Do syncing, etc. for an already-running process.
This returns after the process has ended and syncing is done.
Captures ctrl-c's, signals, etc.
"""
stdout_read_file = os.fdopen(stdout_read_fd, 'r... | 0.002114 |
def trailing_stop_loss(self, accountID, **kwargs):
"""
Shortcut to create a Trailing Stop Loss Order in an Account
Args:
accountID : The ID of the Account
kwargs : The arguments to create a TrailingStopLossOrderRequest
Returns:
v20.response.Response ... | 0.003906 |
def importPeopleForm(self, request, tag):
"""
Create and return a L{liveform.LiveForm} for adding new L{Person}s.
"""
form = liveform.LiveForm(
self.importAddresses,
[liveform.Parameter('addresses', liveform.TEXTAREA_INPUT,
self._pa... | 0.003745 |
def where(self, custom_restrictions=[], **restrictions):
"""
Analog to SQL "WHERE". Does not perform a query until `select` is
called. Returns a repo object. Options selected through keyword
arguments are assumed to use == unles the value is a list, tuple, or
dictionary. List or ... | 0.001418 |
def randomize(self, rand_gen=None, *args, **kwargs):
"""
Randomize the model.
Make this draw from the prior if one exists, else draw from given random generator
:param rand_gen: np random number generator which takes args and kwargs
:param flaot loc: loc parameter for random number generator
:p... | 0.005456 |
def is_valid_url(url):
"""Checks if a given string is an url"""
from .misc import to_text
if not url:
return url
pieces = urllib_parse.urlparse(to_text(url))
return all([pieces.scheme, pieces.netloc]) | 0.004367 |
def from_file(file_path, incl_pot=True):
"""
Load catchment object from a ``.CD3`` or ``.xml`` file.
If there is also a corresponding ``.AM`` file (annual maximum flow data) or
a ``.PT`` file (peaks over threshold data) in the same folder as the CD3 file, these datasets will also be loaded.
:param... | 0.003012 |
def get_group_index(labels, shape, sort, xnull):
"""
For the particular label_list, gets the offsets into the hypothetical list
representing the totally ordered cartesian product of all possible label
combinations, *as long as* this space fits within int64 bounds;
otherwise, though group indices ide... | 0.000344 |
def list_upgrades(ruby=None,
runas=None,
gem_bin=None):
'''
.. versionadded:: 2015.8.0
Check if an upgrade is available for installed gems
gem_bin : None
Full path to ``gem`` binary to use.
ruby : None
If RVM or rbenv are installed, the ruby vers... | 0.001031 |
def attach(self, gui):
"""Attach the view to the GUI."""
super(WaveformView, self).attach(gui)
self.actions.add(self.toggle_waveform_overlap)
self.actions.add(self.toggle_show_labels)
self.actions.separator()
# Box scaling.
self.actions.add(self.widen)
se... | 0.001918 |
def score(self, X, design, scan_onsets=None):
""" After fit() is applied to the data of a group of participants,
use the parameters estimated by fit() function to evaluate
from some data of a set of participants to evaluate
the log likelihood of some new data of the same part... | 0.000423 |
def _parse_time(self, tokens):
"""
Parse the date range for the query
E.g. WHERE time > now() - 48h AND time < now() - 24h
would result in DateRange(datetime_start, datetime_end)
where
datetime_start would be parsed from now() - 48h
and
datetime_end would... | 0.006237 |
def _check_triple_quotes(self, quote_record):
"""Check if the triple quote from tokenization is valid.
Args:
quote_record: a tuple containing the info about the string
from tokenization, giving the (token, quote, row number, column).
"""
_, triple, row, col =... | 0.006522 |
def start(authkey, queues, mode='local'):
"""Create a new multiprocess.Manager (or return existing one).
Args:
:authkey: string authorization key
:queues: *INTERNAL_USE*
:mode: 'local' indicates that the manager will only be accessible from the same host, otherwise remotely accessible.
Returns:
... | 0.016988 |
def append_item(self, item):
"""
Add an item to the end of the menu before the exit item.
Args:
item (MenuItem): The item to be added.
"""
did_remove = self.remove_exit()
item.menu = self
self.items.append(item)
if did_remove:
sel... | 0.006024 |
def as_dataframe(self, time_index=False, absolute_time=False):
"""
Converts the TDMS file to a DataFrame
:param time_index: Whether to include a time index for the dataframe.
:param absolute_time: If time_index is true, whether the time index
values are absolute times or rel... | 0.002528 |
def _make_reversed_operation_costs(self):
"""
Заполняет массив _reversed_operation_costs
на основе имеющегося массива operation_costs
"""
_reversed_operation_costs = dict()
for up, costs in self.operation_costs.items():
for low, cost in costs.items():
... | 0.003617 |
def set_max_clients(limit):
"""Set the maximum number of simultaneous batch submission that can execute
in parallel.
:param int limit: The maximum number of simultaneous batch submissions
"""
global _dirty, _max_clients
LOGGER.debug('Setting maximum client limit to %i', limit)
_dirty = Tr... | 0.002882 |
def _perform_update(self, method, resource, payload):
'''
Execute the update task.
'''
# python2/3 compatibility wizardry
try:
file_type = file
except NameError:
file_type = IOBase
if isinstance(payload, (dict, list)):
respons... | 0.004376 |
def reset_clipboard(self):
""" Resets the clipboard, so that old elements do not pollute the new selection that is copied into the
clipboard.
:return:
"""
# reset selections
for state_element_attr in ContainerState.state_element_attrs:
self.model_copies[s... | 0.006024 |
def convert_column(data, schemae):
"""Convert known types from primitive to rich."""
ctype = schemae.converted_type
if ctype == parquet_thrift.ConvertedType.DECIMAL:
scale_factor = Decimal("10e-{}".format(schemae.scale))
if schemae.type == parquet_thrift.Type.INT32 or schemae.type == parquet... | 0.001647 |
def get_activity_admin_session(self, proxy):
"""Gets the ``OsidSession`` associated with the activity administration service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ActivityAdminSession) - an
``ActivityAdminSession``
raise: NullArgument - ``pro... | 0.004843 |
def firmware_version(self):
"""
Provides information on the connected Pebble, including its firmware version, language, capabilities, etc.
.. note:
This is a blocking call if :meth:`fetch_watch_info` has not yet been called, which could lead to deadlock
if called in an end... | 0.005362 |
def _get_answer(self, part):
"""
Note: Answers are only revealed after a correct submission. If you've
have not already solved the puzzle, AocdError will be raised.
"""
answer_fname = getattr(self, "answer_{}_fname".format(part))
if os.path.isfile(answer_fname):
... | 0.002734 |
def create_physical_relationship(manager, physical_handle_id, other_handle_id, rel_type):
"""
Makes relationship between the two nodes and returns the relationship.
If a relationship is not possible NoRelationshipPossible exception is
raised.
"""
other_meta_type = get_node_meta_type(manager, oth... | 0.006188 |
def Nicola(T, M, Tc, Pc, omega):
r'''Estimates the thermal conductivity of a liquid as a function of
temperature using the CSP method of [1]_. A statistically derived
equation using any correlated terms.
Requires temperature, molecular weight, critical temperature and pressure,
and acentric factor.... | 0.000651 |
def send(self, packet, retry=True):
"""send a packet down the line to the inteface"""
addr = ('255.255.255.255', self.port) # 255. is the broadcast IP for UDP
try:
self.send_socket.sendto(packet, addr)
except Exception as e:
self.log("Link failed to send packet o... | 0.006961 |
def get_pid_from_tid(self, dwThreadId):
"""
Retrieves the global ID of the process that owns the thread.
@type dwThreadId: int
@param dwThreadId: Thread global ID.
@rtype: int
@return: Process global ID.
@raise KeyError: The thread does not exist.
"""... | 0.001758 |
def bookmark(ctx):
"""Bookmark group.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon group bookmark
```
\b
```bash
$ polyaxon group -g 2 bookmark
```
"""
user, project_name, _group = get_project_group_or_local(ctx.obj.get('projec... | 0.004981 |
def get_decoder(cls, config: DecoderConfig, prefix: str) -> 'Decoder':
"""
Creates decoder based on config type.
:param config: Decoder config.
:param prefix: Prefix to prepend for decoder.
:return: Decoder instance.
"""
config_type = type(config)
if con... | 0.004637 |
def set_max_entries(self):
"""
Define the maximum of entries for computing the priority
of each items later.
"""
if self.cache:
self.max_entries = float(max([i[0] for i in self.cache.values()])) | 0.00813 |
def _determine_next_ott_id(self):
"""Read an initial value (int) from our stored counter (file)
Checks out master branch as a side effect!
"""
if self._doc_counter_lock is None:
self._doc_counter_lock = Lock()
with self._doc_counter_lock:
_LOG.debug('Read... | 0.006088 |
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
v... | 0.003795 |
def sendMessage(self, chat_id, text,
parse_mode=None,
disable_web_page_preview=None,
disable_notification=None,
reply_to_message_id=None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#sendmessag... | 0.016867 |
def process(self, input_data, topic=None):
"""
Invokes each handler in sequence.
Publishes final output data.
Params:
input_data: message received by stream
topic: name of plugin or stream message received from,
if applicable
... | 0.004184 |
def set_autostep(self, val):
"""Set autostep value (property)"""
if val is None:
# disabled by default for pdsh compat (+inf is 1E400, but a bug in
# python 2.4 makes it impossible to be pickled, so we use less)
# NOTE: Later, we could consider sys.maxint here
... | 0.004202 |
def weeks_of_year(cls, year):
"""Return an iterator over the weeks of the given year.
Years have either 52 or 53 weeks."""
w = cls(year, 1)
while w.year == year:
yield w
w += 1 | 0.008621 |
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op n... | 0.006356 |
def is_connection_dropped(conn): # Platform-specific
"""
Returns True if the connection is dropped and should be closed.
:param conn:
:class:`httplib.HTTPConnection` object.
Note: For platforms like AppEngine, this will always return ``False`` to
let the platform handle connection recycli... | 0.000958 |
def _to_pb(self):
"""Construct a KeyRange protobuf.
:rtype: :class:`~google.cloud.spanner_v1.proto.keys_pb2.KeyRange`
:returns: protobuf corresponding to this instance.
"""
kwargs = {}
if self.start_open is not None:
kwargs["start_open"] = _make_list_value_p... | 0.002801 |
def validate_length(low=None, high=None, equal=None):
"""
Validate the length of a field with either low, high, or equal.
Should work with anything that supports len().
:param low: Smallest length required.
:param high: Longest length required.
:param equal: Exact length required.
:raises: ... | 0.000894 |
def create_order_line_item(cls, order_line_item, **kwargs):
"""Create OrderLineItem
Create a new OrderLineItem
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_order_line_item(order_line... | 0.005336 |
def weigh_users(X_test, model, classifier_type="LinearSVC"):
"""
Uses a trained model and the unlabelled features to produce a user-to-label distance matrix.
Inputs: - feature_matrix: The graph based-features in either NumPy or SciPy sparse array format.
- model: A trained scikit-learn One-vs... | 0.00578 |
def get_protocol_sequence(self,sweep):
"""
given a sweep, return the protocol as condensed sequence.
This is better for comparing similarities and determining steps.
There should be no duplicate numbers.
"""
self.setsweep(sweep)
return list(self.protoSeqX),list(se... | 0.012012 |
def hit_groups(hits):
"""
* each sequence may have more than one 16S rRNA gene
* group hits for each gene
"""
groups = []
current = False
for hit in sorted(hits, key = itemgetter(0)):
if current is False:
current = [hit]
elif check_overlap(current, hit) is True or... | 0.007843 |
def _get_service(self, version='v3'):
'''get service client for the google drive API
:param version: version to use (default is v3)
'''
invalid = True
# The user hasn't disabled cache of credentials
if self._credential_cache is not None:
storage = Storage(sel... | 0.00536 |
def filter_time_range(self, start, end, regex=None):
"""Filter keys for all items within the desired time range.
Loops over all keys in the collection and uses `regex` to extract and build
`datetime`s. From the collection of `datetime`s, all values within `start` and `end`
(inclusive) a... | 0.007163 |
def _has_example(self, label):
"""Whether this data type has an example with the given ``label``."""
if label in self._raw_examples:
return True
else:
for field in self.all_fields:
dt, _ = unwrap_nullable(field.data_type)
if not is_user_def... | 0.003945 |
def run_spider(self, target_url, context_name=None, user_name=None):
"""Run spider against a URL."""
self.logger.debug('Spidering target {0}...'.format(target_url))
context_id, user_id = self._get_context_and_user_ids(context_name, user_name)
if user_id:
self.logger.debug('... | 0.005634 |
def get_float_relative(strings: Sequence[str],
prefix1: str,
delta: int,
prefix2: str,
ignoreleadingcolon: bool = False) -> Optional[float]:
"""
Fetches a float parameter via :func:`get_string_relative`.
"""
retu... | 0.002237 |
def newNode(name):
"""Create a new Node """
ret = libxml2mod.xmlNewNode(name)
if ret is None:raise treeError('xmlNewNode() failed')
return xmlNode(_obj=ret) | 0.017442 |
def list(self, order_id, **params):
"""
Retrieve order's line items
Returns all line items associated to order
:calls: ``get /orders/{order_id}/line_items``
:param int order_id: Unique identifier of a Order.
:param dict params: (optional) Search options.
:return... | 0.006645 |
def apply_config(self, config):
"""
Constructs HAProxyConfig and HAProxyControl instances based on the
contents of the config.
This is mostly a matter of constructing the configuration stanzas.
"""
self.haproxy_config_path = config["config_file"]
global_stanza =... | 0.001054 |
def split_bel_stmt(stmt: str, line_num) -> tuple:
"""Split bel statement into subject, relation, object tuple"""
m = re.match(f"^(.*?\))\s+([a-zA-Z=\->\|:]+)\s+([\w(]+.*?)$", stmt, flags=0)
if m:
return (m.group(1), m.group(2), m.group(3))
else:
log.info(
f"Could not parse b... | 0.020548 |
def _modify(self, **patch):
"""Override modify to check kwargs before request sent to device."""
if 'state' in patch:
if patch['state'] not in ['user-up', 'user-down', 'unchecked', 'fqdn-up']:
msg = "The node resource does not support a modify with the " \
... | 0.003865 |
def belongsToModule(obj, module):
"""Returns True is an object belongs to a module."""
return obj.__module__ == module.__name__ or obj.__module__.startswith(
module.__name__) | 0.009901 |
def cfn_viz(template, parameters={}, outputs={}, out=sys.stdout):
"""Render dot output for cloudformation.template in json format.
"""
known_sg, open_sg = _analyze_sg(template['Resources'])
(graph, edges) = _extract_graph(template.get('Description', ''),
template['Res... | 0.00161 |
def from_proto_dict(proto_dict: Dict) -> 'GridQubit':
"""Proto dict must have 'row' and 'col' keys."""
if 'row' not in proto_dict or 'col' not in proto_dict:
raise ValueError(
'Proto dict does not contain row or col: {}'.format(proto_dict))
return GridQubit(row=proto_... | 0.008451 |
def parse_public(data):
"""
Loads a public key from a DER or PEM-formatted file. Supports RSA, DSA and
EC public keys. For RSA keys, both the old RSAPublicKey and
SubjectPublicKeyInfo structures are supported. Also allows extracting a
public key from an X.509 certificate.
:param data:
A... | 0.001242 |
def create_or_update_user(self, username, policies=None, groups=None, mount_point=DEFAULT_MOUNT_POINT):
"""
Create or update LDAP users policies and group associations.
Supported methods:
POST: /auth/{mount_point}/users/{username}. Produces: 204 (empty body)
:param usernam... | 0.003486 |
def get_design_matrix(self, names=None, format='long', mode='both',
force=False, sampling_rate='TR', **kwargs):
''' Get design matrix and associated information.
Args:
names (list): Optional list of names of variables to include in the
returned desi... | 0.001571 |
def load_molecule(name, format=None):
'''Read a `~chemlab.core.Molecule` from a file.
.. seealso:: `chemlab.io.datafile`
'''
mol = datafile(name, format=format).read('molecule')
display_system(System([mol])) | 0.012658 |
def match(self, ref):
""" Get all concepts matching this ref. For a dimension, that is all
its attributes, but not the dimension itself. """
try:
concept = self[ref]
if not isinstance(concept, Dimension):
return [concept]
return [a for a in con... | 0.005222 |
def read_pdb(pdbfname, as_string=False):
"""Reads a given PDB file and returns a Pybel Molecule."""
pybel.ob.obErrorLog.StopLogging() # Suppress all OpenBabel warnings
if os.name != 'nt': # Resource module not available for Windows
maxsize = resource.getrlimit(resource.RLIMIT_STACK)[-1]
re... | 0.003891 |
def QA_util_get_trade_range(start, end):
'给出交易具体时间'
start, end = QA_util_get_real_datelist(start, end)
if start is not None:
return trade_date_sse[trade_date_sse
.index(start):trade_date_sse.index(end) + 1:1]
else:
return None | 0.003472 |
def reduce_object_file_names(self, dirn):
"""Recursively renames all files named XXX.cpython-...-linux-gnu.so"
to "XXX.so", i.e. removing the erroneous architecture name
coming from the local system.
"""
py_so_files = shprint(sh.find, dirn, '-iname', '*.so')
filens = py_s... | 0.0032 |
def read_stats(self):
""" Read current ports statistics from chassis.
:return: dictionary {port name {group name, {stat name: stat value}}}
"""
self.statistics = TgnObjectsDict()
for port in self.session.ports.values():
self.statistics[port] = port.read_port_stats()... | 0.005698 |
def rfcformat(dt, localtime=False):
"""Return the RFC822-formatted representation of a datetime object.
:param datetime dt: The datetime.
:param bool localtime: If ``True``, return the date relative to the local
timezone instead of UTC, displaying the proper offset,
e.g. "Sun, 10 Nov 2013 0... | 0.002165 |
def bitswap_wantlist(self, peer=None, **kwargs):
"""Returns blocks currently on the bitswap wantlist.
.. code-block:: python
>>> c.bitswap_wantlist()
{'Keys': [
'QmeV6C6XVt1wf7V7as7Yak3mxPma8jzpqyhtRtCvpKcfBb',
'QmdCWFLDXqgdWQY9kVubbEHBbkieKd3uo7... | 0.002685 |
def output_best_scores(self, best_epoch_str: str) -> None:
"""Output best scores to the filesystem"""
BEST_SCORES_FILENAME = "best_scores.txt"
with open(os.path.join(self.exp_dir, BEST_SCORES_FILENAME),
"w", encoding=ENCODING) as best_f:
print(best_epoch_str, file=b... | 0.005917 |
def get_namespace(self, uri):
"""Return a :class:`.Namespace` corresponding to the given ``uri``.
If the given ``uri`` is a relative URI (i.e. it does not
contain a leading slash ``/``), the ``uri`` is adjusted to
be relative to the ``uri`` of the namespace itself. This
method i... | 0.00313 |
def _compute(self, arrays, dates, assets, mask):
"""
For each row in the input, compute a like-shaped array of per-row
ranks.
"""
return masked_rankdata_2d(
arrays[0],
mask,
self.inputs[0].missing_value,
self._method,
se... | 0.005814 |
def add_cmd_method(self, name, method, argc=None, complete=None):
"""Adds a command to the command line interface loop.
Parameters
----------
name : string
The command.
method : function(args)
The function to execute when this command is issued. The argu... | 0.001596 |
def final_bearing(self, format='numeric'):
"""Calculate final bearing between locations in segments.
Args:
format (str): Format of the bearing string to return
Returns:
list of list of float: Groups of bearings between points in
segments
"""
... | 0.003704 |
def play_state(self):
"""Play state, e.g. playing or paused."""
# TODO: extract to a convert module
state = self._setstate.playbackState
if state == 1:
return const.PLAY_STATE_PLAYING
if state == 2:
return const.PLAY_STATE_PAUSED
return const.PLAY... | 0.006006 |
def get_client(self, request=None):
"""Return the client from the OAuth parameters."""
if not isinstance(request, oauth.Request):
request = self.get_oauth_request()
client_key = request.get_parameter('oauth_consumer_key')
if not client_key:
raise Exception('Missi... | 0.006885 |
def get_response(self, assessment_section_id, item_id):
"""Gets the submitted response to the associated item.
arg: assessment_section_id (osid.id.Id): ``Id`` of the
``AssessmentSection``
arg: item_id (osid.id.Id): ``Id`` of the ``Item``
return: (osid.assessment.Re... | 0.002967 |
def get_rating_metadata(self):
"""Gets the metadata for a rating.
return: (osid.Metadata) - metadata for the rating
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceForm.get_group_metadata_template
met... | 0.006452 |
def p_compilerDirective(p):
"""compilerDirective : '#' PRAGMA pragmaName '(' pragmaParameter ')'"""
directive = p[3].lower()
param = p[5]
if directive == 'include':
fname = param
if p.parser.file:
if os.path.dirname(p.parser.file):
fname = os.path.join(os.path... | 0.001499 |
def service_confirmation(self, bslpdu):
"""Receive packets forwarded by the proxy and send them upstream to the network service access point."""
if _debug: ProxyServiceNetworkAdapter._debug("service_confirmation %r", bslpdu)
# build a PDU
pdu = NPDU(bslpdu.pduData)
# the source... | 0.007277 |
def _add_tasks_to_taskpaper(
self,
pathToTaskpaperDoc,
taskString
):
"""*add the tasks to a taskpaper document*
**Key Arguments:**
- ``pathToTaskpaperDoc`` -- the path to the taskpaper document to import the tasks into
- ``taskString`` -- a string con... | 0.002166 |
def calculate_partial_digest(username, realm, password):
'''
Calculate a partial digest that may be stored and used to authenticate future
HTTP Digest sessions.
'''
return md5.md5("%s:%s:%s" % (username.encode('utf-8'), realm, password.encode('utf-8'))).hexdigest() | 0.010526 |
def create_table_service(self):
'''
Creates a TableService object with the settings specified in the
CloudStorageAccount.
:return: A service object.
:rtype: :class:`~azure.storage.table.tableservice.TableService`
'''
try:
from ..table.tableservice im... | 0.005548 |
def remove_option(self, section, option):
"""Remove an option."""
if not section or section == self.default_section:
sectdict = self._defaults
else:
try:
sectdict = self._sections[section]
except KeyError:
raise from_none(NoSect... | 0.004057 |
def write_to(self, out):
""" Write the raw header content to the out stream
Parameters:
----------
out : {file object}
The output stream
"""
out.write(bytes(self.header))
out.write(self.record_data) | 0.007463 |
def get_same_container_repos_from_spec(app_or_library_spec):
"""Given the spec of an app or library, returns all repos that are guaranteed
to live in the same container"""
repos = set()
app_or_lib_repo = get_repo_of_app_or_library(app_or_library_spec.name)
if app_or_lib_repo is not None:
rep... | 0.004098 |
def to_dict(self):
"""
Serializes a definition to a dictionary, ready for json.
Children are serialised recursively.
"""
ddict = {'name': self.name, 'icon': self.icon,
'line': self.line, 'column': self.column,
'children': [], 'description': self... | 0.003891 |
def serialize(self):
"""Returns serialized chunk data in dictionary."""
return {
'word': self.word,
'pos': self.pos,
'label': self.label,
'dependency': self.dependency,
'has_cjk': self.has_cjk(),
} | 0.004016 |
def _input_pins(self, pins):
"""Read multiple pins specified in the given list and return list of pin values
GPIO.HIGH/True if the pin is pulled high, or GPIO.LOW/False if pulled low.
"""
[self._validate_channel(pin) for pin in pins]
# Get GPIO state.
gpio = self.i2c.read... | 0.010593 |
def pbs(ac1, ac2, ac3, window_size, window_start=0, window_stop=None,
window_step=None, normed=True):
"""Compute the population branching statistic (PBS) which performs a comparison
of allele frequencies between three populations to detect genome regions that are
unusually differentiated in one popu... | 0.00318 |
def enable(states):
'''
Enable state function or sls run
CLI Example:
.. code-block:: bash
salt '*' state.enable highstate
salt '*' state.enable test.succeed_without_changes
.. note::
To enable a state file from running provide the same name that would
be passed ... | 0.00082 |
def _set_setting(self, settings):
"""Validate the settings and then send the PATCH request."""
for key, value in settings.items():
_validate_setting(key, value)
try:
self._settings_request(method="patch", json_data=settings)
self.update(settings_json=setting... | 0.004274 |
def send_status_response(environ, start_response, e, add_headers=None, is_head=False):
"""Start a WSGI response for a DAVError or status code."""
status = get_http_status_string(e)
headers = []
if add_headers:
headers.extend(add_headers)
# if 'keep-alive' in environ.get('HTTP_CONNECTION',... | 0.002566 |
def sync(self):
"""
synchronize self from Ariane server according its id (prioritary) or name
:return:
"""
LOGGER.debug("Location.sync")
params = None
if self.id is not None:
params = {'id': self.id}
elif self.name is not None:
para... | 0.00355 |
def in_collision_other(self, other_manager,
return_names=False, return_data=False):
"""
Check if any object from this manager collides with any object
from another manager.
Parameters
-------------------
other_manager : CollisionManager
... | 0.001167 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.