text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def encode(self):
"""Encode the DAT packet based on instance variables, populating
self.buffer, returning self."""
fmt = b"!HH%dsx" % len(self.errmsgs[self.errorcode])
log.debug("encoding ERR packet with fmt %s", fmt)
self.buffer = struct.pack(fmt,
... | 0.004264 |
def __get_keywords(self):
"""
Get all the keywords related of this page
Returns:
An array of strings
"""
txt = self.text
for line in txt:
for word in split_words(line):
yield(word) | 0.007435 |
def pop(self, count=None):
'''Passing in the queue from which to pull items, the current time,
when the locks for these returned items should expire, and the number
of items to be popped off.'''
results = [Job(self.client, **job) for job in json.loads(
self.client('pop', self... | 0.00431 |
def distance_landscape_as_3d_data(self, x_axis, y_axis):
"""
Returns the distance landscape as three-dimensional data for the specified projection.
:param x_axis: variable to be plotted on the x axis of projection
:param y_axis: variable to be plotted on the y axis of projection
... | 0.005655 |
def set(self, key: URIRef, value: Union[Literal, BNode, URIRef, str, int], lang: Optional[str]=None):
""" Set the VALUE for KEY predicate in the Metadata Graph
:param key: Predicate to be set (eg. DCT.creator)
:param value: Value to be stored (eg. "Cicero")
:param lang: [Optional] Langu... | 0.006443 |
def safe_gz_unzip(contents):
''' Takes a file's contents passed as a string (contents) and either gz-unzips the contents and returns the uncompressed data or else returns the original contents.
This function raises an exception if passed what appears to be gz-zipped data (from the magic number) but if gzip ... | 0.007143 |
def density(self, *args):
""" Mean density in g/cc
"""
M = self.mass(*args) * MSUN
V = 4./3 * np.pi * (self.radius(*args) * RSUN)**3
return M/V | 0.016304 |
def pause(self, scaling_group):
"""
Pauses all execution of the policies for the specified scaling group.
"""
uri = "/%s/%s/pause" % (self.uri_base, utils.get_id(scaling_group))
resp, resp_body = self.api.method_post(uri)
return None | 0.007117 |
def module_definition_from_mirteFile_dict(man, d):
""" Creates a ModuleDefinition instance from the dictionary <d> from
a mirte-file for the Manager instance <man>. """
m = ModuleDefinition()
if 'inherits' not in d:
d['inherits'] = list()
if 'settings' not in d:
d['settings'] = d... | 0.000611 |
def off(self, group):
"""Turn the LED off for a group."""
asyncio.ensure_future(self._send_led_on_off_request(group, 0),
loop=self._loop) | 0.010929 |
def reindex(config):
"""
Recreate the Search Index.
"""
request = config.task(_reindex).get_request()
config.task(_reindex).run(request) | 0.006369 |
def _create_validation_error(self,
name, # type: str
value, # type: Any
validation_outcome=None, # type: Any
error_type=None, # type: Type[... | 0.006839 |
def negative_directional_movement(high_data, low_data):
"""
Negative Directional Movement (-DM).
-DM: if DWNMOVE > UPMOVE and DWNMOVE > 0 then -DM = DWNMOVE else -Dm = 0
"""
catch_errors.check_for_input_len_diff(high_data, low_data)
up_moves = calculate_up_moves(high_data)
down_moves = cal... | 0.001764 |
def _init_browser(self):
"""
Ovveride this method with the appropriate way to prepare a logged in
browser.
"""
self.browser = mechanize.Browser()
self.browser.set_handle_robots(False)
self.browser.open(self.server_url + "/youraccount/login")
self.browser.s... | 0.003937 |
def create_gtr(params):
"""
parse the arguments referring to the GTR model and return a GTR structure
"""
model = params.gtr
gtr_params = params.gtr_params
if model == 'infer':
gtr = GTR.standard('jc', alphabet='aa' if params.aa else 'nuc')
else:
try:
kwargs = {}
... | 0.006299 |
def update(self):
"""Update RAM memory stats using the input method."""
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local':
# Update stats using the standard system lib
# Grab MEM using the psutil virtual_memory method
vm_s... | 0.003717 |
async def open(self):
"""Open handler connection and authenticate session.
If the handler is already open, this operation will do nothing.
A handler opened with this method must be explicitly closed.
It is recommended to open a handler within a context manager as
opposed to call... | 0.003252 |
def find_definition(project, code, offset, resource=None, maxfixes=1):
"""Return the definition location of the python name at `offset`
A `Location` object is returned if the definition location can be
determined, otherwise ``None`` is returned.
"""
fixer = fixsyntax.FixSyntax(project, code, resour... | 0.000969 |
def traceroute(self,
destination,
source=C.TRACEROUTE_SOURCE,
ttl=C.TRACEROUTE_TTL,
timeout=C.TRACEROUTE_TIMEOUT,
vrf=C.TRACEROUTE_VRF):
"""Execute traceroute and return results."""
traceroute_result = {}
... | 0.004089 |
def unpack_bitstring(length, is_float, is_signed, bits):
# type: (int, bool, bool, typing.Any) -> typing.Union[float, int]
"""
returns a value calculated from bits
:param length: length of signal in bits
:param is_float: value is float
:param bits: value as bits (array/iterable)
:param is_si... | 0.004138 |
def to_unicode(sorb, allow_eval=False):
r"""Ensure that strings are unicode (UTF-8 encoded).
Evaluate bytes literals that are sometimes accidentally created by str(b'whatever')
>>> to_unicode(b'whatever')
'whatever'
>>> to_unicode(b'b"whatever"')
'whatever'
>>> to_unicode(repr(b'b"whatever... | 0.002066 |
def change_mime(self, bucket, key, mime):
"""修改文件mimeType:
主动修改指定资源的文件类型,具体规格参考:
http://developer.qiniu.com/docs/v6/api/reference/rs/chgm.html
Args:
bucket: 待操作资源所在空间
key: 待操作资源文件名
mime: 待操作文件目标mimeType
"""
resource = entry(bucke... | 0.004396 |
def prepack(self, namedstruct, skip_self=False, skip_sub=False):
'''
Run prepack
'''
if not skip_self and self.prepackfunc is not None:
self.prepackfunc(namedstruct) | 0.009569 |
def convert(csv, json, **kwargs):
'''Convert csv to json.
csv: filename or file-like object
json: filename or file-like object
if csv is '-' or None:
stdin is used for input
if json is '-' or None:
stdout is used for output
'''
csv_local, json_local = None, None
try... | 0.001183 |
def main():
'''This is the main function of this script.
The current script args are shown below ::
Usage: checkplotlist [-h] [--search SEARCH] [--sortby SORTBY]
[--filterby FILTERBY] [--splitout SPLITOUT]
[--outprefix OUTPREFIX] [--maxkeyworke... | 0.002236 |
def dump_pytorch_graph(graph):
"""List all the nodes in a PyTorch graph."""
f = "{:25} {:40} {} -> {}"
print(f.format("kind", "scopeName", "inputs", "outputs"))
for node in graph.nodes():
print(f.format(node.kind(), node.scopeName(),
[i.unique() for i in node.inputs()],
... | 0.002469 |
def pct_decode(s):
"""
Return the percent-decoded version of string s.
>>> pct_decode('%43%6F%75%63%6F%75%2C%20%6A%65%20%73%75%69%73%20%63%6F%6E%76%69%76%69%61%6C')
'Coucou, je suis convivial'
>>> pct_decode('')
''
>>> pct_decode('%2525')
'%25'
"""
if s is None:
return N... | 0.004065 |
def config(path=None, root=None, db=None):
"""Return the default run_config object for this installation."""
import ambry.run
return ambry.run.load(path=path, root=root, db=db) | 0.005319 |
def _set_mpls_adjust_bandwidth_lsp_all(self, v, load=False):
"""
Setter method for mpls_adjust_bandwidth_lsp_all, mapped from YANG variable /brocade_mpls_rpc/mpls_adjust_bandwidth_lsp_all (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_mpls_adjust_bandwidth_lsp_all... | 0.005892 |
def p_IndexTypes(self, p):
"""IndexTypes : IndexTypes ',' IndexType
| IndexType"""
n = len(p)
if n == 4:
p[0] = p[1] + [p[3]]
elif n == 2:
p[0] = [p[1]] | 0.008696 |
def _dequeue_function(self):
""" Internal method to dequeue to events. """
from UcsBase import WriteUcsWarning, _GenericMO, WriteObject, UcsUtils
while len(self._wbs):
lowestTimeout = None
for wb in self._wbs:
pollSec = wb.params["pollSec"]
managedObject = wb.params["managedObject"]
timeoutSec ... | 0.036284 |
def dispose(self):
"""Disposes the :py:class:`securityhandlerhelper` object."""
self._username = None
self._password = None
self._org_url = None
self._proxy_url = None
self._proxy_port = None
self._token_url = None
self._securityHandler = None
self... | 0.003263 |
def destroy(self):
"""
Declare that you are done with this OptionParser. This cleans up
reference cycles so the OptionParser (and all objects referenced by
it) can be garbage-collected promptly. After calling destroy(), the
OptionParser is unusable.
"""
OptionCo... | 0.004024 |
def _resolve_assignment_parts(parts, assign_path, context):
"""recursive function to resolve multiple assignments"""
assign_path = assign_path[:]
index = assign_path.pop(0)
for part in parts:
assigned = None
if isinstance(part, nodes.Dict):
# A dictionary in an iterating cont... | 0.000759 |
def save_reg(data):
'''
Save the register to msgpack files
'''
reg_dir = _reg_dir()
regfile = os.path.join(reg_dir, 'register')
try:
if not os.path.exists(reg_dir):
os.makedirs(reg_dir)
except OSError as exc:
if exc.errno == errno.EEXIST:
pass
... | 0.001757 |
def get_grid(start, end, nsteps=100):
"""
Generates a equal distanced list of float values with nsteps+1 values, begining start and ending with end.
:param start: the start value of the generated list.
:type float
:param end: the end value of the generated list.
:type float
:param nstep... | 0.005607 |
def log_deferred(op, log_id, every_n=1, first_n=None):
"""Helper method inserting compliance logging ops.
Note: This helper is not guaranteed to be efficient, as it will insert ops
and control dependencies. If this proves to be a bottleneck, submitters
may wish to consider other methods such as ext... | 0.009871 |
def os_requires_version(ostack_release, pkg):
"""
Decorator for hook to specify minimum supported release
"""
def wrap(f):
@wraps(f)
def wrapped_f(*args):
if os_release(pkg) < ostack_release:
raise Exception("This hook is not supported on releases"
... | 0.002309 |
def rename_index(self, old_name, new_name=None):
"""
Renames an index.
:param old_name: The name of the index to rename from.
:type old_name: str
:param new_name: The name of the index to rename to.
:type new_name: str or None
:rtype: Table
"""
... | 0.002604 |
def create(self, **kwargs):
"""
Creates a new resource.
:param kwargs: The properties of the resource
:return: The created item returned by the API
wrapped as a `Model` object
"""
response = self.ghost.execute_post('%s/' % self._type_name, json={
... | 0.004405 |
async def recv_message(self):
"""Coroutine to receive incoming message from the client.
If client sends UNARY request, then you can call this coroutine
only once. If client sends STREAM request, then you should call this
coroutine several times, until it returns None. To simplify your c... | 0.00291 |
def num_coll_reqd(DIM_FRACTAL, material, DiamTarget):
"""Return the number of doubling collisions required.
Calculates the number of doubling collisions required to produce
a floc of diameter DiamTarget.
"""
return DIM_FRACTAL * np.log2(DiamTarget/material.Diameter) | 0.003484 |
def description(self):
"""string or None if unknown"""
name = None
try:
name = self._TYPE_NAMES[self.audioObjectType]
except IndexError:
pass
if name is None:
return
if self.sbrPresentFlag == 1:
name += "+SBR"
if se... | 0.005013 |
def get_settings_from_client(client):
"""Pull out settings from a SoftLayer.BaseClient instance.
:param client: SoftLayer.BaseClient instance
"""
settings = {
'username': '',
'api_key': '',
'timeout': '',
'endpoint_url': '',
}
try:
settings['username'] = ... | 0.001515 |
def groups(self):
""" dict {group name -> group labels} """
if len(self.groupings) == 1:
return self.groupings[0].groups
else:
to_groupby = lzip(*(ping.grouper for ping in self.groupings))
to_groupby = Index(to_groupby)
return self.axis.groupby(to_... | 0.006098 |
def _wrap_definition_section(source, width):
# type: (str, int) -> str
"""Wrap the given definition section string to the current terminal size.
Note:
Auto-adjusts the spacing between terms and definitions.
Args:
source: The section string to wrap.
Returns:
The wrapped sec... | 0.001239 |
def setup(app):
"""Setup autodoc."""
# Fix for documenting models.FileField
from django.db.models.fields.files import FileDescriptor
FileDescriptor.__get__ = lambda self, *args, **kwargs: self
import django
django.setup()
app.connect('autodoc-skip-member', skip)
app.add_stylesheet('_stat... | 0.002985 |
def prune_hashes(self, hashes, list_type):
"""Prune any hashes not in source resource or change list."""
discarded = []
for hash in hashes:
if (hash in self.hashes):
self.hashes.discard(hash)
discarded.append(hash)
self.logger.info("Not calcula... | 0.008734 |
def setup(config):
"""
Setup the environment for an example run.
"""
formatter = config.Formatter()
if config.verbose:
formatter = result.Verbose(formatter)
if config.color:
formatter = result.Colored(formatter)
current_result = result.ExampleResult(formatter)
ivoire... | 0.002653 |
def ExtractEventsFromSources(self):
"""Processes the sources and extracts events.
Raises:
BadConfigOption: if the storage file path is invalid or the storage
format not supported or an invalid filter was specified.
SourceScannerError: if the source scanner could not find a supported
... | 0.003288 |
def info(self):
"""Returns the name and version of the current shell"""
proc = Popen(['fish', '--version'],
stdout=PIPE, stderr=DEVNULL)
version = proc.stdout.read().decode('utf-8').split()[-1]
return u'Fish Shell {}'.format(version) | 0.006993 |
def set_pkg_verif_code(self, doc, code):
"""Sets the package verification code, if not already set.
code - A string.
Raises CardinalityError if already defined.
Raises OrderError if no package previously defined.
"""
self.assert_package_exists()
if not self.packag... | 0.004049 |
def warningFlag(self):
'''
When viewing individual event registrations, there are a large number of potential
issues that can arise that may warrant scrutiny. This property just checks all of
these conditions and indicates if anything is amiss so that the template need not
check ... | 0.009269 |
def publish_synchronous(self, *args, **kwargs):
'''
Helper for publishing a message using transactions. If 'cb' keyword
arg is supplied, will be called when the transaction is committed.
'''
cb = kwargs.pop('cb', None)
self.tx.select()
self.basic.publish(*args, *... | 0.005587 |
def _ParseFileEntry(self, knowledge_base, file_entry):
"""Parses artifact file system data for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_entry (dfvfs.FileEntry): file entry that contains the artifact
value data.
Rais... | 0.004582 |
def get_rich_menu_image(self, rich_menu_id, timeout=None):
"""Call download rich menu image API.
https://developers.line.me/en/docs/messaging-api/reference/#download-rich-menu-image
:param str rich_menu_id: ID of the rich menu with the image to be downloaded
:param timeout: (optional) ... | 0.004624 |
def run(self):
"""
Returns the sum of unread messages across all registered backends
"""
unread = 0
current_unread = 0
for id, backend in enumerate(self.backends):
temp = backend.unread or 0
unread = unread + temp
if id == self.current_... | 0.003972 |
def hybrid_forward(self, F, scores, target_dists, finished, best_hyp_indices):
"""
Choose an extension of each hypothesis from its softmax distribution.
:param scores: Vocabulary scores for the next beam step. (batch_size * beam_size, target_vocabulary_size)
:param target_dists: The non... | 0.006159 |
def run_manager(self, job_override=None):
"""The run manager.
The run manager is responsible for loading the plugin required based on
what the user has inputted using the parsed_command value as found in
the job_args dict. If the user provides a *job_override* the method
will at... | 0.000925 |
def vnic_attach_to_network_distributed(nicspec, port_group, logger):
"""
Attach vNIC to a Distributed Port Group network
:param nicspec: <vim.vm.device.VirtualDeviceSpec>
:param port_group: <vim.dvs.DistributedVirtualPortgroup>
:param logger:
:return: updated 'nicspec'
... | 0.005 |
def set_logger(self, logger_name, level=logging.INFO):
"""
Convenience function to quickly configure full debug output
to go to the console.
"""
log = logging.getLogger(logger_name)
log.setLevel(level)
ch = logging.StreamHandler(None)
ch.setLevel(level)
... | 0.003175 |
def parse_ontology(self, fn, flatten=True, part_of_cc_only=False):
""" Parse an OBO file and store GO term information.
This function needs to be called before `parse_annotations`, in order
to read in the Gene Ontology terms and structure.
Parameters
----------
fn: str
... | 0.001444 |
def find_loops(self, _path=None):
"""Crappy function that finds a single loop in the tree"""
if _path is None:
_path = []
if self in _path:
return _path + [self]
elif self._children == []:
return None
else:
for child in self._chil... | 0.005249 |
def dependencyOrder(aMap, aList = None):
"""
Given descriptions of dependencies in aMap and an optional list of items in aList
if not aList, aList = aMap.keys()
Returns a list containing each element of aList and all its precursors so that every precursor of
any element in the returned list is seen before tha... | 0.021419 |
def process_fields(self, field_names, depth):
'''
The primary purpose of this function is to store the sql field list
and the depth to which we process.
'''
# List of field names in correct order.
self.field_names = field_names
# number of fields.
self.num... | 0.003861 |
def equation(self):
"""Mix-in class that returns matrix rows for difference in head between inside and
outside equals zeros
Returns matrix part (nunknowns,neq)
Returns rhs part nunknowns
"""
mat = np.empty((self.nunknowns, self.model.neq))
rhs = np.zeros(self.nunk... | 0.007682 |
def load_config(self, path, environments, fill_with_defaults=False):
"""Will load default.yaml and <environment>.yaml at given path.
The environment config will override the default values.
:param path: directory where to find your config files. If the last character is not a slash (/) it will ... | 0.003396 |
def _ssid_inventory(self, inventory, ssid):
"""
Filters an inventory to only return servers matching ssid
"""
matching_hosts = {}
for host in inventory:
if inventory[host]['comment'] == ssid:
matching_hosts[host] = inventory[host]
return match... | 0.006079 |
def is_callable(self):
"""
Ensures :attr:`subject` is a callable.
"""
if not callable(self._subject):
raise self._error_factory(_format("Expected {} to be callable", self._subject)) | 0.013333 |
def restore_backup(self, backup, name, flavor, volume):
"""
Restores a backup to a new database instance. You must supply a backup
(either the ID or a CloudDatabaseBackup object), a name for the new
instance, as well as a flavor and size (in GB) for the instance.
"""
retu... | 0.005249 |
def intensityDistributionSTE(self, bins=10, range=None):
'''
return distribution of STE intensity
'''
v = np.abs(self._last_diff[self.mask_STE])
return np.histogram(v, bins, range) | 0.008889 |
def reserve_file(self, relative_path):
"""reserve a XML file for the slice at <relative_path>.xml
- the relative path will be created for you
- not writing anything to that file is an error
"""
if os.path.isabs(relative_path):
raise ValueError('%s must be a relative ... | 0.002375 |
def _appendstore(self, store):
"""Join another store on to the end of this one."""
if not store.bitlength:
return
# Set new array offset to the number of bits in the final byte of current array.
store = offsetcopy(store, (self.offset + self.bitlength) % 8)
if store.of... | 0.004155 |
def block_create(
self,
type,
account,
wallet=None,
representative=None,
key=None,
destination=None,
amount=None,
balance=None,
previous=None,
source=None,
work=None,
):
"""
Creates a json representations... | 0.005167 |
def to_pycode(self):
"""Create a python code object from the more abstract
codetransfomer.Code object.
Returns
-------
co : CodeType
The python code object.
"""
consts = self.consts
names = self.names
varnames = self.varnames
f... | 0.000606 |
def render_workflow_html_template(filename, subtemplate, filelists, **kwargs):
""" Writes a template given inputs from the workflow generator. Takes
a list of tuples. Each tuple is a pycbc File object. Also the name of the
subtemplate to render and the filename of the output.
"""
dirnam = os.path.d... | 0.005098 |
def respond(self):
"""Call the gateway and write its iterable output."""
mrbs = self.server.max_request_body_size
if self.chunked_read:
self.rfile = ChunkedRFile(self.conn.rfile, mrbs)
else:
cl = int(self.inheaders.get(b'Content-Length', 0))
if mrbs an... | 0.002281 |
async def update_notifications(self, on_match_open: bool = None, on_tournament_end: bool = None):
""" update participants notifications for this tournament
|methcoro|
Args:
on_match_open: Email registered Challonge participants when matches open up for them
on_tournamen... | 0.007075 |
def show_message(self, c_attack, c_defend, result, dmg, print_console='Yes'):
"""
function to wrap the display of the battle messages
"""
perc_health_att = '[' + str(round((c_attack.stats['Health']*100) / c_attack.stats['max_health'] )) + '%]'
perc_health_def = '[' + str(round((c... | 0.015152 |
def calculate_input(self, buffer):
"""
Calculate how many keystrokes were used in triggering this folder (if applicable).
"""
if TriggerMode.ABBREVIATION in self.modes and self.backspace:
if self._should_trigger_abbreviation(buffer):
if self.immediate:
... | 0.005085 |
def experiment(self, key, values):
"""Populate the ``experiment`` key.
Also populates the ``legacy_name``, the ``accelerator``, and the
``institutions`` keys through side effects.
"""
experiment = self.get('experiment', {})
legacy_name = self.get('legacy_name', '')
accelerator = self.get('a... | 0.000806 |
def get_task_list(self, since='', task_types='', task_status=''):
"""
invokes TouchWorksMagicConstants.ACTION_GET_TASK_LIST action
:param since - If given a datetime, retrieves only tasks created (or last modified)
after that date and time. Defaults to 1/1/1900.
:param task_s... | 0.003636 |
def compilers(self):
"""The list of compilers used to build asset."""
return [self.environment.compilers.get(e) for e in self.compiler_extensions] | 0.018519 |
def safe_remove_file(filename, app):
"""
Removes a given resource file from builder resources.
Needed mostly during test, if multiple sphinx-build are started.
During these tests js/cass-files are not cleaned, so a css_file from run A is still registered in run B.
:param filename: filename to remov... | 0.004684 |
def vinet_v_single(p, v0, k0, k0p, min_strain=0.01):
"""
find volume at given pressure using brenth in scipy.optimize
this is for single p value, not vectorized
:param p: pressure in GPa
:param v0: unit-cell volume in A^3 at 1 bar
:param k0: bulk modulus at reference conditions
:param k0p: ... | 0.00141 |
def chebi(name=None, identifier=None) -> Abundance:
"""Build a ChEBI abundance node."""
return Abundance(namespace='CHEBI', name=name, identifier=identifier) | 0.006061 |
def download_file(p_realm, p_url, p_op_file, p_username, p_password):
"""
Currently not working...
# https://docs.python.org/3/library/urllib.request.html#examples
# Create an OpenerDirector with support for Basic HTTP Authentication...
"""
auth_handler = urllib.request.HTTPBasicAuthHandler()
... | 0.001279 |
def to_df(figure):
"""
Extracts the data from a Plotly Figure
Parameters
----------
figure : plotly_figure
Figure from which data will be
extracted
Returns a DataFrame or list of DataFrame
"""
dfs=[]
for trace in figure['data']:
if '... | 0.020678 |
def dcos_version():
"""Return the version of the running cluster.
:return: DC/OS cluster version as a string
"""
url = _gen_url('dcos-metadata/dcos-version.json')
response = dcos.http.request('get', url)
if response.status_code == 200:
return response.json()['version']
else:
... | 0.003012 |
def create_from_binary(cls, ignore_signature_check, binary_view):
'''Creates a new object MFTHeader from a binary stream. The binary
stream can be represented by a byte string, bytearray or a memoryview of the
bytearray.
Args:
binary_view (memoryview of bytearray) - A binary... | 0.011086 |
def vol(self, gain, gain_type='amplitude', limiter_gain=None):
'''Apply an amplification or an attenuation to the audio signal.
Parameters
----------
gain : float
Interpreted according to the given `gain_type`.
If `gain_type' = 'amplitude', `gain' is a positive a... | 0.000886 |
def filter(self, filter):
"""Filter entries by calling function or applying regex."""
if hasattr(filter, '__call__'):
return [entry for entry in self.entries if filter(entry)]
else:
pattern = re.compile(filter, re.IGNORECASE)
return [entry for entry in self.en... | 0.005714 |
def get_compressed_filename(self, filename):
"""If the given filename should be compressed, returns the
compressed filename.
A file can be compressed if:
- It is a whitelisted extension
- The compressed file does not exist
- The compressed file exists by is older than t... | 0.001896 |
def create_key_file(service, key):
"""Create a file containing key."""
keyfile = _keyfile_path(service)
if os.path.exists(keyfile):
log('Keyfile exists at %s.' % keyfile, level=WARNING)
return
with open(keyfile, 'w') as fd:
fd.write(key)
log('Created new keyfile at %s.' % k... | 0.00295 |
def front(self, *fields):
'''Return the front pair of the structure'''
ts = self.irange(0, 0, fields=fields)
if ts:
return ts.start(), ts[0] | 0.011111 |
def memoize(f):
"""Cache value returned by the function."""
@wraps(f)
def w(*args, **kw):
memoize.mem[f] = v = f(*args, **kw)
return v
return w | 0.005714 |
def altaz(self, temperature_C=None, pressure_mbar='standard'):
"""Compute (alt, az, distance) relative to the observer's horizon
The altitude returned is an `Angle` in degrees above the
horizon, while the azimuth is the compass direction in degrees
with north being 0 degrees and east be... | 0.004292 |
def _track_class_field(cls, field):
""" Track a field on the current model """
if '__' in field:
_track_class_related_field(cls, field)
return
# Will raise FieldDoesNotExist if there is an error
cls._meta.get_field(field)
# Detect m2m fields changes
if isinstance(cls._meta.get_fi... | 0.002008 |
def make_workspace(measurement, channel=None, name=None, silence=False):
"""
Create a workspace containing the model for a measurement
If `channel` is None then include all channels in the model
If `silence` is True, then silence HistFactory's output on
stdout and stderr.
"""
context = sil... | 0.001138 |
def dispatch_to_extension_op(op, left, right):
"""
Assume that left or right is a Series backed by an ExtensionArray,
apply the operator defined by op.
"""
# The op calls will raise TypeError if the op is not defined
# on the ExtensionArray
# unbox Series and Index to arrays
if isinsta... | 0.001181 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.