code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def months_ago(date, nb_months=1):
nb_years = nb_months // 12
nb_months = nb_months % 12
month_diff = date.month - nb_months
if month_diff > 0:
new_month = month_diff
else:
new_month = 12 + month_diff
nb_years += 1
return date.replace(day=1, month=new_month, year=date.year - nb_years) | Return the given `date` with `nb_months` substracted from it. |
def _fill_argparser(self, parser):
for key, val in self._options.items():
add_argument(parser, key, val) | Fill an `argparser.ArgumentParser` with the options from this chain |
def callHook(self, hookname, *args, **kwargs):
'Call all functions registered with `addHook` for the given hookname.'
r = []
for f in self.hooks[hookname]:
try:
r.append(f(*args, **kwargs))
except Exception as e:
exceptionCaught(e)
return r | Call all functions registered with `addHook` for the given hookname. |
def get(self):
if self.bucket.get() < 1:
return None
now = time.time()
self.mutex.acquire()
try:
task = self.priority_queue.get_nowait()
self.bucket.desc()
except Queue.Empty:
self.mutex.release()
return None
task.exetime = now + self.processing_timeout
self.processing.put(task)
self.mutex.release()
return task.taskid | Get a task from queue when bucket available |
def recursively_resume_states(self):
super(ContainerState, self).recursively_resume_states()
for state in self.states.values():
state.recursively_resume_states() | Resume the state and all of it child states. |
def toListInt(value):
if TypeConverters._can_convert_to_list(value):
value = TypeConverters.toList(value)
if all(map(lambda v: TypeConverters._is_integer(v), value)):
return [int(v) for v in value]
raise TypeError("Could not convert %s to list of ints" % value) | Convert a value to list of ints, if possible. |
def delete_name(name):
session = create_session()
try:
user = session.query(User).filter_by(name=name).first()
session.delete(user)
session.commit()
except SQLAlchemyError, e:
session.rollback()
raise bottle.HTTPError(500, "Database Error", e)
finally:
session.close() | This function don't use the plugin. |
def contour_mask(self, contour):
new_data = np.zeros(self.data.shape)
num_boundary = contour.boundary_pixels.shape[0]
boundary_px_ij_swapped = np.zeros([num_boundary, 1, 2])
boundary_px_ij_swapped[:, 0, 0] = contour.boundary_pixels[:, 1]
boundary_px_ij_swapped[:, 0, 1] = contour.boundary_pixels[:, 0]
cv2.fillPoly(
new_data, pts=[
boundary_px_ij_swapped.astype(
np.int32)], color=(
BINARY_IM_MAX_VAL, BINARY_IM_MAX_VAL, BINARY_IM_MAX_VAL))
orig_zeros = np.where(self.data == 0)
new_data[orig_zeros[0], orig_zeros[1]] = 0
return BinaryImage(new_data.astype(np.uint8), frame=self._frame) | Generates a binary image with only the given contour filled in. |
def verify_email(self, action_token, signed_data):
try:
action = "verify-email"
user = get_user_by_action_token(action, action_token)
if not user or not user.signed_data_match(signed_data, action):
raise mocha_exc.AppError("Verification Invalid!")
else:
user.set_email_verified(True)
flash_success("Account verified. You can now login")
username = user.username
if user.login_method == "email":
username = user.email
return redirect(self.login, username=username)
except Exception as e:
logging.exception(e)
flash_error("Verification Failed!")
return redirect(self.login) | Verify email account, in which a link was sent to |
def stop(self, sig=signal.SIGINT):
for cpid in self.sandboxes:
logger.warn('Stopping %i...' % cpid)
try:
os.kill(cpid, sig)
except OSError:
logger.exception('Error stopping %s...' % cpid)
for cpid in list(self.sandboxes):
try:
logger.info('Waiting for %i...' % cpid)
pid, status = os.waitpid(cpid, 0)
logger.warn('%i stopped with status %i' % (pid, status >> 8))
except OSError:
logger.exception('Error waiting for %i...' % cpid)
finally:
self.sandboxes.pop(cpid, None) | Stop all the workers, and then wait for them |
def generate_ngrams(args, parser):
store = utils.get_data_store(args)
corpus = utils.get_corpus(args)
if args.catalogue:
catalogue = utils.get_catalogue(args)
else:
catalogue = None
store.add_ngrams(corpus, args.min_size, args.max_size, catalogue) | Adds n-grams data to the data store. |
def load(config_file):
with open(config_file, "r") as f:
def env_get():
return dict(os.environ)
tmpl = Template(f.read())
return Config(yaml.load(tmpl.render(**env_get()))) | Processes and loads config file. |
def crop_to_sheet(self,sheet_coord_system):
"Crop the slice to the SheetCoordinateSystem's bounds."
maxrow,maxcol = sheet_coord_system.shape
self[0] = max(0,self[0])
self[1] = min(maxrow,self[1])
self[2] = max(0,self[2])
self[3] = min(maxcol,self[3]) | Crop the slice to the SheetCoordinateSystem's bounds. |
def removeIndividual(self, individual):
q = models.Individual.delete().where(
models.Individual.id == individual.getId())
q.execute() | Removes the specified individual from this repository. |
def update_insert_values(bel_resource: Mapping, mapping: Mapping[str, Tuple[str, str]], values: Dict[str, str]) -> None:
for database_column, (section, key) in mapping.items():
if section in bel_resource and key in bel_resource[section]:
values[database_column] = bel_resource[section][key] | Update the value dictionary with a BEL resource dictionary. |
def allow_user(user):
def processor(action, argument):
db.session.add(
ActionUsers.allow(action, argument=argument, user_id=user.id)
)
return processor | Allow a user identified by an email address. |
def output_vlan(gandi, vlan, datacenters, output_keys, justify=10):
output_generic(gandi, vlan, output_keys, justify)
if 'dc' in output_keys:
for dc in datacenters:
if dc['id'] == vlan.get('datacenter_id',
vlan.get('datacenter', {}).get('id')):
dc_name = dc.get('dc_code', dc.get('iso', ''))
break
output_line(gandi, 'datacenter', dc_name, justify) | Helper to output a vlan information. |
def submit_url(self, url, params={}, _extra_params={}):
self._check_user_parameters(params)
params = copy.copy(params)
params['url'] = url
return self._submit(params, _extra_params=_extra_params) | Submit a website for analysis. |
def data_context(fn, mode="r"):
with open(data_context_name(fn), mode) as f:
return f.read() | Return content fo the `fn` from the `template_data` directory. |
def customer(self):
url = self._get_link('customer')
if url:
resp = self.client.customers.perform_api_call(self.client.customers.REST_READ, url)
return Customer(resp) | Return the customer for this subscription. |
def gather_metrics(self, runs):
for run_dirs in runs.values():
with open(JSON_METRICS_FILE, 'w') as ostr:
ostr.write('[\n')
for i in range(len(run_dirs)):
with open(osp.join(run_dirs[i], YAML_REPORT_FILE)) as istr:
data = yaml.safe_load(istr)
data.pop('category', None)
data.pop('command', None)
data['id'] = run_dirs[i]
json.dump(data, ostr, indent=2)
if i != len(run_dirs) - 1:
ostr.write(',')
ostr.write('\n')
ostr.write(']\n') | Write a JSON file with the result of every runs |
async def handle_agent_job_started(self, agent_addr, message: AgentJobStarted):
self._logger.debug("Job %s %s started on agent %s", message.job_id[0], message.job_id[1], agent_addr)
await ZMQUtils.send_with_addr(self._client_socket, message.job_id[0], BackendJobStarted(message.job_id[1])) | Handle an AgentJobStarted message. Send the data back to the client |
def meth_acl(args):
r = fapi.get_repository_method_acl(args.namespace, args.method,
args.snapshot_id)
fapi._check_response_code(r, 200)
acls = sorted(r.json(), key=lambda k: k['user'])
return map(lambda acl: '{0}\t{1}'.format(acl['user'], acl['role']), acls) | Retrieve access control list for given version of a repository method |
def _compute_fval(X, A, R, P, Z, lmbdaA, lmbdaR, lmbdaZ, normX):
f = lmbdaA * norm(A) ** 2
for i in range(len(X)):
ARAt = dot(A, dot(R[i], A.T))
f += (norm(X[i] - ARAt) ** 2) / normX[i] + lmbdaR * norm(R[i]) ** 2
return f | Compute fit for full slices |
def browse_outdir(self):
self.dirsel.popup(
'Select directory', self.w.outdir.set_text, initialdir=self.outdir)
self.set_outdir() | Browse for output directory. |
def to_datetime(t):
if t is None:
return None
year, mon, day, h, m, s = t
try:
return datetime(year, mon, day, h, m, s)
except ValueError:
pass
mday = (0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
if mon < 1:
mon = 1
if mon > 12:
mon = 12
if day < 1:
day = 1
if day > mday[mon]:
day = mday[mon]
if h > 23:
h = 23
if m > 59:
m = 59
if s > 59:
s = 59
if mon == 2 and day == 29:
try:
return datetime(year, mon, day, h, m, s)
except ValueError:
day = 28
return datetime(year, mon, day, h, m, s) | Convert 6-part time tuple into datetime object. |
def total(self):
total = 0
for item in self.items.all():
total += item.total
return total | Total cost of the order |
def from_kwargs(cls, **kwargs):
config = cls()
for slot in cls.__slots__:
if slot.startswith('_'):
slot = slot[1:]
setattr(config, slot, kwargs.pop(slot, cls.get_default(slot)))
if kwargs:
raise ValueError("Unrecognized option(s): {}".format(kwargs.keys()))
return config | Initialise configuration from kwargs. |
def delete(self):
res = self.session.delete(self.href)
self.emit('deleted', self)
return res | Delete resource from the API server |
def super_mro(self):
if not isinstance(self.mro_pointer, scoped_nodes.ClassDef):
raise exceptions.SuperError(
"The first argument to super must be a subtype of "
"type, not {mro_pointer}.",
super_=self,
)
if isinstance(self.type, scoped_nodes.ClassDef):
self._class_based = True
mro_type = self.type
else:
mro_type = getattr(self.type, "_proxied", None)
if not isinstance(mro_type, (bases.Instance, scoped_nodes.ClassDef)):
raise exceptions.SuperError(
"The second argument to super must be an "
"instance or subtype of type, not {type}.",
super_=self,
)
if not mro_type.newstyle:
raise exceptions.SuperError(
"Unable to call super on old-style classes.", super_=self
)
mro = mro_type.mro()
if self.mro_pointer not in mro:
raise exceptions.SuperError(
"The second argument to super must be an "
"instance or subtype of type, not {type}.",
super_=self,
)
index = mro.index(self.mro_pointer)
return mro[index + 1 :] | Get the MRO which will be used to lookup attributes in this super. |
def insert(self, space_no, *args):
d = self.replyQueue.get()
packet = RequestInsert(self.charset, self.errors, d._ipro_request_id, space_no, Request.TNT_FLAG_ADD, *args)
self.transport.write(bytes(packet))
return d.addCallback(self.handle_reply, self.charset, self.errors, None) | insert tuple, if primary key exists server will return error |
def server_link(rel, server_id=None, self_rel=False):
servers_href = '/v1/servers'
link = _SERVER_LINKS[rel].copy()
link['href'] = link['href'].format(**locals())
link['rel'] = 'self' if self_rel else rel
return link | Helper for getting a Server link document, given a rel. |
def connect_to_cloud_cdn(region=None):
global default_region
if region in ['DFW', 'IAD', 'ORD', 'SYD', 'HKG']:
return _create_client(ep_name="cdn", region="DFW")
elif region in ['LON']:
return _create_client(ep_name="cdn", region="LON")
else:
if default_region in ['DFW', 'IAD', 'ORD', 'SYD', 'HKG']:
return _create_client(ep_name="cdn", region="DFW")
elif default_region in ['LON']:
return _create_client(ep_name="cdn", region="LON")
else:
return _create_client(ep_name="cdn", region=region) | Creates a client for working with cloud loadbalancers. |
def GetClosestPoint(x, a, b):
assert(x.IsUnitLength())
assert(a.IsUnitLength())
assert(b.IsUnitLength())
a_cross_b = a.RobustCrossProd(b)
p = x.Minus(
a_cross_b.Times(
x.DotProd(a_cross_b) / a_cross_b.Norm2()))
if SimpleCCW(a_cross_b, a, p) and SimpleCCW(p, b, a_cross_b):
return p.Normalize()
if x.Minus(a).Norm2() <= x.Minus(b).Norm2():
return a
else:
return b | Returns the point on the great circle segment ab closest to x. |
def layer_tagger_mapping(self):
return {
PARAGRAPHS: self.tokenize_paragraphs,
SENTENCES: self.tokenize_sentences,
WORDS: self.tokenize_words,
ANALYSIS: self.tag_analysis,
TIMEXES: self.tag_timexes,
NAMED_ENTITIES: self.tag_named_entities,
CLAUSE_ANNOTATION: self.tag_clause_annotations,
CLAUSES: self.tag_clauses,
LAYER_CONLL: self.tag_syntax_vislcg3,
LAYER_VISLCG3: self.tag_syntax_maltparser,
WORDNET: self.tag_wordnet
} | Dictionary that maps layer names to taggers that can create that layer. |
def btc_is_p2wpkh_address( address ):
wver, whash = segwit_addr_decode(address)
if whash is None:
return False
if len(whash) != 20:
return False
return True | Is the given address a p2wpkh address? |
def tag(self, tagname, message=None, force=True):
return git_tag(self.repo_dir, tagname, message=message, force=force) | Create an annotated tag. |
def convert_output_to_v4(self, controller_input):
player_input = SimpleControllerState()
player_input.throttle = controller_input[0]
player_input.steer = controller_input[1]
player_input.pitch = controller_input[2]
player_input.yaw = controller_input[3]
player_input.roll = controller_input[4]
player_input.jump = controller_input[5]
player_input.boost = controller_input[6]
player_input.handbrake = controller_input[7]
return player_input | Converts a v3 output to a v4 controller state |
def send(self, message):
log.debug("sending '{0}' message".format(message.type))
send_miu = self.socket.getsockopt(nfc.llcp.SO_SNDMIU)
try:
data = str(message)
except nfc.llcp.EncodeError as e:
log.error("message encoding failed: {0}".format(e))
else:
return self._send(data, send_miu) | Send a handover request message to the remote server. |
def _match_minimum_date_time(self, match_key, date_time_value, match=True):
if match:
gtelt = '$gte'
else:
gtelt = '$lt'
if match_key in self._query_terms:
self._query_terms[match_key][gtelt] = date_time_value
else:
self._query_terms[match_key] = {gtelt: date_time_value} | Matches a minimum date time value |
def simhash(self, content):
if content is None:
self.hash = -1
return
if isinstance(content, str):
features = self.tokenizer_func(content, self.keyword_weight_pari)
self.hash = self.build_from_features(features)
elif isinstance(content, collections.Iterable):
self.hash = self.build_from_features(content)
elif isinstance(content, int):
self.hash = content
else:
raise Exception("Unsupported parameter type %s" % type(content)) | Select policies for simhash on the different types of content. |
def _common_prefix(names):
if not names:
return ''
prefix = names[0]
for name in names:
i = 0
while i < len(prefix) and i < len(name) and prefix[i] == name[i]:
i += 1
prefix = prefix[:i]
return prefix | Get the common prefix for all names |
def elements(self):
offset = self.EXTRA_DIGITS
if offset:
return (self._id[:offset], self.company_prefix, self._reference,
self.check_digit)
else:
return (self.company_prefix, self._reference, self.check_digit) | Return the identifier's elements as tuple. |
def add_contact(self):
self.api.lists.addcontact(
contact=self.cleaned_data['email'], id=self.list_id, method='POST') | Create a contact with using the email on the list. |
async def _wrap_ws(self, handler, *args, **kwargs):
try:
method = self.request_method()
data = await handler(self, *args, **kwargs)
status = self.responses.get(method, OK)
response = {
'type': 'response',
'key': getattr(self.request, 'key', None),
'status': status,
'payload': data
}
except Exception as ex:
response = {
'type': 'response',
'key': getattr(self.request, 'key', None),
'status': getattr(ex, 'status', 500),
'payload': getattr(ex, 'msg', 'general error')
}
return self.format(method, response) | wraps a handler by receiving a websocket request and returning a websocket response |
def api_send_mail(request, key=None, hproPk=None):
if not check_api_key(request, key, hproPk):
return HttpResponseForbidden
sender = request.POST.get('sender', settings.MAIL_SENDER)
dests = request.POST.getlist('dests')
subject = request.POST['subject']
message = request.POST['message']
html_message = request.POST.get('html_message')
if html_message and html_message.lower() == 'false':
html_message = False
if 'response_id' in request.POST:
key = hproPk + ':' + request.POST['response_id']
else:
key = None
generic_send_mail(sender, dests, subject, message, key, 'PlugIt API (%s)' % (hproPk or 'StandAlone',), html_message)
return HttpResponse(json.dumps({}), content_type="application/json") | Send a email. Posts parameters are used |
def explain_weights_sklearn(estimator, vec=None, top=_TOP,
target_names=None,
targets=None,
feature_names=None, coef_scale=None,
feature_re=None, feature_filter=None):
return explain_weights_sklearn_not_supported(estimator) | Return an explanation of an estimator |
def _init_server_authentication(self, ssl_verify: OpenSslVerifyEnum, ssl_verify_locations: Optional[str]) -> None:
self._ssl_ctx.set_verify(ssl_verify.value)
if ssl_verify_locations:
with open(ssl_verify_locations):
pass
self._ssl_ctx.load_verify_locations(ssl_verify_locations) | Setup the certificate validation logic for authenticating the server. |
def match_to_dict(self, match, gids):
values = {}
for gid in gids:
try:
values[gid] = self.map_value(match.group(gid), gid)
except IndexError:
pass
return values | Map values from match into a dictionary. |
def handle_modifier_down(self, modifier):
_logger.debug("%s pressed", modifier)
if modifier in (Key.CAPSLOCK, Key.NUMLOCK):
if self.modifiers[modifier]:
self.modifiers[modifier] = False
else:
self.modifiers[modifier] = True
else:
self.modifiers[modifier] = True | Updates the state of the given modifier key to 'pressed' |
def update(self, other):
Cluster.update(self, other)
self.rules.extend(other.rules) | Extend the current cluster with data from another cluster |
def text_extract(path, password=None):
pdf = Info(path, password).pdf
return [pdf.getPage(i).extractText() for i in range(pdf.getNumPages())] | Extract text from a PDF file |
def paintEvent(self, event):
if self.isVisible() and self.position != self.Position.FLOATING:
self._background_brush = QBrush(QColor(
self.editor.sideareas_color))
self._foreground_pen = QPen(QColor(
self.palette().windowText().color()))
painter = QPainter(self)
painter.fillRect(event.rect(), self._background_brush) | Fills the panel background using QPalette. |
def _twig_to_uniqueid(bundle, twig, **kwargs):
res = bundle.filter(twig=twig, force_ps=True, check_visible=False, check_default=False, **kwargs)
if len(res) == 1:
return res.to_list()[0].uniqueid
else:
raise ValueError("did not return a single unique match to a parameter for '{}'".format(twig)) | kwargs are passed on to filter |
def run(url, cmd, log_path, log_level, log_session, force_discovery, print_info):
log_level = log_levels[log_level]
conn = condoor.Connection("host", list(url), log_session=log_session, log_level=log_level, log_dir=log_path)
try:
conn.connect(force_discovery=force_discovery)
if print_info:
echo_info(conn)
for command in cmd:
result = conn.send(command)
print("\nCommand: {}".format(command))
print("Result: \n{}".format(result))
except (condoor.ConnectionError, condoor.ConnectionAuthenticationError, condoor.ConnectionTimeoutError,
condoor.InvalidHopInfoError, condoor.CommandSyntaxError, condoor.CommandTimeoutError,
condoor.CommandError, condoor.ConnectionError) as excpt:
click.echo(excpt)
finally:
conn.disconnect()
return | Run the main function. |
def run_friedman_smooth(x, y, span):
N = len(x)
weight = numpy.ones(N)
results = numpy.zeros(N)
residuals = numpy.zeros(N)
mace.smooth(x, y, weight, span, 1, 1e-7, results, residuals)
return results, residuals | Run the FORTRAN smoother. |
def job_exists(self, prov):
with self.lock:
self.cur.execute('select * from "jobs" where "prov" = ?;', (prov,))
rec = self.cur.fetchone()
return rec is not None | Check if a job exists in the database. |
def _resizeCurrentColumnToContents(self, new_index, old_index):
if new_index.column() not in self._autosized_cols:
self._resizeVisibleColumnsToContents()
self.dataTable.scrollTo(new_index) | Resize the current column to its contents. |
def reopen(args):
if not args.isadmin:
return "Nope, not gonna do it."
msg = args.msg.split()
if not msg:
return "Syntax: !poll reopen <pollnum>"
if not msg[0].isdigit():
return "Not a valid positve integer."
pid = int(msg[0])
poll = get_open_poll(args.session, pid)
if poll is None:
return "That poll doesn't exist or has been deleted!"
poll.active = 1
return "Poll %d reopened!" % pid | reopens a closed poll. |
def _file_path(self, src_path, dest, regex):
m = re.search(regex, src_path)
if dest.endswith('/') or dest == '':
dest += '{filename}'
names = m.groupdict()
if not names and m.groups():
names = {'filename': m.groups()[-1]}
for name, value in names.items():
dest = dest.replace('{%s}' % name, value)
dest = dest.strip(' /')
if not dest:
progress_logger.error('destination path must not resolve to be null')
raise GrablibError('bad path')
new_path = self.download_root.joinpath(dest)
new_path.relative_to(self.download_root)
return new_path | check src_path complies with regex and generate new filename |
def encode(data, mime_type='', charset='utf-8', base64=True):
if isinstance(data, six.text_type):
data = data.encode(charset)
else:
charset = None
if base64:
data = utils.text(b64encode(data))
else:
data = utils.text(quote(data))
result = ['data:', ]
if mime_type:
result.append(mime_type)
if charset:
result.append(';charset=')
result.append(charset)
if base64:
result.append(';base64')
result.append(',')
result.append(data)
return ''.join(result) | Encode data to DataURL |
def unknown_command(self, args):
mode_mapping = self.master.mode_mapping()
mode = args[0].upper()
if mode in mode_mapping:
self.master.set_mode(mode_mapping[mode])
return True
return False | handle mode switch by mode name as command |
def apseudo(Ss, ipar, sigma):
Is = random.randint(0, len(Ss) - 1, size=len(Ss))
if not ipar:
BSs = Ss[Is]
else:
A, B = design(6)
K, BSs = [], []
for k in range(len(Ss)):
K.append(np.dot(A, Ss[k][0:6]))
Pars = np.random.normal(K, sigma)
for k in range(len(Ss)):
BSs.append(np.dot(B, Pars[k]))
return np.array(BSs) | draw a bootstrap sample of Ss |
def calculate_metrics(self, model, train_loader, valid_loader, metrics_dict):
self.log_count += 1
log_valid = (
valid_loader is not None
and self.valid_every_X
and not (self.log_count % self.valid_every_X)
)
metrics_dict = {}
if self.config["log_train_metrics_func"] is not None:
func = self.config["log_train_metrics_func"]
func_list = func if isinstance(func, list) else [func]
for func in func_list:
metrics_dict = self._calculate_custom_metrics(
model, train_loader, func, metrics_dict, split="train"
)
if self.config["log_valid_metrics_func"] is not None and log_valid:
func = self.config["log_valid_metrics_func"]
func_list = func if isinstance(func, list) else [func]
for func in func_list:
metrics_dict = self._calculate_custom_metrics(
model, valid_loader, func, metrics_dict, split="valid"
)
metrics_dict = self._calculate_standard_metrics(
model, train_loader, self.log_train_metrics, metrics_dict, "train"
)
if log_valid:
metrics_dict = self._calculate_standard_metrics(
model, valid_loader, self.log_valid_metrics, metrics_dict, "valid"
)
return metrics_dict | Add standard and custom metrics to metrics_dict |
def create_command(self, name, operation, **kwargs):
if not isinstance(operation, six.string_types):
raise ValueError("Operation must be a string. Got '{}'".format(operation))
name = ' '.join(name.split())
client_factory = kwargs.get('client_factory', None)
def _command_handler(command_args):
op = CLICommandsLoader._get_op_handler(operation)
client = client_factory(command_args) if client_factory else None
result = op(client, **command_args) if client else op(**command_args)
return result
def arguments_loader():
return list(extract_args_from_signature(CLICommandsLoader._get_op_handler(operation),
excluded_params=self.excluded_command_handler_args))
def description_loader():
return extract_full_summary_from_signature(CLICommandsLoader._get_op_handler(operation))
kwargs['arguments_loader'] = arguments_loader
kwargs['description_loader'] = description_loader
cmd = self.command_cls(self.cli_ctx, name, _command_handler, **kwargs)
return cmd | Constructs the command object that can then be added to the command table |
def service(self, name: str = None):
if self._services_initialized:
from warnings import warn
warn('Services have already been initialized. Please register '
f'{name} sooner.')
return lambda x: x
def wrapper(service):
self.register_service(name, service)
return service
return wrapper | Decorator to mark something as a service. |
def new_revision(self, *fields):
if not self._id:
assert g.get('draft'), \
'Only draft documents can be assigned new revisions'
else:
with self.draft_context():
assert self.count(Q._id == self._id) == 1, \
'Only draft documents can be assigned new revisions'
if len(fields) > 0:
fields.append('revision')
self.revision = datetime.now()
self.upsert(*fields) | Save a new revision of the document |
def construct(self, uri, *args, **kw):
logger.debug(util.lazy_format("Constructing {0}", uri))
if ('override' not in kw or kw['override'] is False) \
and uri in self.resolved:
logger.debug(util.lazy_format("Using existing {0}", uri))
return self.resolved[uri]
else:
ret = self._construct(uri, *args, **kw)
logger.debug(util.lazy_format("Constructed {0}", ret))
return ret | Wrapper to debug things |
def files_in_path(path):
aggregated_files = []
for dir_, _, files in os.walk(path):
for file in files:
relative_dir = os.path.relpath(dir_, path)
if ".git" not in relative_dir:
relative_file = os.path.join(relative_dir, file)
aggregated_files.append(relative_file)
return aggregated_files | Return a list of all files in a path but exclude git folders. |
def get(self, block=True, timeout=None):
value = self._queue.get(block, timeout)
if self._queue.empty():
self.clear()
return value | Removes and returns an item from the queue. |
def list_records_for_project(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
data = list_records_for_project_raw(id, name, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | List all BuildRecords for a given Project |
def colorbar(height, length, colormap):
cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))
cbar = (cbar * (colormap.values.max() - colormap.values.min())
+ colormap.values.min())
return colormap.colorize(cbar) | Return the channels of a colorbar. |
def reply_bytes(self, request):
flags = struct.pack("<I", self._flags)
payload_type = struct.pack("<b", 0)
payload_data = bson.BSON.encode(self.doc)
data = b''.join([flags, payload_type, payload_data])
reply_id = random.randint(0, 1000000)
response_to = request.request_id
header = struct.pack(
"<iiii", 16 + len(data), reply_id, response_to, OP_MSG)
return header + data | Take a `Request` and return an OP_MSG message as bytes. |
def _from_dict(cls, _dict):
args = {}
if 'models' in _dict:
args['models'] = [
SpeechModel._from_dict(x) for x in (_dict.get('models'))
]
else:
raise ValueError(
'Required property \'models\' not present in SpeechModels JSON')
return cls(**args) | Initialize a SpeechModels object from a json dictionary. |
def astype(self, type_name):
if type_name == 'nddata':
return self.as_nddata()
if type_name == 'hdu':
return self.as_hdu()
raise ValueError("Unrecognized conversion type '%s'" % (type_name)) | Convert AstroImage object to some other kind of object. |
def select(self, table, cols, execute=True, select_type='SELECT', return_type=list):
select_type = select_type.upper()
assert select_type in SELECT_QUERY_TYPES
statement = '{0} {1} FROM {2}'.format(select_type, join_cols(cols), wrap(table))
if not execute:
return statement
values = self.fetch(statement)
return self._return_rows(table, cols, values, return_type) | Query every row and only certain columns from a table. |
def decode(hashcode, delta=False):
lat, lon, lat_length, lon_length = _decode_c2i(hashcode)
if hasattr(float, "fromhex"):
latitude_delta = 90.0/(1 << lat_length)
longitude_delta = 180.0/(1 << lon_length)
latitude = _int_to_float_hex(lat, lat_length) * 90.0 + latitude_delta
longitude = _int_to_float_hex(lon, lon_length) * 180.0 + longitude_delta
if delta:
return latitude, longitude, latitude_delta, longitude_delta
return latitude, longitude
lat = (lat << 1) + 1
lon = (lon << 1) + 1
lat_length += 1
lon_length += 1
latitude = 180.0*(lat-(1 << (lat_length-1)))/(1 << lat_length)
longitude = 360.0*(lon-(1 << (lon_length-1)))/(1 << lon_length)
if delta:
latitude_delta = 180.0/(1 << lat_length)
longitude_delta = 360.0/(1 << lon_length)
return latitude, longitude, latitude_delta, longitude_delta
return latitude, longitude | decode a hashcode and get center coordinate, and distance between center and outer border |
def apply_interceptors(work_db, enabled_interceptors):
names = (name for name in interceptor_names() if name in enabled_interceptors)
for name in names:
interceptor = get_interceptor(name)
interceptor(work_db) | Apply each registered interceptor to the WorkDB. |
def send(self, *args):
for frame in args:
self.sock.sendall(self.apply_send_hooks(frame, False).pack()) | Send a number of frames. |
def from_etree(
el, node=None, node_cls=None,
tagsub=functools.partial(re.sub, r'\{.+?\}', ''),
Node=Node):
node_cls = node_cls or Node
if node is None:
node = node_cls()
tag = tagsub(el.tag)
attrib = dict((tagsub(k), v) for (k, v) in el.attrib.items())
node.update(attrib, tag=tag)
if el.text:
node['text'] = el.text
for child in el:
child = from_etree(child, node_cls=node_cls)
node.append(child)
if el.tail:
node['tail'] = el.tail
return node | Convert the element tree to a tater tree. |
def update(self, **kwargs):
if 'monitor' in kwargs:
value = self._format_monitor_parameter(kwargs['monitor'])
kwargs['monitor'] = value
elif 'monitor' in self.__dict__:
value = self._format_monitor_parameter(self.__dict__['monitor'])
self.__dict__['monitor'] = value
return super(Pool, self)._update(**kwargs) | Custom update method to implement monitor parameter formatting. |
def secretfile_args(parser):
parser.add_argument('--secrets',
dest='secrets',
help='Path where secrets are stored',
default=os.path.join(os.getcwd(), ".secrets"))
parser.add_argument('--policies',
dest='policies',
help='Path where policies are stored',
default=os.path.join(os.getcwd(), "vault", ""))
parser.add_argument('--secretfile',
dest='secretfile',
help='Secretfile to use',
default=os.path.join(os.getcwd(), "Secretfile"))
parser.add_argument('--tags',
dest='tags',
help='Tags of things to seed',
default=[],
type=str,
action='append')
parser.add_argument('--include',
dest='include',
help='Specify paths to include',
default=[],
type=str,
action='append')
parser.add_argument('--exclude',
dest='exclude',
help='Specify paths to exclude',
default=[],
type=str,
action='append') | Add Secretfile management command line arguments to parser |
def bind(renderer, to):
@wraps(to)
def view(request, **kwargs):
try:
returned = to(request, **kwargs)
except Exception as error:
view_error = getattr(renderer, "view_error", None)
if view_error is None:
raise
return view_error(request, error)
try:
return renderer.render(request, returned)
except Exception as error:
render_error = getattr(renderer, "render_error", None)
if render_error is None:
raise
return render_error(request, returned, error)
return view | Bind a renderer to the given callable by constructing a new rendering view. |
def Contradiction(expr1: Expression, expr2: Expression) -> Expression:
expr = Disjunction(Conjunction(expr1, Negation(expr2)),
Conjunction(Negation(expr1), expr2))
return ast.fix_missing_locations(expr) | Return expression which is the contradiction of `expr1` and `expr2`. |
def to_rdkit_molecule(data):
mol = RWMol()
conf = Conformer()
mapping = {}
is_3d = False
for n, a in data.atoms():
ra = Atom(a.number)
ra.SetAtomMapNum(n)
if a.charge:
ra.SetFormalCharge(a.charge)
if a.isotope != a.common_isotope:
ra.SetIsotope(a.isotope)
if a.radical:
ra.SetNumRadicalElectrons(a.radical)
mapping[n] = m = mol.AddAtom(ra)
conf.SetAtomPosition(m, (a.x, a.y, a.z))
if a.z:
is_3d = True
if not is_3d:
conf.Set3D(False)
for n, m, b in data.bonds():
mol.AddBond(mapping[n], mapping[m], _bond_map[b.order])
mol.AddConformer(conf)
SanitizeMol(mol)
return mol | MoleculeContainer to RDKit molecule object converter |
def deprecate(
message: str, category: Any = DeprecationWarning, stacklevel: int = 0
) -> Callable[[F], F]:
def decorator(func: F) -> F:
if not __debug__:
return func
@functools.wraps(func)
def wrapper(*args, **kargs):
warnings.warn(message, category, stacklevel=stacklevel + 2)
return func(*args, **kargs)
return cast(F, wrapper)
return decorator | Return a decorator which adds a warning to functions. |
def do_api_calls_update_cache(self):
zones = self.parse_env_zones()
data = self.group_instances(zones)
self.cache.write_to_cache(data)
self.inventory = data | Do API calls and save data in cache. |
def _calc_distortion(self):
m = self._X.shape[0]
self.distortion = 1/m * sum(
linalg.norm(self._X[i, :] - self.centroids[self.clusters[i]])**2 for i in range(m)
)
return self.distortion | Calculates the distortion value of the current clusters |
def acquire_node(self, node):
try:
return node.set(self.resource, self.lock_key, nx=True, px=self.ttl)
except (redis.exceptions.ConnectionError, redis.exceptions.TimeoutError):
return False | acquire a single redis node |
def _cast_number(value):
"Convert numbers as string to an int or float"
m = FLOAT_REGEX.search(value)
if m is not None:
return float(value)
return int(value) | Convert numbers as string to an int or float |
def stream(self, request, counter=0):
if self._children:
for child in self._children:
if isinstance(child, String):
yield from child.stream(request, counter+1)
else:
yield child | Returns an iterable over strings. |
def _build_line(colwidths, colaligns, linefmt):
"Return a string which represents a horizontal line."
if not linefmt:
return None
if hasattr(linefmt, "__call__"):
return linefmt(colwidths, colaligns)
else:
begin, fill, sep, end = linefmt
cells = [fill*w for w in colwidths]
return _build_simple_row(cells, (begin, sep, end)) | Return a string which represents a horizontal line. |
def crawler(site, uri=None):
config = load_site_config(site)
model = _get_model('crawl', config, uri)
visited_set, visited_uri_set, consume_set, crawl_set = get_site_sets(
site, config
)
if not visited_set.has(model.hash):
visited_set.add(model.hash)
visited_uri_set.add(model.uri)
if (
model.is_consume_page
and not consume_set.has(model.hash)
):
consume_set.add(model.hash)
consume_q.enqueue(
consumer,
site,
model.uri
)
else:
for crawl_uri in model.uris_to_crawl:
if (
not visited_uri_set.has(crawl_uri)
and not crawl_set.has(crawl_uri)
):
crawl_set.add(crawl_uri)
crawl_q.enqueue(
crawler,
site,
crawl_uri
) | Crawl URI using site config. |
def iterations(self, parameter):
return numpy.arange(0, self.last_iteration(parameter), self.thinned_by) | Returns the iteration each sample occurred at. |
def external_answer(self, *sequences):
if not getattr(self, 'external', False):
return
if hasattr(self, 'test_func') and self.test_func is not self._ident:
return
libs = libraries.get_libs(self.__class__.__name__)
for lib in libs:
if not lib.check_conditions(self, *sequences):
continue
if not lib.get_function():
continue
prepared_sequences = lib.prepare(*sequences)
try:
return lib.func(*prepared_sequences)
except Exception:
pass | Try to get answer from known external libraries. |
def scene_command(self, command):
self.logger.info("scene_command: Group %s Command %s", self.group_id, command)
command_url = self.hub.hub_url + '/0?' + command + self.group_id + "=I=0"
return self.hub.post_direct_command(command_url) | Wrapper to send posted scene command and get response |
def r_date_num(obj, multiple=False):
if isinstance(obj, (list, tuple)):
it = iter
else:
it = LinesIterator
if multiple:
datasets = {}
for line in it(obj):
label = line[2]
if label not in datasets:
datasets[label] = Dataset([Dataset.DATE, Dataset.FLOAT])
datasets[label].name = label
datasets[label].parse_elements(line[0:2])
return datasets.values()
dataset = Dataset([Dataset.DATE, Dataset.FLOAT])
return dataset.load(it(obj)) | Read date-value table. |
def resize(self, height, width, **kwargs):
self.client.exec_resize(self.exec_id, height=height, width=width) | resize pty of an execed process |
def removeSubEditor(self, subEditor):
if subEditor is self.focusProxy():
self.setFocusProxy(None)
subEditor.removeEventFilter(self)
self._subEditors.remove(subEditor)
self.hBoxLayout.removeWidget(subEditor) | Removes the subEditor from the layout and removes the event filter. |
async def open(
self,
cmd: List[str],
input_source: Optional[str],
output: Optional[str] = "-",
extra_cmd: Optional[str] = None,
stdout_pipe: bool = True,
stderr_pipe: bool = False,
) -> bool:
stdout = subprocess.PIPE if stdout_pipe else subprocess.DEVNULL
stderr = subprocess.PIPE if stderr_pipe else subprocess.DEVNULL
if self.is_running:
_LOGGER.warning("FFmpeg is already running!")
return True
self._generate_ffmpeg_cmd(cmd, input_source, output, extra_cmd)
_LOGGER.debug("Start FFmpeg with %s", str(self._argv))
try:
proc_func = functools.partial(
subprocess.Popen,
self._argv,
bufsize=0,
stdin=subprocess.PIPE,
stdout=stdout,
stderr=stderr,
)
self._proc = await self._loop.run_in_executor(None, proc_func)
except Exception as err:
_LOGGER.exception("FFmpeg fails %s", err)
self._clear()
return False
return self._proc is not None | Start a ffmpeg instance and pipe output. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.