code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
ret = False
# we will only use the primary key if it hasn't been modified
pk = None
if self.schema.pk.name not in self.modified_fields:
pk = self.pk
if pk:
ret = self.update()
else:
ret = self.insert()
return ret | def save(self) | persist the fields in this object into the db, this will update if _id is set, otherwise
it will insert
see also -- .insert(), .update() | 5.518147 | 4.675807 | 1.180149 |
ret = False
q = self.query
pk = self.pk
if pk:
pk_name = self.schema.pk.name
self.query.is_field(pk_name, pk).delete()
setattr(self, pk_name, None)
# mark all the fields that still exist as modified
self.reset_modified... | def delete(self) | delete the object from the db if pk is set | 4.92226 | 4.559365 | 1.079593 |
self.modified_fields = set()
# compensate for us not having knowledge of certain fields changing
for field_name, field in self.schema.normal_fields.items():
if isinstance(field, ObjectField):
self.modified_fields.add(field_name) | def reset_modified(self) | reset field modification tracking
this is handy for when you are loading a new Orm with the results from a query and
you don't want set() to do anything, you can Orm(**fields) and then orm.reset_modified() to
clear all the passed in fields from the modified list | 6.454761 | 5.967418 | 1.081667 |
modified_fields = set()
fields = self.make_dict(fields, fields_kwargs)
fields = self._modify(fields)
for field_name, field_val in fields.items():
in_schema = field_name in self.schema.fields
if in_schema:
setattr(self, field_name, field_va... | def modify(self, fields=None, **fields_kwargs) | update the fields of this instance with the values in dict fields
this should rarely be messed with, if you would like to manipulate the
fields you should override _modify()
:param fields: dict, the fields in a dict
:param **fields_kwargs: dict, if you would like to pass the fields as ... | 3.056952 | 2.872727 | 1.064129 |
d = {}
for field_name, field in self.schema.normal_fields.items():
field_val = getattr(self, field_name, None)
field_val = field.jsonable(self, field_val)
if field_val is not None:
d[field_name] = field_val
return d | def jsonable(self, *args, **options) | return a public version of this instance that can be jsonified
Note that this does not return _id, _created, _updated, the reason why is
because lots of times you have a different name for _id (like if it is a
user object, then you might want to call it user_id instead of _id) and I
di... | 2.773097 | 2.744032 | 1.010592 |
# check image dimensions
image_header = hdu1[0].header
image_header_ = hdu2[0].header
#
naxis = image_header['naxis']
naxis_ = image_header_['naxis']
if naxis != naxis_:
raise ValueError('Incompatible NAXIS values: {}, {}'.format(
naxis, naxis_
))
naxis1... | def merge2images(hdu1, hdu2, debugplot) | Merge 2 EMIR images, averaging the common region.
Parameters
----------
hdu1 : HDUList object
Input image #1.
hdu2 : HDUList object
Input image #2.
debugplot : int
Determines whether intermediate computations and/or plots
are displayed. The valid codes are defined in... | 2.022757 | 1.997939 | 1.012422 |
inters = []
cs = dsnparse.parse_environs(dsn_env_name, parse_class=connection_class)
for c in cs:
inter = c.interface
set_interface(inter, c.name)
inters.append(inter)
return inters | def configure_environ(dsn_env_name='PROM_DSN', connection_class=DsnConnection) | configure interfaces based on environment variables
by default, when prom is imported, it will look for PROM_DSN, and PROM_DSN_N (where
N is 1 through infinity) in the environment, if it finds them, it will assume they
are dsn urls that prom understands and will configure db connections with them. If you
... | 6.941122 | 8.006957 | 0.866886 |
c = dsnparse.parse(dsn, parse_class=connection_class)
inter = c.interface
set_interface(inter, c.name)
return inter | def configure(dsn, connection_class=DsnConnection) | configure an interface to be used to query a backend
you use this function to configure an Interface using a dsn, then you can get
that interface using the get_interface() method
dsn -- string -- a properly formatted prom dsn, see DsnConnection for how to format the dsn | 10.998655 | 12.086741 | 0.909977 |
global interfaces
if not interface: raise ValueError('interface is empty')
# close down the interface before we discard it
if name in interfaces:
interfaces[name].close()
interfaces[name] = interface | def set_interface(interface, name='') | don't want to bother with a dsn? Use this method to make an interface available | 6.676614 | 6.565468 | 1.016929 |
yield ws
finally:
await ws.close() | async def open_websocket_server(sock, filter=None): # pylint: disable=W0622
ws = await create_websocket_server(sock, filter=filter)
try | A context manager which serves this websocket.
:param filter: an async callback which accepts the connection request
and returns a bool, or an explicit Accept/Reject message. | 13.941444 | 16.57922 | 0.840899 |
async def create_websocket_server(sock, filter=None): # pylint: disable=W0622
ws = Websocket()
await ws.start_server(sock, filter=filter)
return ws | A more low-level form of open_websocket_server.
You are responsible for closing this websocket. | null | null | null | |
return {f:v for f, v in self.fields.items() if not f.startswith('_')} | def normal_fields(self) | fields that aren't magic (eg, aren't _id, _created, _updated) | 4.914705 | 3.128212 | 1.571091 |
return {f:v for f, v in self.normal_fields.items() if v.required} | def required_fields(self) | The normal required fields (eg, no magic fields like _id are included) | 6.889053 | 4.222136 | 1.631651 |
return {f:v for f, v in self.fields.items() if f.startswith('_')} | def magic_fields(self) | the magic fields for the schema | 5.868443 | 5.041322 | 1.164068 |
if not index_name:
raise ValueError("index_name must have a value")
if index_name in self.indexes:
raise ValueError("index_name {} has already been defined on {}".format(
index_name, str(self.indexes[index_name].fields)
))
if not isins... | def set_index(self, index_name, index) | add an index to the schema
for the most part, you will use the __getattr__ method of adding indexes for a more fluid interface,
but you can use this if you want to get closer to the bare metal
index_name -- string -- the name of the index
index -- Index() -- an Index instance | 2.707899 | 2.652859 | 1.020747 |
if not hasattr(self, "_schema"):
ret = None
o = self._type
if isinstance(o, type):
ret = getattr(o, "schema", None)
elif isinstance(o, Schema):
ret = o
else:
module, klass = utils.get_objects(o... | def schema(self) | return the schema instance if this is reference to another table | 4.082687 | 3.792392 | 1.076547 |
try:
val = instance.__dict__[self.instance_field_name]
except KeyError as e:
#raise AttributeError(str(e))
val = None
return val | def fval(self, instance) | return the raw value that this property is holding internally for instance | 4.433514 | 4.063693 | 1.091006 |
if method not in self._available_methods:
raise ValueError('Unknown method: {0}'.format(method))
self._default_references[method] = reference | def set_default_reference(self, method, reference) | Set the default reference for a method.
:arg method: name of a method
:type method: :class:`str`
{reference} | 3.344226 | 3.802249 | 0.879539 |
if method not in self._available_methods:
raise ValueError('Unknown method: {0}'.format(method))
return self._default_references.get(method) | def get_default_reference(self, method) | Returns the default reference for a method.
:arg method: name of a method
:type method: :class:`str`
:return: reference
:rtype: :class:`Reference <pyxray.descriptor.Reference>` or :class:`str` | 3.588422 | 4.3674 | 0.821638 |
header = ['IUPAC', 'Siegbahn', 'Energy (eV)', 'Probability']
rows = []
for xraytransition in self.element_xray_transitions(element):
try:
iupac = self.xray_transition_notation(xraytransition, 'iupac')
except:
iupac = ''
... | def print_element_xray_transitions(self, element, file=sys.stdout, tabulate_kwargs=None) | Prints all x-ray transitions for an element, with their different
notations and energy.
{element}
:arg file: file for output, default to standard out | 1.971686 | 2.086485 | 0.94498 |
m = importlib.import_module(modulepath)
mpath = m.__file__
ret = set([m])
if "__init__." in mpath.lower():
mpath = os.path.dirname(mpath)
# https://docs.python.org/2/library/pkgutil.html#pkgutil.iter_modules
for module_info in pkgutil.iter_modules([mpath]):
sub... | def get_modules(modulepath) | return all found modules at modulepath (eg, foo.bar) including modulepath module | 2.663087 | 2.600706 | 1.023986 |
if isinstance(modulepath, ModuleType):
modules = get_modules(modulepath.__name__)
else:
modules = get_modules(modulepath)
ret = set()
for m in modules:
cs = inspect.getmembers(m, lambda v: inspect.isclass(v) and issubclass(v, parent_class))
for class_name, klass in ... | def get_subclasses(modulepath, parent_class) | given a module return all the parent_class subclasses that are found in
that module and any submodules.
:param modulepath: string, a path like foo.bar.che
:param parent_class: object, the class whose children you are looking for
:returns: set, all the found child classes in modulepath of parent_class | 2.57935 | 2.842088 | 0.907555 |
if orm_class in orm_classes: return
for field_name, field_val in orm_class.schema.fields.items():
if field_val.is_ref():
build_dump_order(field_val.schema.orm_class, orm_classes)
if orm_class not in orm_classes:
orm_classes.append(orm_class) | def build_dump_order(orm_class, orm_classes) | pass in an array, when you encounter a ref, call this method again with the array
when something has no more refs, then it gets appended to the array and returns, each
time something gets through the list they are added, but before they are added to the
list it is checked to see if it is already in the list... | 2.78167 | 2.814164 | 0.988453 |
ret = set()
try:
m = importlib.import_module(path)
except ImportError:
# we have a classpath
m, klass = get_objects(path)
if issubclass(klass, Orm):
ret.add(klass)
else:
ret.update(get_subclasses(m, Orm))
return ret | def get_orm_classes(path) | this will return prom.Orm classes found in the given path (classpath or modulepath) | 4.973095 | 4.206204 | 1.182324 |
table_map = get_table_map(paths)
for conn_name, conn_info in table_map.items():
inter = conn_info["interface"]
conn = inter.connection_config
table_names = conn_info["table_names"]
cmd = get_base_cmd("backup", inter, directory)
cmd.extend(table_names)
if d... | def main_dump(paths, directory, dry_run) | dump all or part of the prom data, currently only works on Postgres databases
basically just a wrapper around `dump backup` https://github.com/Jaymon/dump | 5.008123 | 5.121066 | 0.977945 |
inter = get_interface(conn_name)
conn = inter.connection_config
cmd = get_base_cmd("restore", inter, directory)
run_cmd(cmd) | def main_restore(directory, conn_name) | Restore your database dumped with the dump command
just a wrapper around `dump restore` https://github.com/Jaymon/dump | 8.624683 | 10.103925 | 0.853597 |
ret = {}
query_str = []
query_args = ['f', table_name]
# I had to brush up on my join knowledge while writing this query
# https://en.wikipedia.org/wiki/Join_(SQL)
#
# other helpful links
# https://wiki.postgresql.org/wiki/Retrieve_primary_key_co... | def _get_fields(self, table_name, **kwargs) | return all the fields for the given schema | 2.727194 | 2.714263 | 1.004764 |
ret = {}
query_str = []
query_str.append('SELECT')
query_str.append(' tbl.relname AS table_name, i.relname AS index_name, a.attname AS field_name,')
query_str.append(' ix.indkey AS index_order, a.attnum AS field_num')
query_str.append('FROM')
query_str.... | def _get_indexes(self, schema, **kwargs) | return all the indexes for the given schema | 2.182182 | 2.102825 | 1.037738 |
index_fields = []
for field_name in fields:
field = schema.fields[field_name]
if issubclass(field.type, basestring):
if field.options.get('ignore_case', False):
field_name = 'UPPER({})'.format(self._normalize_name(field_name))
... | def _set_index(self, schema, name, fields, **index_options) | NOTE -- we set the index name using <table_name>_<name> format since indexes have to have
a globally unique name in postgres
http://www.postgresql.org/docs/9.1/static/sql-createindex.html | 2.593766 | 2.421517 | 1.071133 |
try:
auth_info = verify_client(self.endpoint_context, request, auth)
except Exception as err:
msg = "Failed to verify client due to: {}".format(err)
logger.error(msg)
return self.error_cls(error="unauthorized_client",
... | def client_authentication(self, request, auth=None, **kwargs) | Deal with client authentication
:param request: The refresh access token request
:param auth: Client authentication information
:param kwargs: Extra keyword arguments
:return: dictionary containing client id, client authentication method
and possibly access token. | 3.026253 | 3.208458 | 0.943211 |
if 'state' in request:
try:
sinfo = self.endpoint_context.sdb[request['code']]
except KeyError:
logger.error('Code not present in SessionDB')
return self.error_cls(error="unauthorized_client")
else:
sta... | def _post_parse_request(self, request, client_id='', **kwargs) | This is where clients come to get their access tokens
:param request: The request
:param authn: Authentication info, comes from HTTP header
:returns: | 3.883475 | 3.992956 | 0.972581 |
kwargs.update(zip(self.meta_names, args))
# call super method
super(OutputRegistry, self).register(new_outputs, **kwargs) | def register(self, new_outputs, *args, **kwargs) | Register outputs and metadata.
* ``initial_value`` - used in dynamic calculations
* ``size`` - number of elements per timestep
* ``uncertainty`` - in percent of nominal value
* ``variance`` - dictionary of covariances, diagonal is square of
uncertianties, no units
* ``... | 6.263554 | 7.565339 | 0.827928 |
# lists of targets and sky frames
with obresult.frames[0].open() as baseimg:
# Initial checks
has_bpm_ext = 'BPM' in baseimg
self.logger.debug('images have BPM extension: %s', has_bpm_ext)
images_info = []
for f in obresult.frames:
... | def initial_classification(self, obresult, target_is_sky=False) | Classify input frames, | 5.160691 | 5.043309 | 1.023275 |
conf = CSUConf(barmodel)
conf.conf_f = hdr.get('CSUCONFF', 'UNKNOWN')
# Read CSUPOS and set position in model
# The bars
for idx in conf.bars:
key = "CSUP{}".format(idx)
# UNIT of CSUPOS?
# who knows
# set CSUPOS for BAR
# Using the model, this sets the... | def read_csu_2(barmodel, hdr) | Read CSU information and slits from header | 5.188095 | 5.07931 | 1.021417 |
conf = CSUConf(barmodel)
conf.set_state(hdr)
return conf | def read_csu_3(barmodel, hdr) | Read CSU information and slits from header | 9.311273 | 9.835355 | 0.946714 |
self.conf_f = hdr.get('CSUCONFF', 'UNKNOWN')
# Read CSUPOS and set position in model
# The bars
for idx in self.bars:
key = "CSUP{}".format(idx)
# UNIT is mm
# set CSUPOS for BAR
# Using the model, this sets the X,Y coordinate
... | def set_state(self, hdr) | Read CSU information and slits from header | 17.835865 | 14.576908 | 1.22357 |
# Slits.
# For the moment we will fuse only reference slits
# clean existing slits
self.slits = {}
mm = []
for idx in self.LBARS:
# References from header
try:
slit_t = hdr["SLIFL%d" % idx]
target_type = ... | def _update_slits(self, hdr) | Recreate slits | 3.986768 | 3.917485 | 1.017686 |
obj, created = super().update_or_create(*args, **kwargs)
if not created:
return self.with_signal(result=(obj, created))
return obj, created | def update_or_create(self, *args, **kwargs) | Only sent when not created, since default implementation will
call `self.create` when creating which triggers our signal
already. | 5.418453 | 4.915322 | 1.10236 |
if duration >= 0:
self.histogram.update(duration)
self.meter.mark() | def update(self, duration) | Add a recorded duration. | 8.449231 | 6.406637 | 1.318825 |
clusters = [m.cluster for m in vmong5k_conf.machines]
sites = g5k_api_utils.get_clusters_sites(clusters)
site_names = set(sites.values())
if len(site_names) > 1:
raise Exception("Multisite deployment not supported yet")
site = site_names.pop()
return _do_build_g5k_conf(vmong5k_conf,... | def _build_g5k_conf(vmong5k_conf) | Build the conf of the g5k provider from the vmong5k conf. | 3.532328 | 3.545891 | 0.996175 |
meta = getattr(obj, '_meta') # make pycharm happy
# dictionary of model values excluding auto created and related fields
return {f.name: getattr(obj, f.name)
for f in meta.get_fields(include_parents=False)
if not f.auto_created} | def copy_model_instance(obj) | Copy Django model instance as a dictionary excluding automatically created
fields like an auto-generated sequence as a primary key or an auto-created
many-to-one reverse relation.
:param obj: Django model object
:return: copy of model instance as dictionary | 5.471466 | 5.072678 | 1.078615 |
# get positional argument names from parameters and apply them to args
# update data with additional kwargs
argpos = {
v['extras']['argpos']: k for k, v in self.parameters.iteritems()
if 'argpos' in v['extras']
}
data = dict(
{argpos[n... | def load_data(self, *args, **kwargs) | Collects positional and keyword arguments into `data` and applies units.
:return: data | 7.584177 | 7.413264 | 1.023055 |
# if units key exists then apply
for k, v in self.parameters.iteritems():
if v and v.get('units'):
data[k] = Q_(data[k], v.get('units'))
return data | def apply_units_to_cache(self, data) | Applies units to data when a proxy reader is used. For example if the
data is cached as JSON and retrieved using the
:class:`~simkit.core.data_readers.JSONReader`, then units can be
applied from the original parameter schema.
:param data: Data read by proxy reader.
:return: data... | 5.340662 | 5.555517 | 0.961326 |
model_dict = copy_model_instance(model_instance)
return super(DjangoModelReader, self).load_data(**model_dict) | def load_data(self, model_instance, *args, **kwargs) | Apply units to model.
:return: data | 6.742488 | 8.156267 | 0.826664 |
@functools.wraps(f)
def wrapped(*args, **kwargs):
with _cache_lock:
identifier = (f.__name__, args, kwargs)
key = pickle.dumps(identifier)
value = cache.get(key)
if value is not None:
logger.debug("HIT for %s -> %s" % (str(identifier)... | def cached(f) | Decorator for caching/retrieving api calls request.
Many calls to the API are getter on static parts (e.g site of a given
cluster name won't change). By caching some responses we can avoid
hammering the API server. | 2.20665 | 2.3813 | 0.926658 |
with _api_lock:
global _api_client
if not _api_client:
conf_file = os.path.join(os.environ.get("HOME"),
".python-grid5000.yaml")
_api_client = Client.from_yaml(conf_file)
return _api_client | def get_api_client() | Gets the reference to the API cient (singleton). | 4.068106 | 3.743358 | 1.086753 |
gk = get_api_client()
sites = get_all_sites_obj()
jobs = []
for site in [s for s in sites if s.uid not in gk.excluded_site]:
logger.info("Reloading %s from %s" % (job_name, site.uid))
_jobs = site.jobs.list(name=job_name,
state="waiting,launching,runni... | def grid_reload_from_name(job_name) | Reload all running or pending jobs of Grid'5000 with a given name.
By default all the sites will be searched for jobs with the name
``job_name``. Using EnOSlib there can be only one job per site with name
``job_name``.
Note that it honors the ``exluded_sites`` attribute of the client so the
scan c... | 4.479863 | 3.441146 | 1.301852 |
gk = get_api_client()
jobs = []
for site, job_id in oargrid_jobids:
jobs.append(gk.sites[site].jobs[job_id])
return jobs | def grid_reload_from_ids(oargrid_jobids) | Reload all running or pending jobs of Grid'5000 from their ids
Args:
oargrid_jobids (list): list of ``(site, oar_jobid)`` identifying the
jobs on each site
Returns:
The list of python-grid5000 jobs retrieved | 4.526653 | 4.709435 | 0.961188 |
jobs = grid_reload_from_name(job_name)
for job in jobs:
job.delete()
logger.info("Killing the job (%s, %s)" % (job.site, job.uid)) | def grid_destroy_from_name(job_name) | Destroy all the jobs with a given name.
Args:
job_name (str): the job name | 4.821754 | 5.950229 | 0.810348 |
jobs = grid_reload_from_ids(oargrid_jobids)
for job in jobs:
job.delete()
logger.info("Killing the jobs %s" % oargrid_jobids) | def grid_destroy_from_ids(oargrid_jobids) | Destroy all the jobs with corresponding ids
Args:
oargrid_jobids (list): the ``(site, oar_job_id)`` list of tuple
identifying the jobs for each site. | 4.028214 | 5.415049 | 0.743893 |
gk = get_api_client()
jobs = []
try:
for site, job_spec in job_specs:
logger.info("Submitting %s on %s" % (job_spec, site))
jobs.append(gk.sites[site].jobs.create(job_spec))
except Exception as e:
logger.error("An error occured during the job submissions")
... | def submit_jobs(job_specs) | Submit a job
Args:
job_spec (dict): The job specifiation (see Grid'5000 API reference) | 3.23937 | 3.428501 | 0.944836 |
all_running = False
while not all_running:
all_running = True
time.sleep(5)
for job in jobs:
job.refresh()
scheduled = getattr(job, "scheduled_at", None)
if scheduled is not None:
logger.info("Waiting for %s on %s [%s]" % (job.uid... | def wait_for_jobs(jobs) | Waits for all the jobs to be runnning.
Args:
jobs(list): list of the python-grid5000 jobs to wait for
Raises:
Exception: if one of the job gets in error state. | 4.176475 | 3.943778 | 1.059004 |
gk = get_api_client()
environment = options.pop("env_name")
options.update(environment=environment)
options.update(nodes=nodes)
key_path = DEFAULT_SSH_KEYFILE
options.update(key=key_path.read_text())
logger.info("Deploying %s with options %s" % (nodes, options))
deployment = gk.site... | def grid_deploy(site, nodes, options) | Deploy and wait for the deployment to be finished.
Args:
site(str): the site
nodes(list): list of nodes (str) to depoy
options(dict): option of the deployment (refer to the Grid'5000 API
Specifications)
Returns:
tuple of deployed(list), undeployed(list) nodes. | 3.62313 | 3.504787 | 1.033766 |
def _to_network_address(host):
splitted = host.split('.')
splitted[0] = splitted[0] + "-" + interface
return ".".join(splitted)
gk = get_api_client()
network_addresses = [_to_network_address(n) for n in nodes]
gk.sites[site].vlans[str(vlan_id)].submit({"nodes": net... | def set_nodes_vlan(site, nodes, interface, vlan_id) | Set the interface of the nodes in a specific vlan.
It is assumed that the same interface name is available on the node.
Args:
site(str): site to consider
nodes(list): nodes to consider
interface(str): the network interface to put in the vlan
vlan_id(str): the id of the vlan | 5.514588 | 5.68177 | 0.970576 |
result = {}
all_clusters = get_all_clusters_sites()
clusters_sites = {c: s for (c, s) in all_clusters.items()
if c in clusters}
for cluster, site in clusters_sites.items():
# here we want the site python-grid5000 site object
result.update({cluster: get_site_... | def clusters_sites_obj(clusters) | Get all the corresponding sites of the passed clusters.
Args:
clusters(list): list of string uid of sites (e.g 'rennes')
Return:
dict corresponding to the mapping cluster uid to python-grid5000 site | 5.785708 | 4.428643 | 1.306429 |
result = {}
gk = get_api_client()
sites = gk.sites.list()
for site in sites:
clusters = site.clusters.list()
result.update({c.uid: site.uid for c in clusters})
return result | def get_all_clusters_sites() | Get all the cluster of all the sites.
Returns:
dict corresponding to the mapping cluster uid to python-grid5000 site | 4.426473 | 4.303916 | 1.028476 |
gk = get_api_client()
site = get_cluster_site(cluster)
return gk.sites[site].clusters[cluster].nodes.list() | def get_nodes(cluster) | Get all the nodes of a given cluster.
Args:
cluster(string): uid of the cluster (e.g 'rennes') | 7.33201 | 9.08429 | 0.807109 |
nics = get_nics(cluster)
# NOTE(msimonin): Since 05/18 nics on g5k nodes have predictable names but
# the api description keep the legacy name (device key) and the new
# predictable name (key name). The legacy names is still used for api
# request to the vlan endpoint This should be fixed in
... | def get_cluster_interfaces(cluster, extra_cond=lambda nic: True) | Get the network interfaces names corresponding to a criteria.
Note that the cluster is passed (not the individual node names), thus it is
assumed that all nodes in a cluster have the same interface names same
configuration. In addition to ``extra_cond``, only the mountable and
Ehernet interfaces are re... | 10.377316 | 10.679876 | 0.97167 |
interfaces = {}
for cluster in clusters:
nics = get_cluster_interfaces(cluster, extra_cond=extra_cond)
interfaces.setdefault(cluster, nics)
return interfaces | def get_clusters_interfaces(clusters, extra_cond=lambda nic: True) | Returns for each cluster the available cluster interfaces
Args:
clusters (str): list of the clusters
extra_cond (lambda): extra predicate to filter network card retrieved
from the API. E.g lambda nic: not nic['mounted'] will retrieve all the
usable network cards that are not mounted by defa... | 2.723363 | 3.969373 | 0.686094 |
candidates = []
for node, status in nodes_status.items():
reservations = status.get("reservations", [])
# we search for the overlapping reservations
overlapping_reservations = []
for reservation in reservations:
queue = reservation.get("queue")
if que... | def can_start_on_cluster(nodes_status,
nodes,
start,
walltime) | Check if #nodes can be started on a given cluster.
This is intended to give a good enough approximation.
This can be use to prefiltered possible reservation dates before submitting
them on oar. | 3.573973 | 3.46506 | 1.031432 |
offset = SYNCHRONISATION_OFFSET
start = time.time() + offset
_t = time.strptime(walltime, "%H:%M:%S")
_walltime = _t.tm_hour * 3600 + _t.tm_min * 60 + _t.tm_sec
# Compute the demand for each cluster
demands = defaultdict(int)
for machine in machines:
cluster = machine["cluster"... | def _do_synchronise_jobs(walltime, machines) | This returns a common reservation date for all the jobs.
This reservation date is really only a hint and will be supplied to each
oar server. Without this *common* reservation_date, one oar server can
decide to postpone the start of the job while the other are already
running. But this doens't prevent ... | 5.097044 | 4.805674 | 1.06063 |
return iter(functools.partial(take, n, iter(iterable)), []) | def chunked(iterable, n) | Break an iterable into lists of a given length::
>>> list(chunked([1, 2, 3, 4, 5, 6, 7], 3))
[[1, 2, 3], [4, 5, 6], [7]]
If the length of ``iterable`` is not evenly divisible by ``n``, the last
returned list will be shorter.
This is useful for splitting up a computation on a large number ... | 6.93455 | 10.231468 | 0.677767 |
for data in rawdata:
try:
item = data[0]
if item[0] == 2:
# Flush messages but we got nothing to flush
continue
if item[0] != 0:
warnings.warn(f"Unknown message type '{item[0]}'", Wa... | def add_data(self, rawdata) | Add data to given room's state | 5.722326 | 5.716574 | 1.001006 |
cid = str(self.__cid)
self.__cid += 1
event = queue.Queue()
self.__callbacks[cid] = event
return cid, event | def register_callback(self) | Register callback that we will have to wait for | 6.542619 | 5.814815 | 1.125164 |
ex = ConnectionError(
"Can't login to a protected room without a proper password", data
)
self.conn.reraise(ex) | def _handle_401(self, data) | Handle Lain being helpful | 21.613096 | 19.698385 | 1.097201 |
ex = IOError("Too fast", data)
self.conn.reraise(ex) | def _handle_429(self, data) | Handle Lain being helpful | 30.81628 | 26.179102 | 1.177133 |
cb_id = data.get("id")
args = data.get("args")
event = self.__callbacks.pop(cb_id, None)
if not event:
return
if not args:
event.put(args)
return
err, info = args
if err is None:
event.put(info)
els... | def _handle_callback(self, data) | Handle lain's callback. Only used with getFileinfo so far | 3.829832 | 3.579142 | 1.070042 |
self.room.user_count = data
self.conn.enqueue_data("user_count", self.room.user_count) | def _handle_userCount(self, data) | Handle user count changes | 8.933415 | 7.205057 | 1.239881 |
for k, v in data.items():
if k == "nick":
if v == "None":
v = "Volaphile"
setattr(self.room.user, k, v)
self.conn.enqueue_data(k, self.room.user.nick)
elif k != "profile":
if not hasattr(self.ro... | def _handle_userInfo(self, data) | Handle user information | 3.943094 | 3.774119 | 1.044772 |
self.room.key = data
self.conn.enqueue_data("key", self.room.key) | def _handle_key(self, data) | Handle keys | 13.962031 | 12.064612 | 1.157271 |
self.room.config.update(data)
self.conn.enqueue_data("config", data) | def _handle_config(self, data) | Handle initial config push and config changes | 15.013976 | 12.426854 | 1.208188 |
initial = data.get("set", False)
files = data["files"]
for f in files:
try:
fobj = File(
self.room,
self.conn,
f[0],
f[1],
type=f[2],
size... | def _handle_files(self, data) | Handle new files being uploaded | 4.472429 | 4.333194 | 1.032132 |
file = self.room.filedict.get(data)
if file:
self.room.filedict = data, None
self.conn.enqueue_data("delete_file", file) | def _handle_delete_file(self, data) | Handle files being removed | 10.758838 | 9.650988 | 1.114791 |
self.conn.enqueue_data(
"chat", ChatMessage.from_data(self.room, self.conn, data)
) | def _handle_chat(self, data) | Handle chat messages | 10.470567 | 8.848443 | 1.183323 |
key, value = change.get("key"), change.get("value")
self.room.config.update({key: value})
self.conn.enqueue_data("config", self.room.config) | def _handle_changed_config(self, change) | Handle configuration changes | 6.62975 | 5.911482 | 1.121504 |
self.room.user.nick = data
self.conn.enqueue_data("user", self.room.user) | def _handle_chat_name(self, data) | Handle user name changes | 15.4451 | 11.136134 | 1.386936 |
if islitlet % 10 == 0:
cout = str(islitlet // 10)
else:
cout = '.'
sys.stdout.write(cout)
if islitlet == islitlet_max:
sys.stdout.write('\n')
sys.stdout.flush() | def islitlet_progress(islitlet, islitlet_max) | Auxiliary function to print out progress in loop of slitlets.
Parameters
----------
islitlet : int
Current slitlet number.
islitlet_max : int
Maximum slitlet number. | 2.728232 | 2.817117 | 0.968448 |
from emirdrp.processing.flatfield import FlatFieldCorrector
flat_info = meta['master_flat']
with rinput.master_flat.open() as hdul:
_logger.info('loading intensity flat')
_logger.debug('flat info: %s', flat_info)
mflat = hdul[0].data
# Check NaN and Ceros
mask1 =... | def get_corrector_f(rinput, meta, ins, datamodel) | Corrector for intensity flat | 5.453946 | 5.301755 | 1.028706 |
def loginfo_method(self, rinput):
klass = rinput.__class__
for key in klass.stored():
val = getattr(rinput, key)
if isinstance(val, DataFrame):
self.logger.debug("DataFrame %s", info.gather_info_dframe(val))
elif isinstance(val, Observatio... | def loginfo(method) | Log the contents of Recipe Input | 7.140352 | 6.824471 | 1.046287 |
return Host(self.address,
alias=self.alias,
user=self.user,
keyfile=self.keyfile,
port=self.port,
extra=self.extra) | def to_host(self) | Copy or coerce to a Host. | 4.212799 | 3.649727 | 1.154278 |
ret = {}
if table_names:
for table_name in table_names:
for name, inter in get_interfaces().items():
if inter.has_table(table_name):
yield table_name, inter, inter.get_fields(table_name)
else:
for name, inter in get_interfaces().items():
... | def get_table_info(*table_names) | Returns a dict with table_name keys mapped to the Interface that table exists in
:param *table_names: the tables you are searching for | 2.345366 | 2.285049 | 1.026396 |
with stream.open() as fp:
fp.write_line("from datetime import datetime, date")
fp.write_line("from decimal import Decimal")
fp.write_line("from prom import Orm, Field")
fp.write_newlines()
for table_name, inter, fields in get_table_info(*table_names):
fp.wri... | def main_generate(table_names, stream) | This will print out valid prom python code for given tables that already exist
in a database.
This is really handy when you want to bootstrap an existing database to work
with prom and don't want to manually create Orm objects for the tables you want
to use, let `generate` do it for you | 2.691465 | 2.606726 | 1.032508 |
pos_x = numpy.asarray(pos_x)
pos_y = numpy.asarray(pos_y)
# convert virtual pixel to real pixel
# convert world coordinate to pixel
center = [1024.5, 1024.5]
cf = EMIR_PLATESCALE_RADS
pos_base_x = pos_x - center[0]
pos_base_y = pos_y - center[1]
ra = numpy.hypot(pos_base_x, pos... | def exvp(pos_x, pos_y) | Convert virtual pixel to real pixel | 4.383437 | 4.21154 | 1.040816 |
if isinstance(first, list):
one = [set(v.split(" ")) for v in first]
else:
one = [{v} for v in first.split(" ")]
if isinstance(second, list):
other = [set(v.split(" ")) for v in second]
else:
other = [{v} for v in second.split(" ")]
# all values in one must app... | def match_sp_sep(first, second) | Verify that all the values in 'first' appear in 'second'.
The values can either be in the form of lists or as space separated
items.
:param first:
:param second:
:return: True/False | 2.933137 | 2.655782 | 1.104434 |
si_url = request["sector_identifier_uri"]
try:
res = self.endpoint_context.httpc.get(si_url)
except Exception as err:
logger.error(err)
res = None
if not res:
raise InvalidSectorIdentifier("Couldn't read from sector_identifier_uri... | def _verify_sector_identifier(self, request) | Verify `sector_identifier_uri` is reachable and that it contains
`redirect_uri`s.
:param request: Provider registration request
:return: si_redirects, sector_id
:raises: InvalidSectorIdentifier | 2.941171 | 2.588438 | 1.136272 |
if not(self._firstline):
self._line = self._file.readline()
self._firstline = False
if not(self._line):
return None
__ll = (self._line).replace('\n', '')
__values = __ll.split()
self._outdict.update(dict(zip(self._keys, __values)))
... | def readline(self) | Read and analyse the next line of the SExtractor catalog
and return a dictionary {'param1': value, 'param2': value, ...}. | 5.59552 | 4.896355 | 1.142793 |
__result = []
__ll = self.readline()
while __ll:
__result.append(__ll)
__ll = self.readline()
return list(__result) | def read(self) | Read the file until EOF and return a list of dictionaries. | 5.475875 | 4.298625 | 1.273867 |
if self._file:
if not(self._file.closed):
self._file.close()
self.closed = True | def close(self) | Close the SExtractor file. | 5.081856 | 4.556998 | 1.115176 |
resources = configuration["resources"]
machines = resources["machines"]
networks = resources["networks"]
oargrid_jobids = configuration.get("oargrid_jobids")
if oargrid_jobids:
logger.debug("Loading the OargridStaticDriver")
return OargridStaticDriver(oargrid_jobids)
else:
... | def get_driver(configuration) | Build an instance of the driver to interact with G5K | 5.967262 | 5.98872 | 0.996417 |
if parts is None:
return None
elif len(parts) == 3:
# verify the cookie signature
timestamp, load, b64_mac = parts
mac = base64.b64decode(b64_mac)
verifier = HMACSigner(algorithm=sign_alg)
if verifier.verify(load.encode('utf-8') + timestamp.encode('utf-8'),
... | def ver_dec_content(parts, sign_key=None, enc_key=None, sign_alg='SHA256') | Verifies the value of a cookie
:param parts: The parts of the payload
:param sign_key: A :py:class:`cryptojwt.jwk.hmac.SYMKey` instance
:param enc_key: A :py:class:`cryptojwt.jwk.hmac.SYMKey` instance
:param sign_alg: Which signing algorithm to was used
:return: A tuple with basic information and a... | 2.452591 | 2.320923 | 1.056731 |
if not timestamp:
timestamp = str(int(time.time()))
_cookie_value = sign_enc_payload(load, timestamp, sign_key=sign_key,
enc_key=enc_key, sign_alg=sign_alg)
content = {name: {"value": _cookie_value}}
if path is not None:
content[name]["path"] =... | def make_cookie_content(name, load, sign_key, domain=None, path=None,
timestamp="", enc_key=None, max_age=0,
sign_alg='SHA256') | Create and return a cookies content
If you only provide a `seed`, a HMAC gets added to the cookies value
and this is checked, when the cookie is parsed again.
If you provide both `seed` and `enc_key`, the cookie gets protected
by using AEAD encryption. This provides both a MAC over the whole cookie
... | 2.589602 | 2.841316 | 0.911409 |
cookie_obj = SimpleCookie(as_unicode(kaka))
morsel = cookie_obj.get(name)
if morsel:
return morsel.value.split("|")
else:
return None | def cookie_parts(name, kaka) | Give me the parts of the cookie payload
:param name: A name of a cookie object
:param kaka: The cookie
:return: A list of parts or None if there is no cookie object with the
given name | 3.501956 | 4.779137 | 0.732759 |
if not kaka:
return None
parts = cookie_parts(name, kaka)
return ver_dec_content(parts, sign_key, enc_key, sign_alg) | def parse_cookie(name, sign_key, kaka, enc_key=None, sign_alg='SHA256') | Parses and verifies a cookie value
Parses a cookie created by `make_cookie` and verifies
it has not been tampered with.
You need to provide the same `sign_key` and `enc_key`
used when creating the cookie, otherwise the verification
fails. See `make_cookie` for details about the verification.
... | 5.850111 | 10.10978 | 0.578659 |
if cookie_name is None:
cookie_name = self.default_value['name']
return self.create_cookie("", "", cookie_name=cookie_name, kill=True) | def delete_cookie(self, cookie_name=None) | Create a cookie that will immediately expire when it hits the other
side.
:param cookie_name: Name of the cookie
:return: A tuple to be added to headers | 5.590549 | 6.887541 | 0.81169 |
if cookie_name is None:
cookie_name = self.default_value['name']
if cookie is None or cookie_name is None:
return None
else:
try:
info, timestamp = parse_cookie(cookie_name, self.sign_key, cookie,
... | def get_cookie_value(self, cookie=None, cookie_name=None) | Return information stored in a Cookie
:param cookie: A cookie instance
:param cookie_name: The name of the cookie I'm looking for
:return: tuple (value, timestamp, type) | 4.510118 | 4.141627 | 1.088972 |
timestamp = str(int(time.time()))
# create cookie payload
try:
_payload = "::".join([payload, timestamp, typ])
except TypeError:
_payload = "::".join([payload[0], timestamp, typ])
content = make_cookie_content(name, _payload, self.sign_key, doma... | def append_cookie(self, cookie, name, payload, typ, domain=None, path=None,
timestamp="", max_age=0) | Adds a cookie to a SimpleCookie instance
:param cookie:
:param name:
:param payload:
:param typ:
:param domain:
:param path:
:param timestamp:
:param max_age:
:return: | 3.345465 | 3.665556 | 0.912676 |
return pvlib.pvsystem.snlinverter(v_mp, p_mp, inverter).flatten() | def f_ac_power(inverter, v_mp, p_mp) | Calculate AC power
:param inverter:
:param v_mp:
:param p_mp:
:return: AC power [W] | 8.770291 | 13.40115 | 0.654443 |
dc = pvlib.pvsystem.sapm(effective_irradiance, cell_temp, module)
fields = ('i_sc', 'i_mp', 'v_oc', 'v_mp', 'p_mp')
return tuple(dc[field] for field in fields) | def f_dc_power(effective_irradiance, cell_temp, module) | Calculate DC power using Sandia Performance model
:param effective_irradiance: effective irradiance [suns]
:param cell_temp: PV cell temperature [degC]
:param module: PV module dictionary or pandas data frame
:returns: i_sc, i_mp, v_oc, v_mp, p_mp | 3.847331 | 2.878004 | 1.336805 |
Ee = pvlib.pvsystem.sapm_effective_irradiance(poa_direct, poa_diffuse,
am_abs, aoi, module)
return Ee.reshape(1, -1) | def f_effective_irradiance(poa_direct, poa_diffuse, am_abs, aoi, module) | Calculate effective irradiance for Sandia Performance model
:param poa_direct: plane of array direct irradiance [W/m**2]
:param poa_diffuse: plane of array diffuse irradiance [W/m**2]
:param am_abs: absolute air mass [dimensionless]
:param aoi: angle of incidence [degrees]
:param module: PV module ... | 3.297701 | 3.525427 | 0.935405 |
temps = pvlib.pvsystem.sapm_celltemp(poa_global, wind_speed, air_temp)
return temps['temp_cell'].values, temps['temp_module'].values | def f_cell_temp(poa_global, wind_speed, air_temp) | Calculate cell temperature.
:param poa_global: plane of array global irradiance [W/m**2]
:param wind_speed: wind speed [m/s]
:param air_temp: ambient dry bulb air temperature [degC]
:return: cell temperature [degC] | 3.153854 | 4.382884 | 0.719584 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.