text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def has(self, id, domain):
"""
Checks if a message has a translation.
@rtype: bool
@return: true if the message has a translation, false otherwise
"""
assert isinstance(id, (str, unicode))
assert isinstance(domain, (str, unicode))
if self.defines(id, dom... | 0.004175 |
def to_representation(self, instance):
"""
Return the updated course data dictionary.
Arguments:
instance (dict): The course data.
Returns:
dict: The updated course data.
"""
updated_course = copy.deepcopy(instance)
enterprise_customer_ca... | 0.006667 |
def _update(self, response_headers):
"""
Update the state of the rate limiter based on the response headers:
X-Ratelimit-Used: Approximate number of requests used this period
X-Ratelimit-Remaining: Approximate number of requests left to use
X-Ratelimit-Reset: Approxi... | 0.001149 |
def get_resources(self, types=None, names=None, languages=None):
"""
Get resources.
types = a list of resource types to search for (None = all)
names = a list of resource names to search for (None = all)
languages = a list of resource languages to search for (None = all)... | 0.009107 |
def process_arguments(self, func, args):
"""Process arguments from the command line into positional and kw args.
Arguments are consumed until the argument spec for the function is filled
or a -- is found or there are no more arguments. Keyword arguments can be
specified using --field=v... | 0.005979 |
def noise3d(self, x, y, z):
"""
Generate 3D OpenSimplex noise from X,Y,Z coordinates.
"""
# Place input coordinates on simplectic honeycomb.
stretch_offset = (x + y + z) * STRETCH_CONSTANT_3D
xs = x + stretch_offset
ys = y + stretch_offset
zs = z + stretch... | 0.002448 |
def list_all_customers(cls, **kwargs):
"""List Customers
Return a list of Customers
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_customers(async=True)
>>> result = thread.g... | 0.002323 |
def resnet_main(seed, flags, model_function, input_function, shape=None):
"""Shared main loop for ResNet Models.
Args:
flags: FLAGS object that contains the params for running. See
ResnetArgParser for created flags.
model_function: the function that instantiates the Model and builds the
ops for... | 0.007122 |
def status(self, obj):
"""Get the wifi interface status."""
data_size = DWORD()
data = PDWORD()
opcode_value_type = DWORD()
self._wlan_query_interface(self._handle, obj['guid'], 6,
byref(data_size), byref(data),
... | 0.005038 |
def _filter_contains(self, term, field_name, field_type, is_not):
"""
Splits the sentence in terms and join them with OR,
using stemmed and un-stemmed.
Assumes term is not a list.
"""
if field_type == 'text':
term_list = term.split()
else:
... | 0.005484 |
def p_action(p):
"""
action : CLIENT_KWD KEY DOT KEY LPAREN args RPAREN
action : SERVER_KWD KEY DOT KEY LPAREN args RPAREN
action : CLIENT_KWD KEY DOT KEY LPAREN args RPAREN IF_KWD REGEX_MATCH_INCOMING_KWD LPAREN p_string_arg RPAREN
action : SERVER_KWD KEY DOT KEY LPAREN args RPAREN IF_KWD REGEX_MAT... | 0.00996 |
def _recv_sf(self, data):
"""Process a received 'Single Frame' frame"""
self.rx_timer.cancel()
if self.rx_state != ISOTP_IDLE:
warning("RX state was reset because single frame was received")
self.rx_state = ISOTP_IDLE
length = six.indexbytes(data, 0) & 0xf
... | 0.003731 |
def commands(self):
"""
Returns a list of commands that are supported by the motor
controller. Possible values are `run-forever`, `run-to-abs-pos`, `run-to-rel-pos`,
`run-timed`, `run-direct`, `stop` and `reset`. Not all commands may be supported.
- `run-forever` will cause the ... | 0.009548 |
def to_native_types(self, slicer=None, na_rep=None, date_format=None,
quoting=None, **kwargs):
""" convert to our native types format, slicing if desired """
values = self.values
i8values = self.values.view('i8')
if slicer is not None:
values = value... | 0.004005 |
def _rpc(http, project, method, base_url, request_pb, response_pb_cls):
"""Make a protobuf RPC request.
:type http: :class:`requests.Session`
:param http: HTTP object to make requests.
:type project: str
:param project: The project to connect to. This is
usually your project na... | 0.000878 |
def clean(self, *args, **kwargs):
"""Clean all loaded values to reload when switching envs"""
for key in list(self.store.keys()):
self.unset(key) | 0.011561 |
def connect(self):
''' instantiate objects / parse config file '''
# open config file for parsing
try:
settings = configparser.ConfigParser()
settings._interpolation = configparser.ExtendedInterpolation()
except Exception as err:
self.logger.error("Fai... | 0.003546 |
def merge(profile, branch, merge_into):
"""Merge a branch into another branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
... | 0.001698 |
def symlink_list(self, load):
'''
Return a dict of all symlinks based on a given path in the repo
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
if not salt.utils.stringutils.is_hex(load['saltenv']) \
and lo... | 0.00292 |
def Zuo_Stenby(T, Tc, Pc, omega):
r'''Calculates air-water surface tension using the reference fluids
methods of [1]_.
.. math::
\sigma^{(1)} = 40.520(1-T_r)^{1.287}
\sigma^{(2)} = 52.095(1-T_r)^{1.21548}
\sigma_r = \sigma_r^{(1)}+ \frac{\omega - \omega^{(1)}}
{\omega^{(2)}-... | 0.000517 |
def _normalize_check_url(self, check_url):
"""
Normalizes check_url by:
* Adding the `http` scheme if missing
* Adding or replacing port with `self.port`
"""
# TODO: Write tests for this method
split_url = urlsplit(check_url)
host = splitport(split_url.p... | 0.004819 |
def _increase_gc_sockets():
"""Increase default sockets for zmq gc. Avoids scaling issues.
https://github.com/zeromq/pyzmq/issues/471
"""
ctx = zmq.Context()
ctx.max_sockets = MAX_SOCKETS
gc.context = ctx | 0.004386 |
def service_list(profile=None, **connection_args):
'''
Return a list of available services (keystone services-list)
CLI Example:
.. code-block:: bash
salt '*' keystone.service_list
'''
kstone = auth(profile, **connection_args)
ret = {}
for service in kstone.services.list():
... | 0.005068 |
def configure_once(config=None, bind_in_runtime=True):
"""Create an injector with a callable config if not present, otherwise, do nothing."""
with _INJECTOR_LOCK:
if _INJECTOR:
return _INJECTOR
return configure(config, bind_in_runtime=bind_in_runtime) | 0.006944 |
def cltext(fname):
"""
Internal undocumented command for closing a text file opened by RDTEXT.
No URL available; relevant lines from SPICE source:
FORTRAN SPICE, rdtext.f::
C$Procedure CLTEXT ( Close a text file opened by RDTEXT)
ENTRY CLTEXT ( FILE )
CHARACTER*(... | 0.002307 |
def from_api_repr(cls, resource):
"""Factory: construct a model reference given its API representation
Args:
resource (Dict[str, object]):
Model reference representation returned from the API
Returns:
google.cloud.bigquery.model.ModelReference:
... | 0.004024 |
def _GetFormatErrorLocation(
self, yaml_definition, last_definition_object):
"""Retrieves a format error location.
Args:
yaml_definition (dict[str, object]): current YAML definition.
last_definition_object (DataTypeDefinition): previous data type
definition.
Returns:
str:... | 0.006144 |
def sport_update(self, sport_id, names=[], account=None, **kwargs):
""" Update a sport. This needs to be **proposed**.
:param str sport_id: The id of the sport to update
:param list names: Internationalized names, e.g. ``[['de', 'Foo'],
['en', 'bar']]``
:para... | 0.001843 |
def kill_job(self, job_id):
"""
Kills a running job
"""
self._loop.call_soon_threadsafe(asyncio.ensure_future, self._simple_send(ClientKillJob(job_id))) | 0.016304 |
def transform(self, X):
"""
Args:
X: DataFrame with NaN's
Returns:
Dictionary with one key - 'X' corresponding to given DataFrame but without nan's
"""
if self.fill_missing:
X = self.filler.complete(X)
return {'X': X} | 0.009934 |
def solve_limited(self, assumptions=[]):
"""
Solve internal formula using given budgets for conflicts and
propagations.
"""
if self.minisat:
if self.use_timer:
start_time = time.clock()
# saving default SIGINT handler
... | 0.007762 |
def tzinfo_eq(tzinfo1, tzinfo2, startYear = 2000, endYear=2020):
"""
Compare offsets and DST transitions from startYear to endYear.
"""
if tzinfo1 == tzinfo2:
return True
elif tzinfo1 is None or tzinfo2 is None:
return False
def dt_test(dt):
if dt is None:
re... | 0.006502 |
def weighted_mean(X, embedding, neighbors, distances):
"""Initialize points onto an existing embedding by placing them in the
weighted mean position of their nearest neighbors on the reference embedding.
Parameters
----------
X: np.ndarray
embedding: TSNEEmbedding
neighbors: np.ndarray
... | 0.002869 |
def prompt_choice_list(msg, a_list, default=1, help_string=None):
"""Prompt user to select from a list of possible choices.
:param msg:A message displayed to the user before the choice list
:type msg: str
:param a_list:The list of choices (list of strings or list of dicts with 'name' & 'desc')
"typ... | 0.00406 |
def ifftr(wave, npoints=None, indep_min=None, indep_max=None):
r"""
Return the real part of the inverse Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
... | 0.000675 |
def assert_equivalent(o1, o2):
'''Asserts that o1 and o2 are distinct, yet equivalent objects
'''
if not (isinstance(o1, type) and isinstance(o2, type)):
assert o1 is not o2
assert o1 == o2
assert o2 == o1 | 0.004292 |
def get_short_lambda_body_text(lambda_func):
"""Return the source of a (short) lambda function.
If it's impossible to obtain, returns None.
"""
try:
source_lines, _ = inspect.getsourcelines(lambda_func)
except (IOError, TypeError):
return None
# skip `def`-ed functions and long ... | 0.00037 |
def _iter_ns_range(self):
"""Iterates over self._ns_range, delegating to self._iter_key_range()."""
while True:
if self._current_key_range is None:
query = self._ns_range.make_datastore_query()
namespace_result = query.Get(1)
if not namespace_result:
break
namesp... | 0.008612 |
def make_interval(long_name, short_name):
""" Create an interval segment """
return Group(
Regex("(-+)?[0-9]+")
+ (
upkey(long_name + "s")
| Regex(long_name + "s").setParseAction(upcaseTokens)
| upkey(long_name)
| Regex(long_name).setParseAction(up... | 0.002146 |
def generate_bqm(graph, table, decision_variables,
linear_energy_ranges=None, quadratic_energy_ranges=None, min_classical_gap=2):
"""
Args:
graph: A networkx.Graph
table: An iterable of valid spin configurations. Each configuration is a tuple of
variable assignments ... | 0.005137 |
def get_descriptor_for_layer(self, layer):
"""
Returns the standard JSON descriptor for the layer. There is a lot of
usefule information in there.
"""
if not layer in self._layer_descriptor_cache:
params = {'f': 'pjson'}
if self.token:
para... | 0.005556 |
def from_scaledproto(cls, scaledproto_mesh,
pos, vel, euler, euler_vel,
rotation_vel=(0,0,0),
component_com_x=None):
"""
TODO: add documentation
"""
mesh = cls(**scaledproto_mesh.items())
# roche coordin... | 0.015564 |
def url(self, filetype, base_dir=None, sasdir='sas', **kwargs):
"""Return the url of a given type of file.
Parameters
----------
filetype : str
File type parameter.
Returns
-------
full : str
The sas url to the file.
"""
... | 0.006479 |
def clip_geometry_to_srs_bounds(geometry, pyramid, multipart=False):
"""
Clip input geometry to SRS bounds of given TilePyramid.
If geometry passes the antimeridian, it will be split up in a multipart
geometry and shifted to within the SRS boundaries.
Note: geometry SRS must be the TilePyramid SRS!... | 0.000607 |
def is_readable(path):
'''
Returns True if provided file or directory exists and can be read with the current user.
Returns False otherwise.
'''
return os.access(os.path.abspath(path), os.R_OK) | 0.00939 |
def base10_integer_to_basek_string(k, x):
"""Convert an integer into a base k string."""
if not (2 <= k <= max_k_labeled):
raise ValueError("k must be in range [2, %d]: %s"
% (max_k_labeled, k))
return ((x == 0) and numerals[0]) or \
(base10_integer_to_basek_string(k... | 0.005277 |
def OS_filter(x,h,N,mode=0):
"""
Overlap and save transform domain FIR filtering.
This function implements the classical overlap and save method of
transform domain filtering using a length P FIR filter.
Parameters
----------
x : input signal to be filtered as an ndarray
h : FI... | 0.010204 |
def get_port_channel_detail_output_lacp_ready_agg(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_channel_detail = ET.Element("get_port_channel_detail")
config = get_port_channel_detail
output = ET.SubElement(get_port_channel_detail, "ou... | 0.003546 |
def send_email(to, subject, html_content,
files=None, dryrun=False, cc=None, bcc=None,
mime_subtype='mixed', mime_charset='utf-8', **kwargs):
"""
Send email using backend specified in EMAIL_BACKEND.
"""
path, attr = configuration.conf.get('email', 'EMAIL_BACKEND').rsplit('.... | 0.004573 |
def _updateModelDBResults(self):
""" Retrieves the current results and updates the model's record in
the Model database.
"""
# -----------------------------------------------------------------------
# Get metrics
metrics = self._getMetrics()
# ----------------------------------------------... | 0.005579 |
def dn_cn_of_certificate_with_san(domain):
'''Return the Common Name (cn) from the Distinguished Name (dn) of the
certificate which contains the `domain` in its Subject Alternativ Name (san)
list.
Needs repo ~/.fabsetup-custom.
Return None if no certificate is configured with `domain` in SAN.
... | 0.002614 |
def authenticate_direct_bind(self, username, password):
"""
Performs a direct bind. We can do this since the RDN is the same
as the login attribute. Hence we just string together a dn to find
this user with.
Args:
username (str): Username of the user to bind (the fie... | 0.002046 |
def _mkstemp_copy(path,
preserve_inode=True):
'''
Create a temp file and move/copy the contents of ``path`` to the temp file.
Return the path to the temp file.
path
The full path to the file whose contents will be moved/copied to a temp file.
Whether it's moved or copi... | 0.004204 |
def create(self, size, number, meta, name=None, image=None, attempts=3):
"""Create container VM nodes. Uses a container declaration which is undocumented.
:param size: The machine type to use.
:type size: ``str`` or :class:`GCENodeSize`
:param number: Amount of nodes to be spawn... | 0.003988 |
def validate_json_request(required_fields):
"""
Return a decorator that ensures that the request passed to the view
function/method has a valid JSON request body with the given required
fields. The dict parsed from the JSON is then passed as the second
argument to the decorated function/method. Fo... | 0.000965 |
def add_verified_read(self):
"""Add ``read`` perm for all verified subj.
Public ``read`` is removed if present.
"""
self.remove_perm(d1_common.const.SUBJECT_PUBLIC, 'read')
self.add_perm(d1_common.const.SUBJECT_VERIFIED, 'read') | 0.007407 |
def _get_heading_level(self, element):
"""
Returns the level of heading.
:param element: The heading.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
:return: The level of heading.
:rtype: int
"""
# pylint: disable=no-self-use
tag... | 0.00311 |
def clean_json(resource_json, resources_map):
"""
Cleanup the a resource dict. For now, this just means replacing any Ref node
with the corresponding physical_resource_id.
Eventually, this is where we would add things like function parsing (fn::)
"""
if isinstance(resource_json, dict):
... | 0.00346 |
def _CopyToDateTimeString(self):
"""Copies the POSIX timestamp to a date and time string.
Returns:
str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#########" or
None if the timestamp is missing or invalid.
"""
if self._timestamp is None:
return None
timestamp, nan... | 0.002751 |
def _new_report(self,
type,
start_date,
end_date,
product_id='BTC-USD',
account_id=None,
format=None,
email=None):
"""`<https://docs.exchange.coinbase.com/#create-a-new-report>`_"""
data... | 0.024917 |
def get_lib(self, arch='x86'):
"""
Get lib directories of Visual C++.
"""
if arch == 'x86':
arch = ''
if arch == 'x64':
arch = 'amd64'
lib = os.path.join(self.vc_dir, 'lib', arch)
if os.path.isdir(lib):
logging.info(_('using lib... | 0.004695 |
def sd2df_CSV(self, table: str, libref: str = '', dsopts: dict = None, tempfile: str = None, tempkeep: bool = False,
**kwargs) -> 'pd.DataFrame':
"""
This is an alias for 'sasdata2dataframe' specifying method='CSV'. Why type all that?
SASdata object that refers to the Sas Data ... | 0.006917 |
def counter(self, ch, part=None):
"""Return a counter on the channel ch.
ch: string or integer.
The channel index number or channel name.
part: int or None
The 0-based enumeration of a True part to return. This
has an effect whether or not the mask or filter... | 0.003317 |
def write_config_json(config_file, data):
"""Serializes an object to disk.
Args:
config_file (str): The path on disk to save the file.
data (object): The object to serialize.
"""
outfile = None
try:
with open(config_file, 'w') as outfile:
json.dump(data, outfile... | 0.004071 |
def validate_properties(self, model, context=None):
"""
Validate simple properties
Performs validation on simple properties to return a result object.
:param model: object or dict
:param context: object, dict or None
:return: shiftschema.result.Result
"""
... | 0.002475 |
def response(self, in_thread: Optional[bool] = None) -> "Message":
"""
Create a response message.
Depending on the incoming message the response can be in a thread. By default the response follow where the
incoming message was posted.
Args:
in_thread (boolean): Over... | 0.002879 |
def check_bcr_catchup(self):
"""we're exceeding data request speed vs receive + process"""
logger.debug(f"Checking if BlockRequests has caught up {len(BC.Default().BlockRequests)}")
# test, perhaps there's some race condition between slow startup and throttle sync, otherwise blocks will never g... | 0.003432 |
def plugin_request(plugin_str):
'''
Extract plugin name and version specifiers from plugin descriptor string.
.. versionchanged:: 0.25.2
Import from `pip_helpers` locally to avoid error `sci-bots/mpm#5`_.
.. _sci-bots/mpm#5: https://github.com/sci-bots/mpm/issues/5
'''
from pip_hel... | 0.00177 |
async def refresh_token(self, refresh_token):
"""
:param refresh_token: an openid refresh-token from a previous token request
"""
async with self._client_session() as client:
well_known = await self._get_well_known(client)
try:
return await self._... | 0.004161 |
def parse_requirement(self, node):
"""
Parses <Requirement>
@param node: Node containing the <Requirement> element
@type node: xml.etree.Element
"""
if 'name' in node.lattrib:
name = node.lattrib['name']
else:
self.raise_error('<Requireme... | 0.00813 |
def rl_set_prompt(prompt: str) -> None: # pragma: no cover
"""
Sets readline's prompt
:param prompt: the new prompt value
"""
safe_prompt = rl_make_safe_prompt(prompt)
if rl_type == RlType.GNU:
encoded_prompt = bytes(safe_prompt, encoding='utf-8')
readline_lib.rl_set_prompt(enc... | 0.002398 |
def get_default_locale_callable():
"""
Wrapper function so that the default mapping is only built when needed
"""
exec_dir = os.path.dirname(os.path.realpath(__file__))
xml_path = os.path.join(exec_dir, 'data', 'FacebookLocales.xml')
fb_locales = _build_locale_table(xml_path)
def default_l... | 0.000909 |
def find_build_map(stack_builders):
"""
Find the BUILD_MAP instruction for which the last element of
``stack_builders`` is a store.
"""
assert isinstance(stack_builders[-1], instrs.STORE_MAP)
to_consume = 0
for instr in reversed(stack_builders):
if isinstance(instr, instrs.STORE_MAP... | 0.001414 |
def deliver_hook(instance, target, payload_override=None):
"""
Deliver the payload to the target URL.
By default it serializes to JSON and POSTs.
"""
payload = payload_override or serialize_hook(instance)
if hasattr(settings, 'HOOK_DELIVERER'):
deliverer = get_module(settings.HOOK_DELIV... | 0.001678 |
def __calculate_current_value(self, asset_class: AssetClass):
""" Calculate totals for asset class by adding all the children values """
# Is this the final asset class, the one with stocks?
if asset_class.stocks:
# add all the stocks
stocks_sum = Decimal(0)
f... | 0.004027 |
def result(retn):
'''
Return a value or raise an exception from a retn tuple.
'''
ok, valu = retn
if ok:
return valu
name, info = valu
ctor = getattr(s_exc, name, None)
if ctor is not None:
raise ctor(**info)
info['errx'] = name
raise s_exc.SynErr(**info) | 0.003175 |
def _read_attr(attr_name):
"""
Parse attribute from file 'pefile.py' and avoid importing
this module directly.
__version__, __author__, __contact__,
"""
regex = attr_name + r"\s+=\s+'(.+)'"
if sys.version_info.major == 2:
with open('pefile.py', 'r') as f:
match = re.sear... | 0.001852 |
def getRect(self):
"""
Returns the window bounds as a tuple of (x,y,w,h)
"""
return (self.x, self.y, self.w, self.h) | 0.048387 |
def parse_options(arguments):
"""Parse command line arguments.
The parsing logic is fairly simple. It can only parse long-style
parameters of the form::
--key value
Several parameters can be defined in the environment and will be used
unless explicitly overridden with command-line argument... | 0.000469 |
def _load(self, file_parser, section_name):
"""The current element is loaded from the configuration file,
all constraints and requirements are checked.
"""
# pylint: disable-msg=W0621
log = logging.getLogger('argtoolbox')
try:
log.debug("looking for field (sec... | 0.001403 |
def load(name):
"""
Loads the font specified by name and returns it as an instance of
`PIL.ImageFont <http://pillow.readthedocs.io/en/latest/reference/ImageFont.html>`_
class.
"""
try:
font_dir = os.path.dirname(__file__)
pil_file = os.path.join(font_dir, '{}.pil'.format(name))
... | 0.005042 |
def get_redis_info():
"""Check Redis connection."""
from kombu.utils.url import _parse_url as parse_redis_url
from redis import (
StrictRedis,
ConnectionError as RedisConnectionError,
ResponseError as RedisResponseError,
)
for conf_name in ('REDIS_URL', 'BROKER_URL', 'CELERY_... | 0.000673 |
def _make_request(self, method, path, data=None, **kwargs):
"""Make a request.
Use the `requests` module to actually perform the request.
Args:
`method`: The method to use.
`path`: The path to the resource.
`data`: Any data to send (for POST and PUT requests... | 0.0013 |
def _socketpair_compat():
"""TCP/IP socketpair including Windows support"""
listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listensock.bind(("127.0.0.1", 0))
listensock.listen(1)
iface, port = lis... | 0.005222 |
def result(self, result):
"""Sets the result of this ResponseStatus.
:param result: The result of this ResponseStatus. # noqa: E501
:type: str
"""
if result is None:
raise ValueError("Invalid value for `result`, must not be `None`") # noqa: E501
allowed_va... | 0.003306 |
def proximal_l1_l2(space, lam=1, g=None):
r"""Proximal operator factory of the group-L1-L2 norm/distance.
Implements the proximal operator of the functional ::
F(x) = lam || |x - g|_2 ||_1
with ``x`` and ``g`` elements in ``space``, and scaling factor ``lam``.
Here, ``|.|_2`` is the pointwise... | 0.000347 |
def graph_to_gluon(self, graph, ctx):
"""Construct SymbolBlock from onnx graph.
Parameters
----------
graph : onnx protobuf object
The loaded onnx graph
ctx : Context or list of Context
Loads the model into one or many context(s).
Returns
... | 0.002353 |
def write_json_flag(flag, fobj, **kwargs):
"""Write a `DataQualityFlag` to a JSON file
Parameters
----------
flag : `DataQualityFlag`
data to write
fobj : `str`, `file`
target file (or filename) to write
**kwargs
other keyword arguments to pass to :func:`json.dump`
... | 0.001025 |
def line_to_offset(self, line, column):
"""
Converts 1-based line number and 0-based column to 0-based character offset into text.
"""
line -= 1
if line >= len(self._line_offsets):
return self._text_len
elif line < 0:
return 0
else:
return min(self._line_offsets[line] + max... | 0.014368 |
def get_vhost(self, vname):
"""
Returns the attributes of a single named vhost in a dict.
:param string vname: Name of the vhost to get.
:returns dict vhost: Attribute dict for the named vhost
"""
vname = quote(vname, '')
path = Client.urls['vhosts_by_name'] % ... | 0.004819 |
def create(self, ignore_warnings=None):
"""Create this AppProfile.
.. note::
Uses the ``instance`` and ``app_profile_id`` on the current
:class:`AppProfile` in addition to the ``routing_policy_type``,
``description``, ``cluster_id`` and ``allow_transactional_writes`... | 0.001462 |
def post_calendar_events(self, calendar_id, body, params=None):
"""
`<>`_
:arg calendar_id: The ID of the calendar to modify
:arg body: A list of events
"""
for param in (calendar_id, body):
if param in SKIP_IN_PATH:
raise ValueError("Empty va... | 0.00363 |
def read_csv_lightcurve(lcfile):
'''
This reads in a K2 lightcurve in CSV format. Transparently reads gzipped
files.
Parameters
----------
lcfile : str
The light curve file to read.
Returns
-------
dict
Returns an lcdict.
'''
# read in the file first
... | 0.002068 |
def substring_search(query, list_of_strings, limit_results=DEFAULT_LIMIT):
""" main function to call for searching
"""
matching = []
query_words = query.split(' ')
# sort by longest word (higest probability of not finding a match)
query_words.sort(key=len, reverse=True)
counter = 0
... | 0.00149 |
def delete(self, timeout=-1, custom_headers=None, force=False):
"""Deletes current resource.
Args:
timeout: Timeout in seconds.
custom_headers: Allows to set custom http headers.
force: Flag to force the operation.
"""
uri = self.data['uri']
... | 0.003906 |
def analyze(self):
"""Run analysis."""
bench = self.kernel.build_executable(verbose=self.verbose > 1, openmp=self._args.cores > 1)
element_size = self.kernel.datatypes_size[self.kernel.datatype]
# Build arguments to pass to command:
args = [str(s) for s in list(self.kernel.const... | 0.003165 |
def _MergeTaskStorage(self, storage_writer):
"""Merges a task storage with the session storage.
This function checks all task stores that are ready to merge and updates
the scheduled tasks. Note that to prevent this function holding up
the task scheduling loop only the first available task storage is m... | 0.009233 |
def address_checksum_and_decode(addr: str) -> Address:
""" Accepts a string address and turns it into binary.
Makes sure that the string address provided starts is 0x prefixed and
checksummed according to EIP55 specification
"""
if not is_0x_prefixed(addr):
raise InvalidAddress('Add... | 0.001802 |
def organize_models(self, outdir, force_rerun=False):
"""Organize and rename SWISS-MODEL models to a single folder with a name containing template information.
Args:
outdir (str): New directory to copy renamed models to
force_rerun (bool): If models should be copied again even i... | 0.005984 |
def _compute_bits(self):
"""
m._compute_bits() -- [utility] Set m.totbits to the number of bits and m.bits to a list of bits at each position
"""
bits = []
totbits = 0
bgbits = 0
bg = self.background
UNCERT = lambda x: x*math.log(x)/math.log(2.0)
... | 0.01359 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.