code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def load_rv_data(filename, indep, dep, indweight=None, dir='./'):
if '/' in filename:
path, filename = os.path.split(filename)
else:
path = dir
load_file = os.path.join(path, filename)
rvdata = np.loadtxt(load_file)
d ={}
d['phoebe_rv_time'] = rvdata[:,0]
d['phoebe_rv_vel'] = rvdata[:,1]
ncol = len(rvdata[0])
if indweight=="Standard deviation":
if ncol >= 3:
d['phoebe_rv_sigmarv'] = rvdata[:,2]
else:
logger.warning('A sigma column is mentioned in the .phoebe file but is not present in the rv data file')
elif indweight =="Standard weight":
if ncol >= 3:
sigma = np.sqrt(1/rvdata[:,2])
d['phoebe_rv_sigmarv'] = sigma
logger.warning('Standard weight has been converted to Standard deviation.')
else:
logger.warning('Phoebe 2 currently only supports standard deviaton')
return d | load dictionary with rv data. |
def remove_thin_device(name, force=False):
cmd = ['dmsetup', 'remove', '--retry', name]
r = util.subp(cmd)
if not force:
if r.return_code != 0:
raise MountError('Could not remove thin device:\n%s' %
r.stderr.decode(sys.getdefaultencoding()).split("\n")[0]) | Destroys a thin device via subprocess call. |
def find_all_by_parameters(self, task_name, session=None, **task_params):
with self._session(session) as session:
query = session.query(TaskRecord).join(TaskEvent).filter(TaskRecord.name == task_name)
for (k, v) in six.iteritems(task_params):
alias = sqlalchemy.orm.aliased(TaskParameter)
query = query.join(alias).filter(alias.name == k, alias.value == v)
tasks = query.order_by(TaskEvent.ts)
for task in tasks:
assert all(k in task.parameters and v == str(task.parameters[k].value) for (k, v) in six.iteritems(task_params))
yield task | Find tasks with the given task_name and the same parameters as the kwargs. |
def _ufo_logging_ref(ufo):
if ufo.path:
return os.path.basename(ufo.path)
return ufo.info.styleName | Return a string that can identify this UFO in logs. |
def from_cache(self, section, name):
cached_value = self.cache.get(
self.get_cache_key(section, name), CachedValueNotFound)
if cached_value is CachedValueNotFound:
raise CachedValueNotFound
if cached_value == preferences_settings.CACHE_NONE_VALUE:
cached_value = None
return self.registry.get(
section=section, name=name).serializer.deserialize(cached_value) | Return a preference raw_value from cache |
def replace(old, new):
parent = old.getparent()
parent.replace(old, new) | A simple way to replace one element node with another. |
def clear(self):
self.sam |= KEY_WRITE
for v in list(self.values()):
del self[v.name]
for k in list(self.subkeys()):
self.del_subkey(k.name) | Remove all subkeys and values from this key. |
def copychildren(self, newdoc=None, idsuffix=""):
if idsuffix is True: idsuffix = ".copy." + "%08x" % random.getrandbits(32)
for c in self:
if isinstance(c, Word):
yield WordReference(newdoc, id=c.id)
else:
yield c.copy(newdoc,idsuffix) | Generator creating a deep copy of the children of this element. If idsuffix is a string, if set to True, a random idsuffix will be generated including a random 32-bit hash |
def color(ip, mac, hue, saturation, value):
bulb = MyStromBulb(ip, mac)
bulb.set_color_hsv(hue, saturation, value) | Switch the bulb on with the given color. |
def create_reader_instances(self,
filenames=None,
reader=None,
reader_kwargs=None):
return load_readers(filenames=filenames,
reader=reader,
reader_kwargs=reader_kwargs,
ppp_config_dir=self.ppp_config_dir) | Find readers and return their instances. |
def __SendMediaBody(self, start, additional_headers=None):
self.EnsureInitialized()
if self.total_size is None:
raise exceptions.TransferInvalidError(
'Total size must be known for SendMediaBody')
body_stream = stream_slice.StreamSlice(
self.stream, self.total_size - start)
request = http_wrapper.Request(url=self.url, http_method='PUT',
body=body_stream)
request.headers['Content-Type'] = self.mime_type
if start == self.total_size:
range_string = 'bytes */%s' % self.total_size
else:
range_string = 'bytes %s-%s/%s' % (start, self.total_size - 1,
self.total_size)
request.headers['Content-Range'] = range_string
if additional_headers:
request.headers.update(additional_headers)
return self.__SendMediaRequest(request, self.total_size) | Send the entire media stream in a single request. |
def insertDict(self, tblname, d, fields = None):
if fields == None:
fields = sorted(d.keys())
values = None
try:
SQL = 'INSERT INTO %s (%s) VALUES (%s)' % (tblname, join(fields, ", "), join(['%s' for x in range(len(fields))], ','))
values = tuple([d[k] for k in fields])
self.locked_execute(SQL, parameters = values)
except Exception, e:
if SQL and values:
sys.stderr.write("\nSQL execution error in query '%s' %% %s at %s:" % (SQL, values, datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
sys.stderr.write("\nError: '%s'.\n" % (str(e)))
sys.stderr.flush()
raise Exception("Error occurred during database insertion: '%s'." % str(e)) | Simple function for inserting a dictionary whose keys match the fieldnames of tblname. |
def decode_from_sha(sha):
if isinstance(sha, str):
sha = sha.encode('utf-8')
return codecs.decode(re.sub(rb'(00)*$', b'', sha), "hex_codec") | convert coerced sha back into numeric list |
def partition(self, ref=None, **kwargs):
from ambry.orm.exc import NotFoundError
from sqlalchemy.orm.exc import NoResultFound
if not ref and not kwargs:
return None
if ref:
for p in self.partitions:
if ref == p.name or ref == p.vname or ref == p.vid or ref == p.id:
p._bundle = self
return p
raise NotFoundError("No partition found for '{}' (a)".format(ref))
elif kwargs:
from ..identity import PartitionNameQuery
pnq = PartitionNameQuery(**kwargs)
try:
p = self.partitions._find_orm(pnq).one()
if p:
p._bundle = self
return p
except NoResultFound:
raise NotFoundError("No partition found for '{}' (b)".format(kwargs)) | Return a partition in this bundle for a vid reference or name parts |
def register(self, name, obj):
if name in self.all:
log.debug('register: %s already existed: %s', name, obj.name)
raise DuplicateDefinitionException(
'register: %s already existed: %s' % (name, obj.name))
log.debug('register: %s ', name)
self.all[name] = obj
return obj | Registers an unique type description |
def walk_revctrl(dirname='', ff=''):
file_finder = None
items = []
if not ff:
distutils.log.error('No file-finder passed to walk_revctrl')
sys.exit(1)
for ep in pkg_resources.iter_entry_points('setuptools.file_finders'):
if ff == ep.name:
distutils.log.info('using %s file-finder', ep.name)
file_finder = ep.load()
finder_items = []
with pythonpath_off():
for item in file_finder(dirname):
if not basename(item).startswith(('.svn', '.hg', '.git')):
finder_items.append(item)
distutils.log.info('%d files found', len(finder_items))
items.extend(finder_items)
if file_finder is None:
distutils.log.error('Failed to load %s file-finder; setuptools-%s extension missing?',
ff, 'subversion' if ff == 'svn' else ff)
sys.exit(1)
return items or [''] | Return files found by the file-finder 'ff'. |
def upload_celery_conf(command='celeryd', app_name=None, template_name=None, context=None):
app_name = app_name or command
default = {'app_name': app_name, 'command': command}
context = context or {}
default.update(context)
template_name = template_name or [u'supervisor/%s.conf' % command, u'supervisor/celery.conf']
upload_supervisor_app_conf(app_name=app_name, template_name=template_name, context=default) | Upload Supervisor configuration for a celery command. |
def update_identity(self):
fr = self.record
d = fr.unpacked_contents
d['identity'] = self._dataset.identity.ident_dict
d['names'] = self._dataset.identity.names_dict
fr.update_contents(msgpack.packb(d), 'application/msgpack') | Update the identity and names to match the dataset id and version |
def write(self, fptr):
self._validate(writing=True)
num_items = len(self.fragment_offset)
length = 8 + 2 + num_items * 14
fptr.write(struct.pack('>I4s', length, b'flst'))
fptr.write(struct.pack('>H', num_items))
for j in range(num_items):
write_buffer = struct.pack('>QIH',
self.fragment_offset[j],
self.fragment_length[j],
self.data_reference[j])
fptr.write(write_buffer) | Write a fragment list box to file. |
def create(self, key, value=None, dir=False, ttl=None, timeout=None):
return self.adapter.set(key, value, dir=dir, ttl=ttl,
prev_exist=False, timeout=timeout) | Creates a new key. |
def init(*args, **kwargs):
default_log_level = kwargs.pop("default_log_level", None)
import cellpy.log as log
log.setup_logging(custom_log_dir=prms.Paths["filelogdir"],
default_level=default_log_level)
b = Batch(*args, **kwargs)
return b | Returns an initialized instance of the Batch class |
def _stop_timers(canvas):
for attr in dir(canvas):
try:
attr_obj = getattr(canvas, attr)
except NotImplementedError:
attr_obj = None
if isinstance(attr_obj, Timer):
attr_obj.stop() | Stop all timers in a canvas. |
def drop(self):
if self._is_dropped is False:
self.table.drop(self.engine)
self._is_dropped = True | Drop the table from the database |
def extract_element(self, vector, idx, name=''):
instr = instructions.ExtractElement(self.block, vector, idx, name=name)
self._insert(instr)
return instr | Returns the value at position idx. |
def split_title(title, width, title_fs):
titles = []
if not title:
return titles
size = reverse_text_len(width, title_fs * 1.1)
title_lines = title.split("\n")
for title_line in title_lines:
while len(title_line) > size:
title_part = title_line[:size]
i = title_part.rfind(' ')
if i == -1:
i = len(title_part)
titles.append(title_part[:i])
title_line = title_line[i:].strip()
titles.append(title_line)
return titles | Split a string for a specified width and font size |
def cast_number_strings_to_integers(d):
for k, v in d.items():
if determine_if_str_or_unicode(v):
if v.isdigit():
d[k] = int(v)
return d | d is a dict |
def indim(self):
indim = self.numOffbids * len(self.generators)
if self.maxWithhold is not None:
return indim * 2
else:
return indim | The number of action values that the environment accepts. |
def subscribe(self, topic=b''):
self.sockets[zmq.SUB].setsockopt(zmq.SUBSCRIBE, topic)
poller = self.pollers[zmq.SUB]
return poller | subscribe to the SUB socket, to listen for incomming variables, return a stream that can be listened to. |
def retrieve_data(self):
df = self.manager.get_historic_data(self.start.date(), self.end.date())
df.replace(0, np.nan, inplace=True)
return df | Retrives data as a DataFrame. |
def PARAMLIMITS(self, value):
assert set(value.keys()) == set(self.PARAMLIMITS.keys()), "The \
new parameter limits are not defined for the same set \
of parameters as before."
for param in value.keys():
assert value[param][0] < value[param][1], "The new \
minimum value for {0}, {1}, is equal to or \
larger than the new maximum value, {2}"\
.format(param, value[param][0], value[param][1])
self._PARAMLIMITS = value.copy() | Set new `PARAMLIMITS` dictionary. |
def build_target_areas(entry):
target_areas = []
areas = str(entry['cap:areaDesc']).split(';')
for area in areas:
target_areas.append(area.strip())
return target_areas | Cleanup the raw target areas description string |
async def volume(self, ctx, volume: int):
if ctx.voice_client is None:
return await ctx.send("Not connected to a voice channel.")
ctx.voice_client.source.volume = volume / 100
await ctx.send("Changed volume to {}%".format(volume)) | Changes the player's volume |
def select_models(clas,pool_or_cursor,**kwargs):
"returns generator yielding instances of the class"
if 'columns' in kwargs: raise ValueError("don't pass 'columns' to select_models")
return (set_options(pool_or_cursor,clas(*row)) for row in clas.select(pool_or_cursor,**kwargs)) | returns generator yielding instances of the class |
def schema(ctx, schema):
data = yaml.load(schema)
if not isinstance(data, (list, tuple)):
data = [data]
with click.progressbar(data, label=schema.name) as bar:
for schema in bar:
ctx.obj['grano'].schemata.upsert(schema) | Load schema definitions from a YAML file. |
async def get_property(self, command):
_LOGGER.debug("Getting property %s", command)
if self.__checkLock():
return BUSY
timeout = self.__get_timeout(command)
response = await self.send_request(
timeout=timeout,
params=EPSON_KEY_COMMANDS[command],
type='json_query')
if not response:
return False
try:
return response['projector']['feature']['reply']
except KeyError:
return BUSY | Get property state from device. |
def diff(self, obj=None):
if self.no_resource:
return NOOP
if not self.present:
if self.existing:
return DEL
return NOOP
if not obj:
obj = self.obj()
is_diff = NOOP
if self.present and self.existing:
if isinstance(self.existing, dict):
current = dict(self.existing)
if 'refresh_interval' in current:
del current['refresh_interval']
if diff_dict(current, obj):
is_diff = CHANGED
elif is_unicode(self.existing):
if self.existing != obj:
is_diff = CHANGED
elif self.present and not self.existing:
is_diff = ADD
return is_diff | Determine if something has changed or not |
def peers_by_group(self, name):
return czmq.Zlist(lib.zyre_peers_by_group(self._as_parameter_, name), True) | Return zlist of current peers of this group. |
async def controller(self):
return await Connection.connect(
self.endpoint,
username=self.username,
password=self.password,
cacert=self.cacert,
bakery_client=self.bakery_client,
loop=self.loop,
max_frame_size=self.max_frame_size,
) | Return a Connection to the controller at self.endpoint |
def qmark(cls, query):
def sub_sequence(m):
s = m.group(0)
if s == "??":
return "?"
if s == "%":
return "%%"
else:
return "%s"
return cls.RE_QMARK.sub(sub_sequence, query) | Convert a "qmark" query into "format" style. |
def returner(ret):
opts = _get_options(ret)
try:
with salt.utils.files.flopen(opts['filename'], 'a') as logfile:
salt.utils.json.dump(ret, logfile)
logfile.write(str('\n'))
except Exception:
log.error('Could not write to rawdata_json file %s', opts['filename'])
raise | Write the return data to a file on the minion. |
def file_fingerprint(fullpath):
stat = os.stat(fullpath)
return ','.join([str(value) for value in [stat.st_ino, stat.st_mtime, stat.st_size] if value]) | Get a metadata fingerprint for a file |
def import_mock(name, *args, **kwargs):
if any(name.startswith(s) for s in mock_modules):
return MockModule()
return orig_import(name, *args, **kwargs) | Mock all modules starting with one of the mock_modules names. |
def _is_valid_decimal(self, inpt, metadata):
if not (isinstance(inpt, float) or isinstance(inpt, Decimal)):
return False
if not isinstance(inpt, Decimal):
inpt = Decimal(str(inpt))
if metadata.get_minimum_decimal() and inpt < metadata.get_minimum_decimal():
return False
if metadata.get_maximum_decimal() and inpt > metadata.get_maximum_decimal():
return False
if metadata.get_decimal_set() and inpt not in metadata.get_decimal_set():
return False
if metadata.get_decimal_scale() and len(str(inpt).split('.')[-1]) != metadata.get_decimal_scale():
return False
else:
return True | Checks if input is a valid decimal value |
def _reformat_docstring(doc, format_fn, code_newline=""):
out = []
status = {"listing": False, "add_line": False, "eat_line": False}
code = False
for line in doc:
if status["add_line"]:
out.append("\n")
status["add_line"] = False
if status["eat_line"]:
status["eat_line"] = False
if line.strip() == "":
continue
if line.strip() == "```":
code = not code
out.append(line + code_newline)
continue
if not code:
if line.rstrip() == "":
status["listing"] = False
line = format_fn(line, status)
if re_listing.match(line):
status["listing"] = True
out.append(line.rstrip() + "\n")
return out | Go through lines of file and reformat using format_fn |
def draw_rect(
self, x:float, y:float, w:float, h:float, *,
stroke:Color=None,
stroke_width:float=1,
stroke_dash:typing.Sequence=None,
fill:Color=None
) -> None:
pass | Draws the given rectangle. |
def global_variable_action(self, text, loc, var):
exshared.setpos(loc, text)
if DEBUG > 0:
print("GLOBAL_VAR:",var)
if DEBUG == 2: self.symtab.display()
if DEBUG > 2: return
index = self.symtab.insert_global_var(var.name, var.type)
self.codegen.global_var(var.name)
return index | Code executed after recognising a global variable |
def save(self, *args, **kwargs):
self.text = clean_text(self.text)
self.text_formatted = format_text(self.text)
super(BaseUserContentModel, self).save(*args, **kwargs) | Clean text and save formatted version. |
def __check_submodules(self):
if not os.path.exists('.git'):
return
with open('.gitmodules') as f:
for l in f:
if 'path' in l:
p = l.split('=')[-1].strip()
if not os.path.exists(p):
raise ValueError('Submodule %s missing' % p)
proc = subprocess.Popen(['git', 'submodule', 'status'],
stdout=subprocess.PIPE)
status, _ = proc.communicate()
status = status.decode("ascii", "replace")
for line in status.splitlines():
if line.startswith('-') or line.startswith('+'):
raise ValueError('Submodule not clean: %s' % line) | Verify that the submodules are checked out and clean. |
def dict_to_op(d, index_name, doc_type, op_type='index'):
if d is None:
return d
op_types = ('create', 'delete', 'index', 'update')
if op_type not in op_types:
msg = 'Unknown operation type "{}", must be one of: {}'
raise Exception(msg.format(op_type, ', '.join(op_types)))
if 'id' not in d:
raise Exception('"id" key not found')
operation = {
'_op_type': op_type,
'_index': index_name,
'_type': doc_type,
'_id': d.pop('id'),
}
operation.update(d)
return operation | Create a bulk-indexing operation from the given dictionary. |
def play():
with sqlite3.connect(ARGS.database) as connection:
connection.text_factory = str
cursor = connection.cursor()
if ARGS.pattern:
if not ARGS.strict:
ARGS.pattern = '%{0}%'.format(ARGS.pattern)
cursor.execute('SELECT * FROM Movies WHERE Name LIKE (?)',
[ARGS.pattern])
try:
path = sorted([row for row in cursor])[0][1]
replace_map = {' ': '\\ ', '"': '\\"', "'": "\\'"}
for key, val in replace_map.iteritems():
path = path.replace(key, val)
os.system('{0} {1} &'.format(ARGS.player, path))
except IndexError:
exit('Error: Movie not found.') | Open the matched movie with a media player. |
def normalize(name):
ret = name.replace(':', '')
ret = ret.replace('%', '')
ret = ret.replace(' ', '_')
return ret | Normalize name for the Statsd convention |
def all(self, components_in_and=True):
self.components_in_and = components_in_and
return [obj for obj in iter(self)] | Return all of the results of a query in a list |
def delay(self):
delay = {'departure_time': None, 'departure_delay': None, 'requested_differs': None,
'remarks': self.trip_remarks, 'parts': []}
if self.departure_time_actual > self.departure_time_planned:
delay['departure_delay'] = self.departure_time_actual - self.departure_time_planned
delay['departure_time'] = self.departure_time_actual
if self.requested_time != self.departure_time_actual:
delay['requested_differs'] = self.departure_time_actual
for part in self.trip_parts:
if part.has_delay:
delay['parts'].append(part)
return delay | Return the delay of the train for this instance |
def global_max(col_vals, index):
col_vals_without_None = [x for x in col_vals if x is not None]
max_col, min_col = zip(*col_vals_without_None)
return max(max_col), min(min_col) | Returns the global maximum and minimum. |
def _disambiguate_pos(self, terms, pos):
candidate_map = {term: wn.synsets(term, pos=pos)[:3] for term in terms}
concepts = set(c for cons in candidate_map.values() for c in cons)
concepts = list(concepts)
sim_mat = self._similarity_matrix(concepts)
map = {}
for term, cons in candidate_map.items():
if not cons:
continue
scores = []
for con in cons:
i = concepts.index(con)
scores_ = []
for term_, cons_ in candidate_map.items():
if term == term_ or not cons_:
continue
cons_idx = [concepts.index(c) for c in cons_]
top_sim = max(sim_mat[i,cons_idx])
scores_.append(top_sim)
scores.append(sum(scores_))
best_idx = np.argmax(scores)
map[term] = cons[best_idx]
return map | Disambiguates a list of tokens of a given PoS. |
def access_list(package):
team, owner, pkg = parse_package(package)
session = _get_session(team)
lookup_url = "{url}/api/access/{owner}/{pkg}/".format(url=get_registry_url(team), owner=owner, pkg=pkg)
response = session.get(lookup_url)
data = response.json()
users = data['users']
print('\n'.join(users)) | Print list of users who can access a package. |
def dist_dir(self):
if self.distribution is None:
warning('Tried to access {}.dist_dir, but {}.distribution '
'is None'.format(self, self))
exit(1)
return self.distribution.dist_dir | The dist dir at which to place the finished distribution. |
def disable(self):
self.engine.data.update(sandbox_type='none')
self.pop('cloud_sandbox_settings', None)
self.pop('sandbox_settings', None) | Disable the sandbox on this engine. |
def evaluate_binop_logical(self, operation, left, right, **kwargs):
if not operation in self.binops_logical:
raise ValueError("Invalid logical binary operation '{}'".format(operation))
result = self.binops_logical[operation](left, right)
return bool(result) | Evaluate given logical binary operation with given operands. |
def secondary_spin(mass1, mass2, spin1, spin2):
mass1, mass2, spin1, spin2, input_is_array = ensurearray(
mass1, mass2, spin1, spin2)
ss = copy.copy(spin2)
mask = mass1 < mass2
ss[mask] = spin1[mask]
return formatreturn(ss, input_is_array) | Returns the dimensionless spin of the secondary mass. |
def use_plenary_assessment_offered_view(self):
self._object_views['assessment_offered'] = PLENARY
for session in self._get_provider_sessions():
try:
session.use_plenary_assessment_offered_view()
except AttributeError:
pass | Pass through to provider AssessmentOfferedLookupSession.use_plenary_assessment_offered_view |
def visit_AST_or(self, pattern):
return any(self.field_match(self.node, value_or)
for value_or in pattern.args) | Match if any of the or content match with the other node. |
def run(self):
for rel_path in sorted(self.paths):
file_path = join(self.data_dir, rel_path)
self.minify(file_path)
after = self.size_of(self.after_total)
before = self.size_of(self.before_total)
saved = self.size_of(self.before_total - self.after_total)
template = '\nTotal: ' \
'\033[92m{}\033[0m -> \033[92m{}\033[0m. ' \
'Compressed: \033[92m{}\033[0m\n'
print(template.format(before, after, saved)) | Start json minimizer and exit when all json files were minimized. |
def IsFileStatEntry(self, original_result):
return (original_result.pathspec.pathtype in [
rdf_paths.PathSpec.PathType.OS, rdf_paths.PathSpec.PathType.TSK
]) | Checks if given RDFValue is a file StatEntry. |
def secp256r1():
GFp = FiniteField(int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", 16))
ec = EllipticCurve(GFp, 115792089210356248762697446949407573530086143415290314195533631308867097853948, 41058363725152142129326129780047268409114441015993725554835256314039467401291)
return ECDSA(ec,
ec.point(0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296, 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5),
GFp) | create the secp256r1 curve |
def extractSeqAndQuals(seq, quals, umi_bases, cell_bases, discard_bases,
retain_umi=False):
new_seq = ""
new_quals = ""
umi_quals = ""
cell_quals = ""
ix = 0
for base, qual in zip(seq, quals):
if ((ix not in discard_bases) and
(ix not in cell_bases)):
if retain_umi:
new_quals += qual
new_seq += base
umi_quals += qual
else:
if ix not in umi_bases:
new_quals += qual
new_seq += base
else:
umi_quals += qual
elif ix in cell_bases:
cell_quals += qual
ix += 1
return new_seq, new_quals, umi_quals, cell_quals | Remove selected bases from seq and quals |
def _empty_notification(self):
sess = cherrypy.session
username = sess.get(SESSION_KEY, None)
if username in self.notifications:
ret = self.notifications[username]
else:
ret = []
self.notifications[username] = []
return ret | empty and return list of message notification |
def from_pillow(pil_image):
pil_image = pil_image.convert('RGB')
cv2_image = np.array(pil_image)
cv2_image = cv2_image[:, :, ::-1].copy()
return cv2_image | Convert from pillow image to opencv |
def _upgrades(self, sid, transport):
if not self.allow_upgrades or self._get_socket(sid).upgraded or \
self._async['websocket'] is None or transport == 'websocket':
return []
return ['websocket'] | Return the list of possible upgrades for a client connection. |
def to_string(self):
node = quote_if_necessary(self.obj_dict['name'])
node_attr = list()
for attr in sorted(self.obj_dict['attributes']):
value = self.obj_dict['attributes'][attr]
if value == '':
value = '""'
if value is not None:
node_attr.append(
'%s=%s' % (attr, quote_if_necessary(value) ) )
else:
node_attr.append( attr )
if node in ('graph', 'node', 'edge') and len(node_attr) == 0:
return ''
node_attr = ', '.join(node_attr)
if node_attr:
node += ' [' + node_attr + ']'
return node + ';' | Return string representation of node in DOT language. |
def _primary_input(self, index):
primary_input = z.ZcashByteData()
primary_input += self.tx_joinsplits[index].anchor
primary_input += self.tx_joinsplits[index].nullifiers
primary_input += self.tx_joinsplits[index].commitments
primary_input += self.tx_joinsplits[index].vpub_old
primary_input += self.tx_joinsplits[index].vpub_new
primary_input += self.hsigs[index]
primary_input += self.tx_joinsplits[index].vmacs
return primary_input.to_bytes() | Primary input for the zkproof |
def measurement_time_typical(self):
meas_time_ms = 1.0
if self.overscan_temperature != OVERSCAN_DISABLE:
meas_time_ms += (2 * _BME280_OVERSCANS.get(self.overscan_temperature))
if self.overscan_pressure != OVERSCAN_DISABLE:
meas_time_ms += (2 * _BME280_OVERSCANS.get(self.overscan_pressure) + 0.5)
if self.overscan_humidity != OVERSCAN_DISABLE:
meas_time_ms += (2 * _BME280_OVERSCANS.get(self.overscan_humidity) + 0.5)
return meas_time_ms | Typical time in milliseconds required to complete a measurement in normal mode |
def extract_date(value):
dtime = value.to_datetime()
dtime = (dtime - timedelta(hours=dtime.hour) - timedelta(minutes=dtime.minute) -
timedelta(seconds=dtime.second) - timedelta(microseconds=dtime.microsecond))
return dtime | Convert timestamp to datetime and set everything to zero except a date |
def layers():
global _cached_layers
if _cached_layers is not None:
return _cached_layers
layers_module = tf.layers
try:
from tensorflow.python import tf2
if tf2.enabled():
tf.logging.info("Running in V2 mode, using Keras layers.")
layers_module = tf.keras.layers
except ImportError:
pass
_cached_layers = layers_module
return layers_module | Get the layers module good for TF 1 and TF 2 work for now. |
def __get_default_settings(self):
LOGGER.debug("> Accessing '{0}' default settings file!".format(UiConstants.settings_file))
self.__default_settings = QSettings(
umbra.ui.common.get_resource_path(UiConstants.settings_file), QSettings.IniFormat) | Gets the default settings. |
def sample(self, hash, limit=None, offset=None):
uri = self._uris['sample'].format(hash)
params = {'limit': limit, 'offset': offset}
return self.get_parse(uri, params) | Return an object representing the sample identified by the input hash, or an empty object if that sample is not found |
def applied():
upgrader = InvenioUpgrader()
logger = upgrader.get_logger()
try:
upgrades = upgrader.get_history()
if not upgrades:
logger.info("No upgrades have been applied.")
return
logger.info("Following upgrade(s) have been applied:")
for u_id, applied in upgrades:
logger.info(" * %s (%s)" % (u_id, applied))
except RuntimeError as e:
for msg in e.args:
logger.error(unicode(msg))
raise | Command for showing all upgrades already applied. |
def _update_gmt(self):
if self.simulation_start is not None:
offset_string = str(self.simulation_start.replace(tzinfo=self.tz)
.utcoffset().total_seconds()/3600.)
self._update_card('GMT', offset_string) | Based on timezone and start date, the GMT card is updated |
def tokenize(self, text, context=0, skip_style_tags=False):
split = self.regex.split(text)
self._text = [segment for segment in split if segment]
self._head = self._global = self._depth = 0
self._bad_routes = set()
self._skip_style_tags = skip_style_tags
try:
tokens = self._parse(context)
except BadRoute:
raise ParserError("Python tokenizer exited with BadRoute")
if self._stacks:
err = "Python tokenizer exited with non-empty token stack"
raise ParserError(err)
return tokens | Build a list of tokens from a string of wikicode and return it. |
def parse_object(self, data):
for key, value in data.items():
if isinstance(value, (str, type(u''))) and \
self.strict_iso_match.match(value):
data[key] = dateutil.parser.parse(value)
return data | Look for datetime looking strings. |
def create(cls, parent, child, relation_type, index=None):
try:
with db.session.begin_nested():
obj = cls(parent_id=parent.id,
child_id=child.id,
relation_type=relation_type,
index=index)
db.session.add(obj)
except IntegrityError:
raise Exception("PID Relation already exists.")
return obj | Create a PID relation for given parent and child. |
def _do_sse_request(self, path, params=None):
urls = [''.join([server.rstrip('/'), path]) for server in self.servers]
while urls:
url = urls.pop()
try:
response = self.sse_session.get(
url,
params=params,
stream=True,
headers={'Accept': 'text/event-stream'},
auth=self.auth,
verify=self.verify,
allow_redirects=False
)
except Exception as e:
marathon.log.error(
'Error while calling %s: %s', url, e.message)
else:
if response.is_redirect and response.next:
urls.append(response.next.url)
marathon.log.debug("Got redirect to {}".format(response.next.url))
elif response.ok:
return response.iter_lines()
raise MarathonError('No remaining Marathon servers to try') | Query Marathon server for events. |
def delete_subject(self, subject_id):
uri = self._get_subject_uri(guid=subject_id)
return self.service._delete(uri) | Remove a specific subject by its identifier. |
def run_commands(self, commands):
if "eos" in self.profile:
return list(self.parent.cli(commands).values())[0]
else:
raise AttributeError("MockedDriver instance has not attribute '_rpc'") | Only useful for EOS |
def analysis_period(self):
return AnalysisPeriod(
self.sky_condition.month,
self.sky_condition.day_of_month,
0,
self.sky_condition.month,
self.sky_condition.day_of_month,
23) | The analysisperiod of the design day. |
def get():
uptime = time.time() - START_TIME
response = dict(uptime=f'{uptime:.2f}s',
links=dict(root='{}'.format(get_root_url())))
return response, HTTPStatus.OK | Check the health of this service |
def watch_firings(self, flag):
lib.EnvSetDefruleWatchFirings(self._env, int(flag), self._rule) | Whether or not the Rule firings are being watched. |
def custom_check(cmd, ignore_retcode=False):
p = custom_popen(cmd)
out, _ = p.communicate()
if p.returncode and not ignore_retcode:
raise RarExecError("Check-run failed")
return out | Run command, collect output, raise error if needed. |
def _get_dns_entry_trs(self):
from bs4 import BeautifulSoup
dns_list_response = self.session.get(
self.URLS['dns'].format(self.domain_id))
self._log('DNS list', dns_list_response)
assert dns_list_response.status_code == 200, \
'Could not load DNS entries.'
html = BeautifulSoup(dns_list_response.content, 'html.parser')
self._log('DNS list', html)
dns_table = html.find('table', {'id': 'cp_domains_dnseintraege'})
assert dns_table is not None, 'Could not find DNS entry table'
def _is_zone_tr(elm):
has_ondblclick = elm.has_attr('ondblclick')
has_class = elm.has_attr('class')
return elm.name.lower() == 'tr' and (has_class or has_ondblclick)
rows = dns_table.findAll(_is_zone_tr)
assert rows is not None and rows, 'Could not find any DNS entries'
return rows | Return the TR elements holding the DNS entries. |
def _FlushInput(self):
self.ser.flush()
flushed = 0
while True:
ready_r, ready_w, ready_x = select.select([self.ser], [],
[self.ser], 0)
if len(ready_x) > 0:
logging.error("Exception from serial port.")
return None
elif len(ready_r) > 0:
flushed += 1
self.ser.read(1)
self.ser.flush()
else:
break | Flush all read data until no more available. |
def _debug_line(linenum: int, line: str, extramsg: str = "") -> None:
log.critical("{}Line {}: {!r}", extramsg, linenum, line) | Writes a debugging report on a line. |
def objectprep(self):
self.runmetadata = createobject.ObjectCreation(self)
if self.extension == 'fastq':
logging.info('Decompressing and combining .fastq files for CLARK analysis')
fileprep.Fileprep(self)
else:
logging.info('Using .fasta files for CLARK analysis')
for sample in self.runmetadata.samples:
sample.general.combined = sample.general.fastqfiles[0] | Create objects to store data and metadata for each sample. Also, perform necessary file manipulations |
def lex(filename):
with io.open(filename, mode='r', encoding='utf-8') as f:
it = _lex_file_object(f)
it = _balance_braces(it, filename)
for token, line, quoted in it:
yield (token, line, quoted) | Generates tokens from an nginx config file |
def influx_query_(self, q):
if self.influx_cli is None:
self.err(
self.influx_query_,
"No database connected. Please initialize a connection")
return
try:
return self.influx_cli.query(q)
except Exception as e:
self.err(e, self.influx_query_,
"Can not query database") | Runs an Influx db query |
def create_loadfile(entities, f):
with open(f, 'w') as out:
out.write(Entity.create_payload(entities)) | Create payload and save to file. |
def rand_alphastr(length, lower=True, upper=True):
if lower is True and upper is True:
return rand_str(length, allowed=string.ascii_letters)
if lower is True and upper is False:
return rand_str(length, allowed=string.ascii_lowercase)
if lower is False and upper is True:
return rand_str(length, allowed=string.ascii_uppercase)
else:
raise Exception | Generate fixed-length random alpha only string. |
def rebin2x2(a):
inshape = np.array(a.shape)
if not (inshape % 2 == np.zeros(2)).all():
raise RuntimeError, "I want even image shapes !"
return rebin(a, inshape/2) | Wrapper around rebin that actually rebins 2 by 2 |
def stream_url(self):
rtsp_url = RTSP_URL.format(
host=self.config.host, video=self.video_query,
audio=self.audio_query, event=self.event_query)
_LOGGER.debug(rtsp_url)
return rtsp_url | Build url for stream. |
def validate_required_attributes(fully_qualified_name: str, spec: Dict[str, Any],
*attributes: str) -> List[RequiredAttributeError]:
return [
RequiredAttributeError(fully_qualified_name, spec, attribute)
for attribute in attributes
if attribute not in spec
] | Validates to ensure that a set of attributes are present in spec |
def select_molecules(name):
mol_formula = current_system().get_derived_molecule_array('formula')
mask = mol_formula == name
ind = current_system().mol_to_atom_indices(mask.nonzero()[0])
selection = {'atoms': Selection(ind, current_system().n_atoms)}
b = current_system().bonds
if len(b) == 0:
selection['bonds'] = Selection([], 0)
else:
molbonds = np.zeros(len(b), 'bool')
for i in ind:
matching = (i == b).sum(axis=1).astype('bool')
molbonds[matching] = True
selection['bonds'] = Selection(molbonds.nonzero()[0], len(b))
return select_selection(selection) | Select all the molecules corresponding to the formulas. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.