text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _ValidateTimeRange(timerange):
"""Parses a timerange argument and always returns non-None timerange."""
if len(timerange) != 2:
raise ValueError("Timerange should be a sequence with 2 items.")
(start, end) = timerange
precondition.AssertOptionalType(start, rdfvalue.RDFDatetime)
precondition.AssertOpt... | 0.016854 |
def submit_row(context):
"""
Displays the row of buttons for delete and save.
"""
opts = context['opts']
change = context['change']
is_popup = context['is_popup']
save_as = context['save_as']
return {
'onclick_attrib': (opts.get_ordered_objects() and change
... | 0.007937 |
def call_interval(freq, **kwargs):
"""Decorator for the CallInterval wrapper"""
def wrapper(f):
return CallInterval(f, freq, **kwargs)
return wrapper | 0.005882 |
def find_exts(top, exts, exclude_dirs=None, include_dirs=None,
match_mode="basename"):
"""
Find all files with the extension listed in `exts` that are located within
the directory tree rooted at `top` (including top itself, but excluding
'.' and '..')
Args:
top (str): Root dir... | 0.000425 |
def find_lt(a, x):
"""Find rightmost value less than x"""
i = bisect.bisect_left(a, x)
if i:
return a[i-1]
raise ValueError | 0.006803 |
def get_area_def(self, key, info=None):
"""Create AreaDefinition for specified product.
Projection information are hard coded for 0 degree geos projection
Test dataset doesn't provide the values in the file container.
Only fill values are inserted.
"""
# TODO Get projec... | 0.00161 |
def add_key(self, key_id, key):
"""
::
POST /:login/keys
:param key_id: label for the new key
:type key_id: :py:class:`basestring`
:param key: the full SSH RSA public key
:type key: :py:class:`str`
Uploads a public k... | 0.011928 |
def on_write_timeout(self, query, consistency, write_type,
required_responses, received_responses, retry_num):
"""
This is called when a write operation times out from the coordinator's
perspective (i.e. a replica did not respond to the coordinator in time).
`qu... | 0.002827 |
def erase(self):
"""White out the progress bar."""
with self._at_last_line():
self.stream.write(self._term.clear_eol)
self.stream.flush() | 0.011561 |
def a2b_base58(s):
"""Convert base58 to binary using BASE58_ALPHABET."""
v, prefix = to_long(BASE58_BASE, lambda c: BASE58_LOOKUP[c], s.encode("utf8"))
return from_long(v, prefix, 256, lambda x: x) | 0.009569 |
async def contains_albums(self, *albums: Sequence[Union[str, Album]]) -> List[bool]:
"""Check if one or more albums is already saved in the current Spotify user’s ‘Your Music’ library.
Parameters
----------
albums : Union[Album, str]
A sequence of artist objects or spotify I... | 0.008439 |
def _definition_from_example(example):
"""Generates a swagger definition json from a given example
Works only for simple types in the dict
Args:
example: The example for which we want a definition
Type is DICT
Returns:
A dict that is the ... | 0.001491 |
def iterate_symbols():
"""
Return an iterator yielding registered netcodes.
"""
for prefix in search_prefixes():
package = importlib.import_module(prefix)
for importer, modname, ispkg in pkgutil.walk_packages(path=package.__path__, onerror=lambda x: None):
network = network_f... | 0.004902 |
def genl_send_simple(sk, family, cmd, version, flags):
"""Send a Generic Netlink message consisting only of a header.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L84
This function is a shortcut for sending a Generic Netlink message without any message payload. The message will only
... | 0.00308 |
def getShare(store, role, shareID):
"""
Retrieve the accessible facet of an Item previously shared with
L{shareItem}.
This method is pending deprecation, and L{Role.getShare} should be
preferred in new code.
@param store: an axiom store (XXX must be the same as role.store)
@param role: a ... | 0.001186 |
def category(self, title, pageid=None, cparams=None, namespace=None):
"""
Returns category query string
"""
query = self.LIST.substitute(
WIKI=self.uri,
ENDPOINT=self.endpoint,
LIST='categorymembers')
status = pageid or title
query += ... | 0.002581 |
def results(self, query_name):
"""
Gets a single saved query with a 'result' object for a project from the
Keen IO API given a query name.
Read or Master key must be set.
"""
url = "{0}/{1}/result".format(self.saved_query_url, query_name)
response = self._get_jso... | 0.005128 |
def dumps(asts):
"""
Create a compressed string from an Trace.
"""
d = asts.values.tostring()
t = asts.index.values.astype(float).tostring()
lt = struct.pack('<L', len(t))
i = asts.name.encode('utf-8')
li = struct.pack('<L', len(i))
try: # python 2
return buffer(zlib.compres... | 0.002342 |
def _detect_branching(self, Dseg: np.ndarray, tips: np.ndarray, seg_reference=None):
"""Detect branching on given segment.
Call function __detect_branching three times for all three orderings of
tips. Points that do not belong to the same segment in all three
orderings are assigned to a... | 0.003778 |
def get_size(path):
'''Return the size of path in bytes if it exists and can be determined.'''
size = os.path.getsize(path)
for item in os.walk(path):
for file in item[2]:
size += os.path.getsize(os.path.join(item[0], file))
return size | 0.003676 |
def ahrs3_encode(self, roll, pitch, yaw, altitude, lat, lng, v1, v2, v3, v4):
'''
Status of third AHRS filter if available. This is for ANU research
group (Ali and Sean)
roll : Roll angle (rad) (float)
pitch ... | 0.004803 |
def application(environ, start_response):
"""WSGI interface.
"""
def send_response(status, body):
if not isinstance(body, bytes):
body = body.encode('utf-8')
start_response(status, [('Content-Type', 'text/plain'),
('Content-Length', '%d' % len(bo... | 0.000889 |
def size_container_folding(value):
"""
Convert value to ast expression if size is not too big.
Converter for sized container.
"""
if len(value) < MAX_LEN:
if isinstance(value, list):
return ast.List([to_ast(elt) for elt in value], ast.Load())
elif isinstance(value, tuple... | 0.000795 |
def slamdunkFilterStatsTable(self):
""" Take the parsed filter stats from Slamdunk and add it to a separate table """
headers = OrderedDict()
headers['mapped'] = {
'namespace': 'Slamdunk',
'title': '{} Mapped'.format(config.read_count_prefix),
'description': ... | 0.005972 |
def freshenFocus(self):
""" Did something which requires a new look. Move scrollbar up.
This often needs to be delayed a bit however, to let other
events in the queue through first. """
self.top.update_idletasks()
self.top.after(10, self.setViewAtTop) | 0.006667 |
def versions():
"""Report versions"""
stream = sys.stdout if _PY3K else sys.stderr
print('PyQ', __version__, file=stream)
if _np is not None:
print('NumPy', _np.__version__, file=stream)
print('KDB+ %s (%s) %s' % tuple(q('.z.K,.z.k,.z.o')), file=stream)
print('Python', sys.version, file=... | 0.003058 |
def _await_descriptor_upload(tor_protocol, onion, progress, await_all_uploads):
"""
Internal helper.
:param tor_protocol: ITorControlProtocol instance
:param onion: IOnionService instance
:param progress: a progess callback, or None
:returns: a Deferred that fires once we've detected at leas... | 0.000654 |
def lyap_r(data, emb_dim=10, lag=None, min_tsep=None, tau=1, min_neighbors=20,
trajectory_len=20, fit="RANSAC", debug_plot=False, debug_data=False,
plot_file=None, fit_offset=0):
"""
Estimates the largest Lyapunov exponent using the algorithm of Rosenstein
et al. [lr_1]_.
Explanation of L... | 0.005946 |
def move_to(self, thing, destination):
"Move a thing to a new location."
thing.bump = self.some_things_at(destination, Obstacle)
if not thing.bump:
thing.location = destination
for o in self.observers:
o.thing_moved(thing) | 0.006993 |
def _iter_coords(nsls):
"""Iterate through all matching coordinates in a sequence of slices."""
# First convert all slices to ranges
ranges = list()
for nsl in nsls:
if isinstance(nsl, int):
ranges.append(range(nsl, nsl+1))
else:
ranges.append(range(nsl.start, nsl... | 0.002404 |
def poll(in_sockets, out_sockets, timeout=-1):
"""
Poll a list of sockets
:param in_sockets: sockets for reading
:param out_sockets: sockets for writing
:param timeout: poll timeout in seconds, -1 is infinite wait
:return: tuple (read socket list, write socket list)
"""
sockets = {}
... | 0.000933 |
def encode(char_data, encoding='utf-8'):
"""
Encode the parameter as a byte string.
:param char_data: the data to encode
:rtype: bytes
"""
if type(char_data) is str:
return char_data.encode(encoding, errors='replace')
elif type(char_data) is bytes:
return char_data
else... | 0.004854 |
def _forward_kernel(self, F, inputs, states, **kwargs):
""" forward using CUDNN or CPU kenrel"""
if self._layout == 'NTC':
inputs = F.swapaxes(inputs, dim1=0, dim2=1)
if self._projection_size is None:
params = (kwargs['{}{}_{}_{}'.format(d, l, g, t)].reshape(-1)
... | 0.002358 |
def matchesWithMatchers(self, event):
'''
Return all matches for this event. The first matcher is also returned for each matched object.
:param event: an input event
'''
ret = []
self._matches(event, set(), ret)
return tuple(ret) | 0.013605 |
def upload(self, source,
destination,
bucket,
chunk_size = 2 * 1024 * 1024,
metadata=None,
keep_private=True):
'''upload a file from a source to a destination. The client is expected
to have a bucket (self._bucket) that ... | 0.008213 |
def difference(self, *iterables):
"""
Return a new set with elements in the set that are not in the
*iterables*.
"""
diff = self._set.difference(*iterables)
return self._fromset(diff, key=self._key) | 0.00813 |
def from_unit_to_satoshi(self, value, unit='satoshi'):
"""
Convert a value to satoshis. units can be any fiat currency.
By default the unit is satoshi.
"""
if not unit or unit == 'satoshi':
return value
if unit == 'bitcoin' or unit == 'btc':
return... | 0.004158 |
def choice_complete(self, ctx, incomplete):
"""Returns the completion results for click.core.Choice
Parameters
----------
ctx : click.core.Context
The current context
incomplete :
The string to complete
Returns
-------
[(str, str)]
A list of completion results
... | 0.002208 |
def generate_format(self):
"""
Means that value have to be in specified format. For example date, email or other.
.. code-block:: python
{'format': 'email'}
Valid value for this definition is user@example.com but not @username
"""
with self.l('if isinstance... | 0.005258 |
def get_path(root, path, default=_UNSET):
"""Retrieve a value from a nested object via a tuple representing the
lookup path.
>>> root = {'a': {'b': {'c': [[1], [2], [3]]}}}
>>> get_path(root, ('a', 'b', 'c', 2, 0))
3
The path format is intentionally consistent with that of
:func:`remap`.
... | 0.000945 |
def serve(application, host='127.0.0.1', port=8080):
"""Gevent-based WSGI-HTTP server."""
# Instantiate the server with a host/port configuration and our application.
WSGIServer((host, int(port)), application).serve_forever() | 0.026087 |
def merge_pdb_range_pairs(prs):
'''Takes in a list of PDB residue IDs (including insertion codes) specifying ranges and returns a sorted list of merged, sorted ranges.
This works as above but we have to split the residues into pairs as "1A" > "19".
'''
new_prs = []
sprs = [sorted((split_pdb_resi... | 0.005482 |
def _index_fs(self):
"""Returns a deque object full of local file system items.
:returns: ``deque``
"""
indexed_objects = self._return_deque()
directory = self.job_args.get('directory')
if directory:
indexed_objects = self._return_deque(
deq... | 0.002558 |
def _convert_metrics_to_xml(metrics, root):
'''
<Version>version-number</Version>
<Enabled>true|false</Enabled>
<IncludeAPIs>true|false</IncludeAPIs>
<RetentionPolicy>
<Enabled>true|false</Enabled>
<Days>number-of-days</Days>
</RetentionPolicy>
'''
# Version
ETree.Sub... | 0.002571 |
def unpublish(self, registry=None):
''' Try to un-publish the current version. Return a description of any
errors that occured, or None if successful.
'''
return registry_access.unpublish(
self.getRegistryNamespace(),
self.getName(),
self.getVersio... | 0.005495 |
def xyz(self):
"""Return all particle coordinates in this compound.
Returns
-------
pos : np.ndarray, shape=(n, 3), dtype=float
Array with the positions of all particles.
"""
if not self.children:
pos = np.expand_dims(self._pos, axis=0)
el... | 0.003854 |
def authenticate_or_redirect(self):
"""
Helper function suitable for @app.before_request and @check.
Sets g.oidc_id_token to the ID token if the user has successfully
authenticated, else returns a redirect object so they can go try
to authenticate.
:returns: A redirect o... | 0.0007 |
def from_project_root(cls, project_root, cli_vars):
"""Create a project from a root directory. Reads in dbt_project.yml and
packages.yml, if it exists.
:param project_root str: The path to the project root to load.
:raises DbtProjectError: If the project is missing or invalid, or if
... | 0.001558 |
def endpoint_2_json(self):
"""
transform local object to JSON
:return: JSON object
"""
LOGGER.debug("Endpoint.endpoint_2_json")
json_obj = {
"endpointID": self.id,
"endpointURL": self.url,
"endpointParentNodeID": self.parent_node_id,
... | 0.00431 |
def update(self, ip_address=values.unset, friendly_name=values.unset,
cidr_prefix_length=values.unset):
"""
Update the IpAddressInstance
:param unicode ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP addres... | 0.006903 |
def get_gaps_and_overlaps(self, tier1, tier2, maxlen=-1):
"""Give gaps and overlaps. The return types are shown in the table
below. The string will be of the format: ``id_tiername_tiername``.
.. note:: There is also a faster method: :func:`get_gaps_and_overlaps2`
For example when a gap... | 0.000398 |
def slurp_properties(source, destination, ignore=[], srckeys=None):
"""Copy properties from *source* (assumed to be a module) to
*destination* (assumed to be a dict).
*ignore* lists properties that should not be thusly copied.
*srckeys* is a list of keys to copy, if the source's __all__ is
untrustw... | 0.008157 |
def create_strategy(name=None):
"""
Create a strategy, or just returns it if it's already one.
:param name:
:return: Strategy
"""
import logging
from bonobo.execution.strategies.base import Strategy
if isinstance(name, Strategy):
return name
if name is None:
name ... | 0.004505 |
def _search(self, words, include=None, exclude=None, lookup=None):
'''Full text search. Return a list of queries to intersect.'''
lookup = lookup or 'contains'
query = self.router.worditem.query()
if include:
query = query.filter(model_type__in=include)
if exclu... | 0.003436 |
def parse(self, raise_parsing_errors=True):
"""
Process the file content.
Usage::
>>> plist_file_parser = PlistFileParser("standard.plist")
>>> plist_file_parser.parse()
True
>>> plist_file_parser.elements.keys()
[u'Dictionary A', u'N... | 0.004169 |
def import_schema_to_json(name, store_it=False):
"""
loads the given schema name
from the local filesystem
and puts it into a store if it
is not in there yet
:param name:
:param store_it: if set to True, stores the contents
:return:
"""
schema_file = u"%s.json" % name
file_p... | 0.001168 |
def error_msg_from_exception(e):
"""Translate exception into error message
Database have different ways to handle exception. This function attempts
to make sense of the exception object and construct a human readable
sentence.
TODO(bkyryliuk): parse the Presto error message from the connection
... | 0.001196 |
async def allocate(
cls, *,
hostname: str = None,
architectures: typing.Sequence[str] = None,
cpus: int = None,
fabrics: typing.Sequence[FabricParam] = None,
interfaces: typing.Sequence[InterfaceParam] = None,
memory: float = None,
... | 0.000271 |
async def addNodes(self, nodedefs):
'''
Quickly add/modify a list of nodes from node definition tuples.
This API is the simplest/fastest way to add nodes, set node props,
and add tags to nodes remotely.
Args:
nodedefs (list): A list of node definition tuples. See be... | 0.003077 |
def flds_firstsort(d):
'''
Perform a lexsort and return the sort indices and shape as a tuple.
'''
shape = [ len( np.unique(d[l]) )
for l in ['xs', 'ys', 'zs'] ];
si = np.lexsort((d['z'],d['y'],d['x']));
return si,shape; | 0.046512 |
def stream(self, sha):
"""For now, all lookup is done by git itself"""
hexsha, typename, size, stream = self._git.stream_object_data(bin_to_hex(sha))
return OStream(hex_to_bin(hexsha), typename, size, stream) | 0.012931 |
def ANC_closed(pH, total_carbonates):
"""Calculate the acid neutralizing capacity (ANC) under a closed system
in which no carbonates are exchanged with the atmosphere during the
experiment. Based on pH and total carbonates in the system.
:param pH: pH of the system
:type pH: float
:param total_... | 0.003115 |
def _friendlyAuthError(fn):
''' Decorator to print a friendly you-are-not-authorised message. Use
**outside** the _handleAuth decorator to only print the message after
the user has been given a chance to login. '''
@functools.wraps(fn)
def wrapped(*args, **kwargs):
try:
r... | 0.008746 |
def redeliver(self):
"""
Re-deliver the answer to the consequence which previously handled it
by raising an exception.
This method is intended to be invoked after the code in question has
been upgraded. Since there are no buggy answer receivers in
production, nothing ca... | 0.00335 |
def get(cls, format):
"""
Gets an emitter, returns the class and a content-type.
"""
if cls.EMITTERS.has_key(format):
return cls.EMITTERS.get(format)
raise ValueError("No emitters found for type %s" % format) | 0.011494 |
def bip32_seed(self, s):
"""
Parse a bip32 private key from a seed.
Return a :class:`BIP32 <pycoin.key.BIP32Node.BIP32Node>` or None.
"""
pair = parse_colon_prefix(s)
if pair is None or pair[0] not in "HP":
return None
if pair[0] == "H":
tr... | 0.00363 |
def adjoint(self):
"""Adjoint of this operator.
Returns
-------
adjoint : `PointwiseInnerAdjoint`
"""
return PointwiseInnerAdjoint(
sspace=self.base_space, vecfield=self.vecfield,
vfspace=self.domain, weighting=self.weights) | 0.006734 |
def get_all_items_of_delivery_note(self, delivery_note_id):
"""
Get all items of delivery note
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param delivery_note_id: the delivery not... | 0.005226 |
def filter(self, **kwargs):
'''
Only columns/attributes that have been specified as having an index with
the ``index=True`` option on the column definition can be filtered with
this method. Prefix, suffix, and pattern match filters must be provided
using the ``.startswith()``, ``... | 0.003943 |
def _dos2unix_cygwin(self, file_path):
"""
Use cygwin to convert file to unix format
"""
dos2unix_cmd = \
[os.path.join(self._cygwin_bin_location, "dos2unix.exe"),
self._get_cygwin_path(file_path)]
process = Popen(dos2unix_cmd,
std... | 0.005195 |
def split_bgedge(self, bgedge, guidance=None, sorted_guidance=False,
account_for_colors_multiplicity_in_guidance=True,
key=None):
""" Splits a :class:`bg.edge.BGEdge` in current :class:`BreakpointGraph` most similar to supplied one (if no unique identifier ``key`` is pr... | 0.008427 |
def systemInformationType2bis():
"""SYSTEM INFORMATION TYPE 2bis Section 9.1.33"""
a = L2PseudoLength(l2pLength=0x15)
b = TpPd(pd=0x6)
c = MessageType(mesType=0x2) # 00000010
d = NeighbourCellsDescription()
e = RachControlParameters()
f = Si2bisRestOctets()
packet = a / b / c / d / e / ... | 0.00295 |
def getrawfile(self, project_id, sha1, filepath):
"""
Get the raw file contents for a file by commit SHA and path.
:param project_id: The ID of a project
:param sha1: The commit or branch name
:param filepath: The path the file
:return: raw file contents
"""
... | 0.005642 |
def leaky_relu(attrs, inputs, proto_obj):
"""Leaky Relu function"""
if 'alpha' in attrs:
new_attrs = translation_utils._fix_attribute_names(attrs, {'alpha' : 'slope'})
else:
new_attrs = translation_utils._add_extra_attributes(attrs, {'slope': 0.01})
return 'LeakyReLU', new_attrs, inputs | 0.012539 |
def api(self):
""" Get or create an Api() instance using django settings. """
api = getattr(self, '_api', None)
if api is None:
self._api = mailjet.Api()
return self._api | 0.009259 |
def _charlist(self, data) -> list:
"""
Private method to return the variables in a SAS Data set that are of type char
:param data: SAS Data object to process
:return: list of character variables
:rtype: list
"""
# Get list of character variables to add to nominal... | 0.00339 |
def dump(args):
"""
%prog dump fastbfile
Export ALLPATHS fastb file to fastq file. Use --dir to indicate a previously
run allpaths folder.
"""
p = OptionParser(dump.__doc__)
p.add_option("--dir",
help="Working directory [default: %default]")
p.add_option("--nosim", defau... | 0.002096 |
def removefromreadergroup(self, groupname):
"""Remove a reader from a reader group"""
hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER)
if 0 != hresult:
raise EstablishContextException(hresult)
try:
hresult = SCardRemoveReaderFromGroup(hcontext, self.na... | 0.006289 |
def radial_density(im, bins=10, voxel_size=1):
r"""
Computes radial density function by analyzing the histogram of voxel
values in the distance transform. This function is defined by
Torquato [1] as:
.. math::
\int_0^\infty P(r)dr = 1.0
where *P(r)dr* is the probability of fi... | 0.000303 |
def get_notifications(self, login=None, **kwargs):
"""Get the current notifications of a user.
:return: JSON
"""
_login = kwargs.get(
'login',
login or self._login
)
_notif_url = NOTIF_URL.format(login=_login)
return self._request_api(url... | 0.0059 |
def _push_forever_keys(self, namespace, key):
"""
Store a copy of the full key for each namespace segment.
:type namespace: str
:type key: str
"""
full_key = '%s%s:%s' % (self.get_prefix(),
hashlib.sha1(encode(self._tags.get_namespace())).... | 0.008065 |
def csv_to_dict(file_name, file_location):
"""
Function to import a csv as a dictionary
Args:
file_name: The name of the csv file
file_location: The location of the file, derive from the os module
Returns: returns a dictionary
"""
file = __os.path.join(file_location, file_name)... | 0.00241 |
def rollout(self, **kwargs):
"""Generate x for open loop movements.
"""
if kwargs.has_key('tau'):
timesteps = int(self.timesteps / kwargs['tau'])
else:
timesteps = self.timesteps
self.x_track = np.zeros(timesteps)
self.reset_state()
... | 0.013393 |
def cancel(self):
"""
Cancel the consumer and stop recieving messages.
This method is a :ref:`coroutine <coroutine>`.
"""
self.sender.send_BasicCancel(self.tag)
try:
yield from self.synchroniser.wait(spec.BasicCancelOK)
except AMQPError:
p... | 0.003407 |
def read(config_file, configspec, server_mode=False, default_section='default_settings', list_values=True):
'''
Read the config file with spec validation
'''
# configspec = ConfigObj(path.join(path.abspath(path.dirname(__file__)), configspec),
# encoding='UTF8',
# ... | 0.007702 |
def create_token(self,
token_name,
project_name,
dataset_name,
is_public):
"""
Creates a token with the given parameters.
Arguments:
project_name (str): Project name
dataset_name (str): Da... | 0.007833 |
def Tracer_AD_Pe(t_seconds, t_bar, C_bar, Pe):
"""Used by Solver_AD_Pe. All inputs and outputs are unitless. This is the
model function, f(x, ...). It takes the independent variable as the
first argument and the parameters to fit as separate remaining arguments.
:param t_seconds: List of times
:typ... | 0.003745 |
def find_position(edges, prow, bstart, bend, total=5):
"""Find a EMIR CSU bar position in a edge image.
Parameters
==========
edges; ndarray,
a 2d image with 1 where is a border, 0 otherwise
prow: int,
reference 'row' of the bars
bstart: int,
minimum 'x' position of a ba... | 0.004721 |
def plot(self, figsize="GROW", parameters=None, chains=None, extents=None, filename=None,
display=False, truth=None, legend=None, blind=None, watermark=None): # pragma: no cover
""" Plot the chain!
Parameters
----------
figsize : str|tuple(float)|float, optional
... | 0.003716 |
def parse_value(self, tup_tree):
"""
Parse a VALUE element and return its text content as a unicode string.
Whitespace is preserved.
The conversion of the text representation of the value to a CIM data
type object requires CIM type information which is not available on the
... | 0.003263 |
def prepare_build_dir(self):
'''Ensure that a build dir exists for the recipe. This same single
dir will be used for building all different archs.'''
self.build_dir = self.get_build_dir()
self.common_dir = self.get_common_dir()
copy_files(join(self.bootstrap_dir, 'build'), self.b... | 0.002865 |
def get_documented_add(self, record_descriptors):
"""
this hack is used to document add function
a methods __doc__ attribute is read-only (or must use metaclasses, what I certainly don't want to do...)
we therefore create a function (who's __doc__ attribute is read/write), and will bind it to Table in _... | 0.004769 |
def _set_logging(
logger_name="colin",
level=logging.INFO,
handler_class=logging.StreamHandler,
handler_kwargs=None,
format='%(asctime)s.%(msecs).03d %(filename)-17s %(levelname)-6s %(message)s',
date_format='%H:%M:%S'):
"""
Set personal logger for this library.
... | 0.00318 |
def add_error(name=None, code=None, status=None):
"""Create a new Exception class"""
if not name or not status or not code:
raise Exception("Can't create Exception class %s: you must set both name, status and code" % name)
myexception = type(name, (PyMacaronException, ), {"code": code, "status": sta... | 0.005725 |
def port_provisioned(port_id):
"""Returns true if port still exists."""
session = db.get_reader_session()
with session.begin():
port_model = models_v2.Port
res = bool(session.query(port_model)
.filter(port_model.id == port_id).count())
return res | 0.003367 |
def cancelar_ultima_venda(self, chave_cfe, dados_cancelamento):
"""Sobrepõe :meth:`~satcfe.base.FuncoesSAT.cancelar_ultima_venda`.
:return: Uma resposta SAT especializada em ``CancelarUltimaVenda``.
:rtype: satcfe.resposta.cancelarultimavenda.RespostaCancelarUltimaVenda
"""
resp... | 0.006981 |
def make_valid_polygon(shape):
"""
Make a polygon valid. Polygons can be invalid in many ways, such as
self-intersection, self-touching and degeneracy. This process attempts to
make a polygon valid while retaining as much of its extent or area as
possible.
First, we call pyclipper to robustly u... | 0.00122 |
def _deserialize_dict(data, boxed_type):
"""Deserializes a dict and its elements.
:param data: dict to deserialize.
:type data: dict
:param boxed_type: class literal.
:return: deserialized dict.
:rtype: dict
"""
return {k: _deserialize(v, boxed_type)
for k, v in six.iterite... | 0.00304 |
def process_generic(self, kind, context):
"""Transform otherwise unhandled kinds of chunks by calling an underscore prefixed function by that name."""
result = None
while True:
chunk = yield result
if chunk is None:
return
result = chunk.clone(line='_' + kind + '(' + chunk.line + ')') | 0.056604 |
def compress_monkey_patch():
"""patch all compress
we need access to variables from widget scss
for example we have::
/themes/bootswatch/cyborg/_variables
but only if is cyborg active for this reasone we need
dynamically append import to every scss file
"""
from compressor.templ... | 0.001253 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.