text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def bind(self, family, type, proto=0):
"""Create (or recreate) the actual socket object."""
self.socket = sockets.Socket(family, type, proto)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.setblocking(0)
#~ self.socket.setsockopt(socket.SOL_SOCKET, socket.TCP_NODE... | 0.005479 |
def get_seconds_until_next_day(now=None):
"""
Returns the number of seconds until the next day (utc midnight). This is the long-term rate limit used by Strava.
:param now: A (utc) timestamp
:type now: arrow.arrow.Arrow
:return: the number of seconds until next day, as int
"""
if now is None:... | 0.005102 |
def help(self):
"""Display command usage information."""
if self.params:
command = self.params.pop().lstrip('-')
if command in self.command.documentation:
(aliases, doc) = self.command.documentation[command]
(synopsis, body) = self._split_docstri... | 0.001947 |
def assistant_initiation_actions(self):
"""
Access the assistant_initiation_actions
:returns: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsList
:rtype: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantIniti... | 0.007911 |
def add_r_ending_to_syllable(last_syllable: str, is_first=True) -> str:
"""
Adds an the -r ending to the last syllable of an Old Norse word.
In some cases, it really adds an -r. In other cases, it on doubles the last character or left the syllable
unchanged.
>>> add_r_ending_to_syllable("arm", True... | 0.001821 |
def from_config(cls, cp, model, nprocesses=1, use_mpi=False):
"""Loads the sampler from the given config file."""
section = "sampler"
# check name
assert cp.get(section, "name") == cls.name, (
"name in section [sampler] must match mine")
# get the number of walkers to... | 0.001682 |
def _int_growth(z, **cosmo):
""" Returns integral of the linear growth factor from z=200 to z=z """
zmax = 200
if hasattr(z, "__len__"):
for zval in z:
assert(zval < zmax)
else:
assert(z < zmax)
y, yerr = scipy.integrate.quad(
lambda z: (1 + z)/(cosmo['omega_M_... | 0.002336 |
def standardize_snps(G):
r"""
Standardize variantes.
Parameters
----------
G : (`n_inds`, `n_snps`) array
Genetic data
Returns
-------
G_out : standardized array
"""
mean = G.mean(0)
std = G.std(0)
return (G - mean) / std | 0.003401 |
def get_dates_in_period(start=None, top=None, step=1, step_dict={}):
"""Return a list of dates from the `start` to `top`."""
delta = relativedelta(**step_dict) if step_dict else timedelta(days=step)
start = start or datetime.today()
top = top or start + delta
dates = []
current = start
whi... | 0.002439 |
def xml(self, fn=None, src='word/document.xml', XMLClass=XML, **params):
"return the src with the given transformation applied, if any."
if src in self.xml_cache: return self.xml_cache[src]
if src not in self.zipfile.namelist(): return
x = XMLClass(
fn=fn or (self.fn and ... | 0.010965 |
def simple_tokenize(name):
"""Simple tokenizer function to be used with the normalizers."""
last_names, first_names = name.split(',')
last_names = _RE_NAME_TOKEN_SEPARATOR.split(last_names)
first_names = _RE_NAME_TOKEN_SEPARATOR.split(first_names)
first_names = [NameToken(n) if len(n) > 1 else Name... | 0.001776 |
def configure_website(self, suffix, error_key='', headers=None):
"""
Configure this bucket to act as a website
:type suffix: str
:param suffix: Suffix that is appended to a request that is for a
"directory" on the website endpoint (e.g. if the suffix
... | 0.001398 |
def tree2doe(str1):
"""tree2doe"""
retstuff = makedoedict(str1)
ddict = makedoetree(retstuff[0], retstuff[1])
ddict = retstuff[0]
retstuff[1] = {}# don't need it anymore
str1 = ''#just re-using it
l1list = list(ddict.keys())
l1list.sort()
for i in range(0, len(l1list)):
str1... | 0.005772 |
def connections(request, edges):
"""
Plot a force-directed graph based on the edges provided
"""
edge_list, node_list = parse.graph_definition(edges)
data = {'nodes': json.dumps(node_list), 'edges': json.dumps(edge_list)}
return render_to_response('miner/connections.html', data) | 0.0033 |
def getSubgraphList(self, parent_name):
"""Returns list of names of subgraphs for Root Graph with name parent_name.
@param parent_name: Name of Root Graph.
@return: List of subgraph names.
"""
if not self.isMultigraph:
raise AttributeError... | 0.009934 |
def create_hdf_file(self):
"""
:return: h5py DataSet
"""
mode = 'w'
if not self._overwrite and os.path.exists(self._fname):
mode = 'a'
self._hdf_file = h5py.File(self._fname, mode)
if self._hdf_basepath == '/':
self._group = self._hdf_fil... | 0.004831 |
def copy(self):
"""
Deepcopy the parameter (with a new uniqueid). All other tags will remain
the same... so some other tag should be changed before attaching back to
a ParameterSet or Bundle.
:return: the copied :class:`Parameter` object
"""
s = self.to_json()
... | 0.008741 |
def make_colormap(seq, name="CustomMap", plot=False):
"""Generate a LinearSegmentedColormap.
Parameters
----------
seq : list of tuples
A sequence of floats and RGB-tuples. The floats should be increasing
and in the interval (0,1).
name : string (optional)
A name for the col... | 0.000895 |
def nonstoichiometric_symmetrized_slab(self, init_slab, tol=1e-3):
"""
This method checks whether or not the two surfaces of the slab are
equivalent. If the point group of the slab has an inversion symmetry (
ie. belong to one of the Laue groups), then it is assumed that the
sur... | 0.001824 |
def run(*args):
"""Load given `envfile` and run `command` with `params`"""
if not args:
args = sys.argv[1:]
if len(args) < 2:
print('Usage: runenv <envfile> <command> <params>')
sys.exit(0)
os.environ.update(create_env(args[0]))
os.environ['_RUNENV_WRAPPED'] = '1'
runna... | 0.001289 |
def translate_args(self, mu, k_agg, return_p=False):
"""%(super)s
The keyword argument return_p computes the p values used to define the
the truncated negative binomial
"""
if return_p:
return nbinom_ztrunc_p(mu, k_agg), k_agg
else:
return mu, k_a... | 0.006211 |
def get_function(fn_name):
"""Retrieve the function defined by the function_name.
Arguments:
fn_name: specification of the type module:function_name.
"""
module_name, callable_name = fn_name.split(':')
current = globals()
if not callable_name:
callable_name = module_name
else... | 0.001271 |
def trace_module(no_print=True):
"""Trace my_module exceptions."""
pwd = os.path.dirname(__file__)
script_name = os.path.join(pwd, "test_my_module.py")
with pexdoc.ExDocCxt() as exdoc_obj:
if pytest.main(["-s", "-vv", "-x", "{0}".format(script_name)]):
raise RuntimeError("Tracing did... | 0.001321 |
def _check_normalization(self):
"""Checks, if the TimeSeries is normalized.
:return: Returns :py:const:`True` if all data entries of the TimeSeries have an equal temporal
distance, :py:const:`False` otherwise.
"""
lastDistance = None
distance = None
fo... | 0.006061 |
def parse_job(self, run_method, options):
"""
Generates and returns a job object with the following:
* a run method, as defined in the readme
* a list of posix-like arguments
* a dictionary of data
* templates: a dict-like interface of (template_name, template_body) pair... | 0.003138 |
def detect(self, G):
"""Detect a single core-periphery pair.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> lrc = cp.LowRankCore()
>>> lrc.detect(G)
... | 0.060948 |
def connectSubsystem(connection, protocol, subsystem):
"""Connect a Protocol to a ssh subsystem channel
"""
deferred = connectSession(connection, protocol)
@deferred.addCallback
def requestSubsystem(session):
return session.requestSubsystem(subsystem)
return deferred | 0.006689 |
def open_console(self, client=None):
"""Open an IPython console for the given client or the current one."""
if not client:
client = self.get_current_client()
if self.ipyconsole is not None:
kernel_id = client.get_kernel_id()
if not kernel_id:
... | 0.002283 |
def earwax(self):
'''Makes audio easier to listen to on headphones. Adds ‘cues’ to 44.1kHz
stereo audio so that when listened to on headphones the stereo image is
moved from inside your head (standard for headphones) to outside and in
front of the listener (standard for speakers).
... | 0.00566 |
def _check_filter_specific_tag(self, specific_tag: list):
"""Check if specific_tag parameter is valid.
:param list specific_tag: list of specific tag to check
"""
if isinstance(specific_tag, list):
if len(specific_tag) > 0:
specific_tag = ",".join(specific_ta... | 0.004193 |
def ngram_counts(args, parser):
"""Outputs the results of performing a counts query."""
store = utils.get_data_store(args)
corpus = utils.get_corpus(args)
catalogue = utils.get_catalogue(args)
store.validate(corpus, catalogue)
store.counts(catalogue, sys.stdout) | 0.003497 |
def get_next_batch(self):
"""
This method is called from the manager. It must return a list or a generator
of BaseRecord objects.
When it has nothing else to read, it must set class variable "finished" to True.
"""
if self.iterator is None:
self.iterator = sel... | 0.008 |
def get_project_by_id(session, project_id, project_details=None, user_details=None):
"""
Get a single project by ID
"""
# GET /api/projects/0.1/projects/<int:project_id>
query = {}
if project_details:
query.update(project_details)
if user_details:
query.update(user_details)
... | 0.00277 |
def i2c_master_write_read(self, i2c_address, data, length):
"""Make an I2C write/read access.
First an I2C write access is issued. No stop condition will be
generated. Instead the read access begins with a repeated start.
This method is useful for accessing most addressable I2C devices... | 0.003221 |
def format_subject(subject):
"""
Prepends 'Re:' to the subject. To avoid multiple 'Re:'s
a counter is added.
NOTE: Currently unused. First step to fix Issue #48.
FIXME: Any hints how to make this i18n aware are very welcome.
"""
subject_prefix_re = r'^Re\[(\d*)\]:\ '
m = re.match(subjec... | 0.002418 |
def on_site(self, site_id=None):
"""Return a :class:`QuerySet` of pages that are published on the site
defined by the ``SITE_ID`` setting.
:param site_id: specify the id of the site object to filter with.
"""
if settings.PAGE_USE_SITE_ID:
if not site_id:
... | 0.004739 |
def formfield(self, **kwargs):
"""
:returns: A :class:`~osm_field.forms.OSMFormField` with a
:class:`~osm_field.widgets.OSMWidget`.
"""
widget_kwargs = {
'lat_field': self.latitude_field_name,
'lon_field': self.longitude_field_name,
}
... | 0.003221 |
def remove(self, document_id, namespace, timestamp):
"""Removes documents from Solr
The input is a python dictionary that represents a mongo document.
"""
self.solr.delete(id=u(document_id),
commit=(self.auto_commit_interval == 0)) | 0.00692 |
def get_or_create_direct_channel(cls, initiator_key, receiver_key):
"""
Creates a direct messaging channel between two user
Args:
initiator: User, who want's to make first contact
receiver: User, other party
Returns:
(Channel, receiver_name)
... | 0.003091 |
def make_gtp_instance(load_file, cgos_mode=False, kgs_mode=False,
minigui_mode=False):
"""Takes a path to model files and set up a GTP engine instance."""
n = DualNetwork(load_file)
if cgos_mode:
player = CGOSPlayer(network=n, seconds_per_move=5, timed_match=True,
... | 0.001961 |
def transform(self, X):
"""Performs predictions blending using the trained weights.
Args:
X (array-like): Predictions of different models.
Returns: dict with blended predictions (key is 'y_pred').
"""
assert np.shape(X)[0] == len(self._weights), (
'Blendi... | 0.005398 |
def update(self):
"""Update the ports list."""
if self.input_method == 'local':
# Only refresh:
# * if there is not other scanning thread
# * every refresh seconds (define in the configuration file)
if self._thread is None:
thread_is_runnin... | 0.002179 |
def function_path(func):
"""
This will return the path to the calling function
:param func:
:return:
"""
if getattr(func, 'func_code', None):
return func.__code__.co_filename.replace('\\', '/')
else:
return func.__code__.co_filename.replace('\\', '/') | 0.00339 |
def Softmax(x, params, axis=-1, **kwargs):
"""Apply softmax to x: exponentiate and normalize along the given axis."""
del params, kwargs
return np.exp(x - backend.logsumexp(x, axis, keepdims=True)) | 0.019704 |
def foldOneLine(outbuf, input, lineLength = 75):
"""
Folding line procedure that ensures multi-byte utf-8 sequences are not broken across lines
TO-DO: This all seems odd. Is it still needed, especially in python3?
"""
if len(input) < lineLength:
# Optimize for unfolded line case
tr... | 0.002725 |
def batch(self, requests):
"""
Make a batch request.
:param requests: A list of dictionaries with keys 'method', 'relative_url' and optionally 'body'.
Yields a list of responses and/or exceptions.
"""
for request in requests:
if 'body' in request:
... | 0.002471 |
def make_response(response):
"""Make response tuple
Potential features to be added
- Parameters validation
"""
if isinstance(response, unicode) or \
isinstance(response, str):
response = (response, 'text/html')
return response | 0.00365 |
def set_locale(new_locale, lc_var=locale.LC_ALL):
"""
Context manager for temporarily setting a locale.
Parameters
----------
new_locale : str or tuple
A string of the form <language_country>.<encoding>. For example to set
the current locale to US English with a UTF8 encoding, you w... | 0.001008 |
def _get_styles(self, style_urls, asset_url_path):
"""
Gets the content of the given list of style URLs and
inlines assets.
"""
styles = []
for style_url in style_urls:
urls_inline = STYLE_ASSET_URLS_INLINE_FORMAT.format(
asset_url_path.rstrip(... | 0.003899 |
def basic_info(user, keys):
"""Prints a table of basic user information"""
table = formatting.KeyValueTable(['Title', 'Basic Information'])
table.align['Title'] = 'r'
table.align['Basic Information'] = 'l'
table.add_row(['Id', user.get('id', '-')])
table.add_row(['Username', user.get('username... | 0.003279 |
def _lock(self, url: str, name: str, hash_: str):
"""
Add details of the files downloaded to _new_lock so they can be saved to the lock file.
Also remove path from _stale_files, whatever remains at the end therefore is stale and can be deleted.
"""
self._new_lock.append({
... | 0.00905 |
def getDependencies(self, retracted=False):
"""
Return a list of siblings who we depend on to calculate our result.
:param retracted: If false retracted/rejected dependencies are dismissed
:type retracted: bool
:return: Analyses the current analysis depends on
:rtype: lis... | 0.003619 |
def _key_digest(self, secret_key):
'''
a helper method for creating a base 64 encoded secret key and digest
:param secret_key: string with key to encrypt/decrypt data
:return: string with base64 key, string with base64 digest
'''
from hashlib import ... | 0.0096 |
def prepare_to_run(self, clock, period_count):
"""
Prepare the activity for execution.
:param clock: The clock containing the execution start time and
execution period information.
:param period_count: The total amount of periods this activity will be
requested to be... | 0.004065 |
def getPreviewURL(self, CorpNum, ReceiptNum, UserID):
""" 팩스 발신번호 목록 확인
args
CorpNum : 팝빌회원 사업자번호
UserID : 팝빌회원 아이디
return
처리결과. list of SenderNumber
raise
PopbillException
"""
return self._httpge... | 0.005376 |
def ssn(self, dob=None, gender=None):
"""
Returns 11 character Norwegian personal identity code (Fødselsnummer).
A Norwegian personal identity code consists of 11 digits, without any
whitespace or other delimiters. The form is DDMMYYIIICC, where III is
a serial number separating... | 0.001239 |
def set_prefix(self, prefix=None):
"""Set prefix to use as a namespace for item lookup.
A dot (.) will be automatically added to the given string.
:param prefix: Prefix, or None to unset
:return: None
"""
if prefix is None:
self._pfx = None
else:
... | 0.005602 |
def active_trail_nodes(self, variables, observed=None):
"""
Returns a dictionary with the given variables as keys and all the nodes reachable
from that respective variable as values.
Parameters
----------
variables: str or array like
variables whose active tra... | 0.002099 |
def enable_hardware_breakpoint(self, dwThreadId, address):
"""
Enables the hardware breakpoint at the given address.
@see:
L{define_hardware_breakpoint},
L{has_hardware_breakpoint},
L{get_hardware_breakpoint},
L{enable_one_shot_hardware_breakpoint... | 0.003311 |
def update_additional_charge(self, *, recurring_billing_id, description, plan_value, plan_tax, plan_tax_return_base,
currency):
"""
Updates the information from an additional charge in an invoice.
Args:
recurring_billing_id: Identifier of the additio... | 0.003953 |
def sample_uniform_initial_state(parameter,
return_constrained=True,
init_sample_shape=(),
seed=None):
"""Initialize from a uniform [-2, 2] distribution in unconstrained space.
Args:
parameter: `sts.Parameter` na... | 0.004051 |
def split(x, split_dim, num_or_size_splits, name=None):
"""Like tf.split.
Args:
x: a Tensor
split_dim: a Dimension in x.shape.dims
num_or_size_splits: either an integer dividing split_dim.size
or a list of integers adding up to split_dim.size
name: an optional string
Returns:
a list of... | 0.007282 |
def logregularize(self, epsilon=2**-1074):
"""
Find bins in the denominator that are 0, and set them to 1,
while setting the corresponding bin in the numerator to
float epsilon. This has the effect of allowing the
logarithm of the ratio array to be evaluated without error.
... | 0.004184 |
def list_elasticache(region, filter_by_kwargs):
"""List all ElastiCache Clusters."""
conn = boto.elasticache.connect_to_region(region)
req = conn.describe_cache_clusters()
data = req["DescribeCacheClustersResponse"]["DescribeCacheClustersResult"]["CacheClusters"]
if filter_by_kwargs:
cluster... | 0.005894 |
def JGE(cpu, target):
"""
Jumps short if greater or equal.
:param cpu: current CPU.
:param target: destination operand.
"""
cpu.PC = Operators.ITEBV(cpu.address_bit_size, (cpu.SF == cpu.OF), target.read(), cpu.PC) | 0.01145 |
def size(f, unit='B', fileStore=None):
"""
Returns the size of a file in bytes.
:param f: Filename
:param unit: Return the byte size in these units (gigabytes, etc.).
:return:
"""
divisor = return_bytes(unit)
fileID = process_infile(f, fileStore)[0]
return fileID.size / divisor | 0.003175 |
def pivot_wavelength(self):
"""Get the bandpass' pivot wavelength.
Unlike calc_pivot_wavelength(), this function will use a cached
value if available.
"""
wl = self.registry._pivot_wavelengths.get((self.telescope, self.band))
if wl is not None:
return wl
... | 0.004386 |
def format_dict(self, delim=':', qu="'"):
"""
Prepares the data as a dictionary with column headers
TODO - get variable names of data[] as strings for hdr
"""
res = 'name' + delim + qu + self.name + qu + ','
for num, d in enumerate(self.data):
res += 'col' + s... | 0.005277 |
def validate(self, folder, cleanup=False, validate_folder=True):
''' validate is the entrypoint to all validation, for
a folder, config, or url. If a URL is found, it is
cloned and cleaned up.
:param validate_folder: ensures the folder name (github repo)
... | 0.003268 |
def return_port(port):
"""Return a port that is no longer being used so it can be reused."""
if port in _random_ports:
_random_ports.remove(port)
elif port in _owned_ports:
_owned_ports.remove(port)
_free_ports.add(port)
elif port in _free_ports:
logging.info("Returning a... | 0.002096 |
def _add_ubridge_ethernet_connection(self, bridge_name, ethernet_interface, block_host_traffic=False):
"""
Creates a connection with an Ethernet interface in uBridge.
:param bridge_name: bridge name in uBridge
:param ethernet_interface: Ethernet interface name
:param block_host_... | 0.005637 |
def _get_args_for_reloading():
"""Returns the executable."""
rv = [sys.executable]
main_module = sys.modules["__main__"]
mod_spec = getattr(main_module, "__spec__", None)
if mod_spec:
# Parent exe was launched as a module rather than a script
rv.extend(["-m", mod_spec.name])
... | 0.002331 |
def chunk(iterable, size):
"""
chunk('ABCDEFG', 3) --> ABC DEF G
"""
# TODO: only used in gui.mainwindow(deprecated)
iterator = iter(iterable)
while size:
result = []
try:
for i in range(size):
elem = next(iterator)
result.append(elem)
... | 0.002179 |
def validate_input(self):
"""Validate the input before saving a scenario.
Those validations are:
1. self.exposure_layer must be not None
2. self.hazard_layer must be not None
3. self.function_id is not an empty string or None
"""
self.exposure_layer = layer_from_... | 0.00185 |
def show(self, dump=False, indent=3, lvl="", label_lvl=""):
"""
Prints or returns (when "dump" is true) a hierarchical view of the
packet.
:param dump: determine if it prints or returns the string value
:param int indent: the size of indentation for each layer
:param str... | 0.003407 |
def create_auth_token(sender, instance, raw, created, **kwargs):
"""Create token when a user is created (from rest_framework).
"""
if not raw:
if created:
sender.objects.create(user=instance) | 0.004484 |
def _parse_geo_location(d):
"""
Parse one geo location
:param d:
:return:
"""
d2 = OrderedDict()
filt = {}
d2['type'] = 'Feature'
# If the necessary keys are missing, put in placeholders so there's no KeyErrors.
for key in EXCEL_GEO:
if key not in d:
d[key] = ... | 0.005405 |
def main(args=None, stdout=sys.stdout):
"""Main method for toil-cwl-runner."""
cwllogger.removeHandler(defaultStreamHandler)
config = Config()
config.cwl = True
parser = argparse.ArgumentParser()
addOptions(parser, config)
parser.add_argument("cwltool", type=str)
parser.add_argument("cwl... | 0.001006 |
def http_response(self, request):
'''Return a :class:`.WsgiResponse` or a :class:`~asyncio.Future`.
This method asynchronously wait for :meth:`stream` and subsequently
returns a :class:`.WsgiResponse`.
'''
content_types = request.content_types
if not content_types or sel... | 0.003063 |
def get_weakref(func):
"""Get a weak reference to bound or unbound `func`.
If `func` is unbound (i.e. has no __self__ attr) get a weakref.ref,
otherwise get a wrapper that simulates weakref.ref.
"""
if func is None:
raise ValueError
if not hasattr(func, '__self__'):
return weakr... | 0.002778 |
def predict(self, control=None, control_matrix=None,
process_matrix=None, process_covariance=None):
"""
Predict the next *a priori* state mean and covariance given the last
posterior. As a special case the first call to this method will
initialise the posterior and prior ... | 0.001807 |
def __get_header_with_auth(self):
"""
This private method returns the HTTP heder filled with the Authorization information with the user token.
The token validity is monitored whenever this function is called, so according to the swagger page of TheTVDB
(https://api.thetvdb.com/swagger) ... | 0.007657 |
def unapply_all(self, force=False):
""" Unapply all patches """
self._check(force)
for patch in reversed(self.db.applied_patches()):
self._unapply_patch(patch)
self.db.save()
self.unapplied(self.db.top_patch()) | 0.007547 |
def bokeh_draw_court(figure, line_color='gray', line_width=1):
"""Returns a figure with the basketball court lines drawn onto it
This function draws a court based on the x and y-axis values that the NBA
stats API provides for the shot chart data. For example the center of the
hoop is located at the (0... | 0.000334 |
def expand_composites (properties):
""" Expand all composite properties in the set so that all components
are explicitly expressed.
"""
if __debug__:
from .property import Property
assert is_iterable_typed(properties, Property)
explicit_features = set(p.feature for p in propertie... | 0.009085 |
def set_(key, value, setting=None, conf_file=_DEFAULT_CONF):
'''
Set a new value for a specific configuration line.
:param str key: The command or block to configure.
:param str value: The command value or command of the block specified by the key parameter.
:param str setting: The command value fo... | 0.001274 |
def _write(self, dap_index, transfer_count,
transfer_request, transfer_data):
"""
Write one or more commands
"""
assert dap_index == 0 # dap index currently unsupported
assert isinstance(transfer_count, six.integer_types)
assert isinstance(transfer_request... | 0.002404 |
def update(self):
"""Update the measured light level in lux."""
if not self._continuous_sampling \
or self._light_level < 0 \
or self._operation_mode != self._mode:
self._reset()
self._set_mode(self._operation_mode)
self._wait_for_resul... | 0.004515 |
def update_event_status(event, status):
'''Update the status of a particular event in the database.
'''
dbs = db.get_session()
dbs.query(db.RecordedEvent).filter(db.RecordedEvent.start == event.start)\
.update({'status': status})
event.status = status
dbs.commit() | 0.003135 |
def download(self, localfile: str, remotefile: str, overwrite: bool = True, **kwargs):
"""
This method downloads a remote file from the SAS servers file system.
localfile - path to the local file to create or overwrite
remotefile - path to remote file tp dpwnload
overwrite - overwrite th... | 0.02697 |
def merge_from_dict(self, dct, lists_only=False):
"""
Merges a dictionary into this configuration object.
See :meth:`ConfigurationObject.merge` for details.
:param dct: Values to update the ConfigurationObject with.
:type dct: dict
:param lists_only: Ignore single-value... | 0.003543 |
def _call(self, dx):
"""Return ``self(x)``."""
x = self.point
dx_norm = dx.norm()
if dx_norm == 0:
return 0
scaled_dx = dx * (self.step / dx_norm)
if self.method == 'backward':
dAdx = self.operator(x) - self.operator(x - scaled_dx)
elif ... | 0.002994 |
def do_insertions(insertions, tokens):
"""
Helper for lexers which must combine the results of several
sublexers.
``insertions`` is a list of ``(index, itokens)`` pairs.
Each ``itokens`` iterable should be inserted at position
``index`` into the token stream given by the ``tokens``
argument... | 0.000543 |
def asdict(self) -> Dict[str, Union[Dict, Union[str, Dict]]]:
"""Return a dictionary describing the method.
This can be used to dump the information into a JSON file.
"""
return {
"service": self.service.name,
**self.signature.serialize(),
} | 0.006536 |
def forwast_autodownload(FORWAST_URL):
"""
Autodownloader for forwast database package for brightway. Used by `lcopt_bw2_forwast_setup` to get the database data. Not designed to be used on its own
"""
dirpath = tempfile.mkdtemp()
r = requests.get(FORWAST_URL)
z = zipfile.ZipFile(io.BytesI... | 0.007246 |
def goto_step(self, inst: InstanceNode) -> InstanceNode:
"""Return member instance of `inst` addressed by the receiver.
Args:
inst: Current instance.
"""
try:
return inst._entry(
inst.value.index(self.parse_value(inst.schema_node)))
except... | 0.004292 |
def map_method(method,object_list,*argseq,**kw):
"""map_method(method,object_list,*args,**kw) -> list
Return a list of the results of applying the methods to the items of the
argument sequence(s). If more than one sequence is given, the method is
called with an argument list consisting of the correspo... | 0.007722 |
def subfield_get(self, obj, type=None):
"""
Verbatim copy from:
https://github.com/django/django/blob/1.9.13/django/db/models/fields/subclassing.py#L38
"""
if obj is None:
return self
return obj.__dict__[self.field.name] | 0.003968 |
def __vCmdSetCamExposureMode(self, args):
'''ToDo: Validate CAM number and Valid Mode Values'''
if len(args) == 1:
for cam in self.camera_list:
cam.boSetExposureMode(args[0])
elif len(args) == 2:
cam = self.camera_list[int(args[1])]
cam.boSetEx... | 0.007767 |
def safe_temp_edit(filename):
"""Safely modify a file within context that automatically reverts any changes afterwards
The file mutatation occurs in place. The file is backed up in a temporary file before edits
occur and when the context is closed, the mutated file is discarded and replaced with the backup.
W... | 0.015949 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.