code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def close_compute_projects(self, compute):
for project in self._projects.values():
if compute in project.computes:
yield from project.close() | Close projects running on a compute |
def build(templates=None, schemes=None, base_output_dir=None):
template_dirs = templates or get_template_dirs()
scheme_files = get_scheme_files(schemes)
base_output_dir = base_output_dir or rel_to_cwd('output')
if not template_dirs or not scheme_files:
raise LookupError
try:
os.makedirs(base_output_dir)
except FileExistsError:
pass
if not os.access(base_output_dir, os.W_OK):
raise PermissionError
templates = [TemplateGroup(path) for path in template_dirs]
build_from_job_list(scheme_files, templates, base_output_dir)
print('Finished building process.') | Main build function to initiate building process. |
def selectis(table, field, value, complement=False):
return selectop(table, field, value, operator.is_, complement=complement) | Select rows where the given field `is` the given value. |
def getcoordinates(self, tree, location):
return tuple(float(x) for x in tree.xpath('.//%s/*/text()' % location)) | Gets coordinates from a specific element in PLIP XML |
def visit(self, node):
method = 'visit_' + type(node).__name__
return getattr(self, method, self.fallback)(node) | Visit the right method of the child class according to the node. |
def register(cls, name):
def register_decorator(reg_cls):
def name_func(self):
return name
reg_cls.name = property(name_func)
assert issubclass(reg_cls, cls), \
"Must be subclass matching your NamedRegistry class"
cls.REGISTRY[name] = reg_cls
return reg_cls
return register_decorator | Decorator to register a class. |
def run(self, b, compute, times=[], **kwargs):
self.run_checks(b, compute, times, **kwargs)
logger.debug("rank:{}/{} calling get_packet_and_syns".format(mpi.myrank, mpi.nprocs))
packet, new_syns = self.get_packet_and_syns(b, compute, times, **kwargs)
if mpi.enabled:
mpi.comm.bcast(packet, root=0)
packet['b'] = b
rpacketlists = self._run_chunk(**packet)
rpacketlists_per_worker = mpi.comm.gather(rpacketlists, root=0)
else:
rpacketlists_per_worker = [self._run_chunk(**packet)]
return self._fill_syns(new_syns, rpacketlists_per_worker) | if within mpirun, workers should call _run_worker instead of run |
def print_with_pager(output):
if sys.stdout.isatty():
try:
pager = subprocess.Popen(
['less', '-F', '-r', '-S', '-X', '-K'],
stdin=subprocess.PIPE, stdout=sys.stdout)
except subprocess.CalledProcessError:
print(output)
return
else:
pager.stdin.write(output.encode('utf-8'))
pager.stdin.close()
pager.wait()
else:
print(output) | Print the output to `stdout` using less when in a tty. |
def __restore_selection(self, start_pos, end_pos):
cursor = self.textCursor()
cursor.setPosition(start_pos)
cursor.setPosition(end_pos, QTextCursor.KeepAnchor)
self.setTextCursor(cursor) | Restore cursor selection from position bounds |
def full_name(self):
return "%s %s %s %s" % (self.get_title_display(),
self.first_name,
self.other_names.replace(",", ""),
self.last_name) | Return the title and full name |
def option_getter(type):
option_getters = {None: ConfigParser.get,
int: ConfigParser.getint,
float: ConfigParser.getfloat,
bool: ConfigParser.getboolean}
return option_getters.get(type, option_getters[None]) | Gets an unbound method to get a configuration option as the given type. |
def keyword(self, text):
cls = self.KEYWORDS[text]
self.push_token(cls(text, self.lineno, self.offset)) | Push a keyword onto the token queue. |
def pixels(self, value: int) -> 'Gap':
raise_not_number(value)
self.gap = '{}px'.format(value)
return self | Set the margin in pixels. |
def make_student(user):
tutor_group, owner_group = _get_user_groups()
user.is_staff = False
user.is_superuser = False
user.save()
owner_group.user_set.remove(user)
owner_group.save()
tutor_group.user_set.remove(user)
tutor_group.save() | Makes the given user a student. |
def remove_sqlvm_from_aglistener(instance, sqlvm_resource_id):
if not is_valid_resource_id(sqlvm_resource_id):
raise CLIError("Invalid SQL virtual machine resource id.")
vm_list = instance.load_balancer_configurations[0].sql_virtual_machine_instances
if sqlvm_resource_id in vm_list:
instance.load_balancer_configurations[0].sql_virtual_machine_instances.remove(sqlvm_resource_id)
return instance | Remove a SQL virtual machine from an availability group listener. |
def package(
files,
tag,
metadata,
extra_options,
branch,
template_dir,
plugins_dir,
static,
install,
spatialite,
version_note,
**extra_metadata
):
"Package specified SQLite files into a new datasette Docker container"
if not shutil.which("docker"):
click.secho(
' The package command requires "docker" to be installed and configured ',
bg="red",
fg="white",
bold=True,
err=True,
)
sys.exit(1)
with temporary_docker_directory(
files,
"datasette",
metadata,
extra_options,
branch,
template_dir,
plugins_dir,
static,
install,
spatialite,
version_note,
extra_metadata,
):
args = ["docker", "build"]
if tag:
args.append("-t")
args.append(tag)
args.append(".")
call(args) | Package specified SQLite files into a new datasette Docker container |
def uri(self, value):
if value == self.__uri:
return
match = URI_REGEX.match(value)
if match is None:
raise ValueError('Unable to match URI from `{}`'.format(value))
for key, value in match.groupdict().items():
setattr(self, key, value) | Attempt to validate URI and split into individual values |
def reset(self):
self.reached_limit = False
self.count = 0
self.seen.clear() | Resets state and uid set. To be called asap to free memory |
def data(self):
if self.sort:
xs = sorted(self.dataset, key=self.sort_key)
elif self.shuffle:
xs = [self.dataset[i] for i in self.random_shuffler(range(len(self.dataset)))]
else:
xs = self.dataset
return xs | Return the examples in the dataset in order, sorted, or shuffled. |
def stddev(self):
if len(self) < 2:
return float('NaN')
try:
arr = self.samples()
mean = sum(arr) / len(arr)
bigsum = 0.0
for x in arr:
bigsum += (x - mean)**2
return sqrt(bigsum / (len(arr) - 1))
except ZeroDivisionError:
return float('NaN') | Return the sample standard deviation. |
def _handle_rate_exceeded(self, response):
waiting_time = int(response.headers.get("Retry-After", 10))
time.sleep(waiting_time) | Handles rate exceeded errors |
def coincidents(self):
coincident_sites = []
for i, tag in enumerate(self.site_properties['grain_label']):
if 'incident' in tag:
coincident_sites.append(self.sites[i])
return coincident_sites | return the a list of coincident sites. |
def validate(self):
if not isinstance(self.fold_scope_location, FoldScopeLocation):
raise TypeError(u'Expected FoldScopeLocation fold_scope_location, got: {} {}'.format(
type(self.fold_scope_location), self.fold_scope_location))
if self.fold_scope_location.field is None:
raise ValueError(u'Expected FoldScopeLocation at a field, but got: {}'
.format(self.fold_scope_location))
if self.fold_scope_location.field == COUNT_META_FIELD_NAME:
if not GraphQLInt.is_same_type(self.field_type):
raise TypeError(u'Expected the _x_count meta-field to be of GraphQLInt type, but '
u'encountered type {} instead: {}'
.format(self.field_type, self.fold_scope_location))
else:
if not isinstance(self.field_type, GraphQLList):
raise ValueError(u'Invalid value of "field_type" for a field that is not '
u'a meta-field, expected a list type but got: {} {}'
.format(self.field_type, self.fold_scope_location))
inner_type = strip_non_null_from_type(self.field_type.of_type)
if isinstance(inner_type, GraphQLList):
raise GraphQLCompilationError(
u'Outputting list-valued fields in a @fold context is currently not supported: '
u'{} {}'.format(self.fold_scope_location, self.field_type.of_type)) | Validate that the FoldedContextField is correctly representable. |
def _check_update_(self):
try:
data = requests.get("https://pypi.python.org/pypi/jira/json", timeout=2.001).json()
released_version = data['info']['version']
if parse_version(released_version) > parse_version(__version__):
warnings.warn(
"You are running an outdated version of JIRA Python %s. Current version is %s. Do not file any bugs against older versions." % (
__version__, released_version))
except requests.RequestException:
pass
except Exception as e:
logging.warning(e) | Check if the current version of the library is outdated. |
def update(self):
response = requests.get(self.update_url, timeout=timeout)
match = ip_pattern.search(response.content)
if not match:
raise ApiError("Couldn't parse the server's response",
response.content)
self.ip = match.group(0) | Updates remote DNS record by requesting its special endpoint URL |
def compute_rewards(self, scores):
for i in range(len(scores)):
if i >= self.k:
scores[i] = 0.
return scores | Retain the K most recent scores, and replace the rest with zeros |
def use_comparative_assessment_part_view(self):
self._object_views['assessment_part'] = COMPARATIVE
for session in self._get_provider_sessions():
try:
session.use_comparative_assessment_part_view()
except AttributeError:
pass | Pass through to provider AssessmentPartLookupSession.use_comparative_assessment_part_view |
def validate_number_attribute(self,
attribute: str,
value_type: Union[Type[int], Type[float]] = int,
minimum: Optional[Union[int, float]] = None,
maximum: Optional[Union[int, float]] = None) -> None:
self.add_errors(
validate_number_attribute(self.fully_qualified_name, self._spec, attribute, value_type,
minimum, maximum)) | Validates that the attribute contains a numeric value within boundaries if specified |
def _select_features(example, feature_list=None):
feature_list = feature_list or ["inputs", "targets"]
return {f: example[f] for f in feature_list} | Select a subset of features from the example dict. |
def begin_transaction(self, transaction_type, trace_parent=None):
return self.tracer.begin_transaction(transaction_type, trace_parent=trace_parent) | Register the start of a transaction on the client |
def merge(self, other):
assert self.attrs == other.attrs
self.tokens.extend(other.tokens)
self.spaces.extend(other.spaces)
self.strings.update(other.strings) | Extend the annotations of this binder with the annotations from another. |
def _get_nics(vm_):
nics = []
if 'public_lan' in vm_:
firewall_rules = []
if 'public_firewall_rules' in vm_:
firewall_rules = _get_firewall_rules(vm_['public_firewall_rules'])
nic = NIC(lan=set_public_lan(int(vm_['public_lan'])),
name='public',
firewall_rules=firewall_rules)
if 'public_ips' in vm_:
nic.ips = _get_ip_addresses(vm_['public_ips'])
nics.append(nic)
if 'private_lan' in vm_:
firewall_rules = []
if 'private_firewall_rules' in vm_:
firewall_rules = _get_firewall_rules(vm_['private_firewall_rules'])
nic = NIC(lan=int(vm_['private_lan']),
name='private',
firewall_rules=firewall_rules)
if 'private_ips' in vm_:
nic.ips = _get_ip_addresses(vm_['private_ips'])
if 'nat' in vm_ and 'private_ips' not in vm_:
nic.nat = vm_['nat']
nics.append(nic)
return nics | Create network interfaces on appropriate LANs as defined in cloud profile. |
def population(self):
"Class containing the population and all the individuals generated"
try:
return self._p
except AttributeError:
self._p = self._population_class(base=self,
tournament_size=self._tournament_size,
classifier=self.classifier,
labels=self._labels,
es_extra_test=self.es_extra_test,
popsize=self._popsize,
random_generations=self._random_generations,
negative_selection=self._negative_selection)
return self._p | Class containing the population and all the individuals generated |
def mul_block(self, index, val):
self._prepare_cache_slice(index)
self.msinds[self.cache_slice] *= val | Multiply values in block |
def boxed_text_to_image_block(tag):
"covert boxed-text to an image block containing an inline-graphic"
tag_block = OrderedDict()
image_content = body_block_image_content(first(raw_parser.inline_graphic(tag)))
tag_block["type"] = "image"
set_if_value(tag_block, "doi", doi_uri_to_doi(object_id_doi(tag, tag.name)))
set_if_value(tag_block, "id", tag.get("id"))
set_if_value(tag_block, "image", image_content)
p_tags = raw_parser.paragraph(tag)
caption_content = []
for p_tag in p_tags:
if not raw_parser.inline_graphic(p_tag):
caption_content.append(body_block_content(p_tag))
set_if_value(tag_block, "caption", caption_content)
return tag_block | covert boxed-text to an image block containing an inline-graphic |
def server_online(self):
response = self._post(self.apiurl + '/v2/server/online', data={'apikey': self.apikey})
return self._raise_or_extract(response) | Returns True if the Joe Sandbox servers are running or False if they are in maintenance mode. |
def convert_lat(Recs):
New = []
for rec in Recs:
if 'model_lat' in list(rec.keys()) and rec['model_lat'] != "":
New.append(rec)
elif 'average_age' in list(rec.keys()) and rec['average_age'] != "" and float(rec['average_age']) <= 5.:
if 'site_lat' in list(rec.keys()) and rec['site_lat'] != "":
rec['model_lat'] = rec['site_lat']
New.append(rec)
elif 'average_inc' in list(rec.keys()) and rec['average_inc'] != "":
rec['model_lat'] = '%7.1f' % (plat(float(rec['average_inc'])))
New.append(rec)
return New | uses lat, for age<5Ma, model_lat if present, else tries to use average_inc to estimate plat. |
def format_context(
context: Context, formatter: typing.Union[str, Formatter] = "full"
) -> str:
if not context:
return ""
if callable(formatter):
formatter_func = formatter
else:
if formatter in CONTEXT_FORMATTERS:
formatter_func = CONTEXT_FORMATTERS[formatter]
else:
raise ValueError(f'Invalid context format: "{formatter}"')
return formatter_func(context) | Output the a context dictionary as a string. |
def Intersect(self, mask1, mask2):
_CheckFieldMaskMessage(mask1)
_CheckFieldMaskMessage(mask2)
tree = _FieldMaskTree(mask1)
intersection = _FieldMaskTree()
for path in mask2.paths:
tree.IntersectPath(path, intersection)
intersection.ToFieldMask(self) | Intersects mask1 and mask2 into this FieldMask. |
def clear_extensions(self, group=None):
if group is None:
ComponentRegistry._registered_extensions = {}
return
if group in self._registered_extensions:
self._registered_extensions[group] = [] | Clear all previously registered extensions. |
def reverse_compl_with_name(old_seq):
new_seq = old_seq.reverse_complement()
new_seq.id = old_seq.id
new_seq.description = old_seq.description
return new_seq | Reverse a SeqIO sequence, but keep its name intact. |
def _construct_from_json(self, rec):
self.delete()
for required_key in ['dagobah_id', 'created_jobs']:
setattr(self, required_key, rec[required_key])
for job_json in rec.get('jobs', []):
self._add_job_from_spec(job_json)
self.commit(cascade=True) | Construct this Dagobah instance from a JSON document. |
def _find_self(param_names: List[str], args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Any:
instance_i = param_names.index("self")
if instance_i < len(args):
instance = args[instance_i]
else:
instance = kwargs["self"]
return instance | Find the instance of ``self`` in the arguments. |
def _get_template_dirs(type="plugin"):
template_dirs = [
os.path.expanduser(os.path.join(USER_CONFIG_DIR, "templates", type)),
os.path.join("rapport", "templates", type)
]
return template_dirs | Return a list of directories where templates may be located. |
def _sumterm(lexer):
xorterm = _xorterm(lexer)
sumterm_prime = _sumterm_prime(lexer)
if sumterm_prime is None:
return xorterm
else:
return ('or', xorterm, sumterm_prime) | Return a sum term expresssion. |
def CheckClientApprovalRequest(approval_request):
_CheckExpired(approval_request)
_CheckHasEnoughGrants(approval_request)
if not client_approval_auth.CLIENT_APPROVAL_AUTH_MGR.IsActive():
return True
token = access_control.ACLToken(username=approval_request.requestor_username)
approvers = set(g.grantor_username for g in approval_request.grants)
labels = sorted(
data_store.REL_DB.ReadClientLabels(approval_request.subject_id),
key=lambda l: l.name)
for label in labels:
client_approval_auth.CLIENT_APPROVAL_AUTH_MGR.CheckApproversForLabel(
token, rdfvalue.RDFURN(approval_request.subject_id),
approval_request.requestor_username, approvers, label.name)
return True | Checks if a client approval request is granted. |
def _gap_progenitor_setup(self):
self._gap_progenitor= self._progenitor().flip()
self._gap_progenitor.turn_physical_off()
ts= numpy.linspace(0.,self._tdisrupt,1001)
self._gap_progenitor.integrate(ts,self._pot)
self._gap_progenitor._orb.orbit[:,1]= -self._gap_progenitor._orb.orbit[:,1]
self._gap_progenitor._orb.orbit[:,2]= -self._gap_progenitor._orb.orbit[:,2]
self._gap_progenitor._orb.orbit[:,4]= -self._gap_progenitor._orb.orbit[:,4]
return None | Setup an Orbit instance that's the progenitor integrated backwards |
def _create_row_col_indices(ratings_df):
user_id_to_user_idx = _create_index(ratings_df, "userId")
item_id_to_item_idx = _create_index(ratings_df, "movieId")
ratings_df["row"] = ratings_df["userId"].apply(
lambda x: user_id_to_user_idx[x])
ratings_df["col"] = ratings_df["movieId"].apply(
lambda x: item_id_to_item_idx[x])
return ratings_df | Maps user and items ids to their locations in the rating matrix. |
def outlierDetection_threaded(samples_x, samples_y_aggregation):
outliers = []
threads_inputs = [[samples_idx, samples_x, samples_y_aggregation]\
for samples_idx in range(0, len(samples_x))]
threads_pool = ThreadPool(min(4, len(threads_inputs)))
threads_results = threads_pool.map(_outlierDetection_threaded, threads_inputs)
threads_pool.close()
threads_pool.join()
for threads_result in threads_results:
if threads_result is not None:
outliers.append(threads_result)
else:
print("error here.")
outliers = None if len(outliers) == 0 else outliers
return outliers | Use Multi-thread to detect the outlier |
def _with_env(self, env):
res = self._browse(env, self._ids)
return res | As the `with_env` class method but for recordset. |
def _get_db_connect(dbSystem,db,user,password):
if dbSystem=='SYBASE':
import Sybase
try:
dbh = Sybase.connect(dbSystem,
user,
password,
database=db )
except:
dbh=None
elif dbSystem=='MYSQL':
import MySQLdb
try:
dbh = MySQLdb.connect(user=user,
passwd=password,
db=db ,
host='gimli')
except:
dbh=None
return dbh | Create a connection to the database specified on the command line |
def create(client, _type, **kwargs):
obj = client.factory.create("ns0:%s" % _type)
for key, value in kwargs.items():
setattr(obj, key, value)
return obj | Create a suds object of the requested _type. |
def list_mypasswords_search(self, searchstring):
log.debug('List MyPasswords with %s' % searchstring)
return self.collection('my_passwords/search/%s.json' %
quote_plus(searchstring)) | List my passwords with searchstring. |
def _safe_readinto(self, b):
total_bytes = 0
mvb = memoryview(b)
while total_bytes < len(b):
if MAXAMOUNT < len(mvb):
temp_mvb = mvb[0:MAXAMOUNT]
n = self.fp.readinto(temp_mvb)
else:
n = self.fp.readinto(mvb)
if not n:
raise IncompleteRead(bytes(mvb[0:total_bytes]), len(b))
mvb = mvb[n:]
total_bytes += n
return total_bytes | Same as _safe_read, but for reading into a buffer. |
def main(handwriting_datasets_file, analyze_features):
logging.info("Start loading data '%s' ...", handwriting_datasets_file)
loaded = pickle.load(open(handwriting_datasets_file))
raw_datasets = loaded['handwriting_datasets']
logging.info("%i datasets loaded.", len(raw_datasets))
logging.info("Start analyzing...")
if analyze_features:
featurelist = [(features.AspectRatio(), "aspect_ratio.csv"),
(features.ReCurvature(1), "re_curvature.csv"),
(features.Height(), "height.csv"),
(features.Width(), "width.csv"),
(features.Time(), "time.csv"),
(features.Ink(), "ink.csv"),
(features.StrokeCount(), "stroke-count.csv")]
for feat, filename in featurelist:
logging.info("create %s...", filename)
analyze_feature(raw_datasets, feat, filename)
cfg = utils.get_project_configuration()
if 'data_analyzation_queue' in cfg:
metrics = dam.get_metrics(cfg['data_analyzation_queue'])
for metric in metrics:
logging.info("Start metric %s...", str(metric))
metric(raw_datasets)
else:
logging.info("No 'data_analyzation_queue' in ~/.hwrtrc") | Start the creation of the wanted metric. |
def eval_str_to_list(input_str: str) -> List[str]:
inner_cast = ast.literal_eval(input_str)
if isinstance(inner_cast, list):
return inner_cast
else:
raise ValueError | Turn str into str or tuple. |
def _convert_and_assert_per_example_weights_compatible(
input_, per_example_weights, dtype):
per_example_weights = tf.convert_to_tensor(
per_example_weights, name='per_example_weights', dtype=dtype)
if input_.get_shape().ndims:
expected_length = input_.get_shape().dims[0]
message = ('per_example_weights must have rank 1 and length %s, but was: %s'
% (expected_length, per_example_weights.get_shape()))
else:
expected_length = None
message = ('per_example_weights must have rank 1 and length equal to the '
'first dimension of inputs (unknown), but was: %s'
% per_example_weights.get_shape())
if per_example_weights.get_shape().ndims not in (1, None):
raise ValueError(message)
if not per_example_weights.get_shape().is_compatible_with((expected_length,)):
raise ValueError(message)
return per_example_weights | Converts per_example_weights to a tensor and validates the shape. |
def all_active(cls):
prefix = context.get_current_config()["redis_prefix"]
queues = []
for key in context.connections.redis.keys():
if key.startswith(prefix):
queues.append(Queue(key[len(prefix) + 3:]))
return queues | List active queues, based on their lengths in Redis. Warning, uses the unscalable KEYS redis command |
def _dump(file_obj, options, out=sys.stdout):
total_count = 0
writer = None
keys = None
for row in DictReader(file_obj, options.col):
if not keys:
keys = row.keys()
if not writer:
writer = csv.DictWriter(out, keys, delimiter=u'\t', quotechar=u'\'', quoting=csv.QUOTE_MINIMAL) \
if options.format == 'csv' \
else JsonWriter(out) if options.format == 'json' \
else None
if total_count == 0 and options.format == "csv" and not options.no_headers:
writer.writeheader()
if options.limit != -1 and total_count >= options.limit:
return
row_unicode = {k: v.decode("utf-8") if isinstance(v, bytes) else v for k, v in row.items()}
writer.writerow(row_unicode)
total_count += 1 | Dump to fo with given options. |
def app_size(self):
"Return the total apparent size, including children."
if self._nodes is None:
return self._app_size
return sum(i.app_size() for i in self._nodes) | Return the total apparent size, including children. |
def _hashes_match(self, a, b):
if len(a) != len(b):
return False
diff = 0
if six.PY2:
a = bytearray(a)
b = bytearray(b)
for x, y in zip(a, b):
diff |= x ^ y
return not diff | Constant time comparison of bytes for py3, strings for py2 |
def _column_resized(self, col, old_width, new_width):
self.dataTable.setColumnWidth(col, new_width)
self._update_layout() | Update the column width. |
def _build_response(self, resp):
self.response.content = resp.content
self.response.status_code = resp.status_code
self.response.headers = resp.headers | Build internal Response object from given response. |
def generate_security_hash(self, content_type, object_pk, timestamp):
info = (content_type, object_pk, timestamp)
key_salt = "django.contrib.forms.CommentSecurityForm"
value = "-".join(info)
return salted_hmac(key_salt, value).hexdigest() | Generate a HMAC security hash from the provided info. |
def auto_scroll(self, thumbkey):
if not self.gui_up:
return
scrollp = self.w.auto_scroll.get_state()
if not scrollp:
return
bnch = self.thumb_dict[thumbkey]
pan_x, pan_y = self.c_view.get_pan()
self.c_view.panset_xy(pan_x, bnch.image.y) | Scroll the window to the thumb. |
def mx_page_trees(self, mx_page):
resp = dict()
for tree_name, tree in self.scheduler.timetable.trees.items():
if tree.mx_page == mx_page:
rest_tree = self._get_tree_details(tree_name)
resp[tree.tree_name] = rest_tree.document
return resp | return trees assigned to given MX Page |
def get(cls, parent, name):
return cls.query.filter_by(parent=parent, name=name).one_or_none() | Get an instance matching the parent and name |
def path_helper(self, operations, view, app=None, **kwargs):
rule = self._rule_for_view(view, app=app)
operations.update(yaml_utils.load_operations_from_docstring(view.__doc__))
if hasattr(view, 'view_class') and issubclass(view.view_class, MethodView):
for method in view.methods:
if method in rule.methods:
method_name = method.lower()
method = getattr(view.view_class, method_name)
operations[method_name] = yaml_utils.load_yaml_from_docstring(method.__doc__)
return self.flaskpath2openapi(rule.rule) | Path helper that allows passing a Flask view function. |
def create_tipo_rede(self):
return TipoRede(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | Get an instance of tipo_rede services facade. |
def limiter(arr):
dyn_range = 32767.0 / 32767.0
lim_thresh = 30000.0 / 32767.0
lim_range = dyn_range - lim_thresh
new_arr = arr.copy()
inds = N.where(arr > lim_thresh)[0]
new_arr[inds] = (new_arr[inds] - lim_thresh) / lim_range
new_arr[inds] = (N.arctan(new_arr[inds]) * 2.0 / N.pi) *\
lim_range + lim_thresh
inds = N.where(arr < -lim_thresh)[0]
new_arr[inds] = -(new_arr[inds] + lim_thresh) / lim_range
new_arr[inds] = -(
N.arctan(new_arr[inds]) * 2.0 / N.pi * lim_range + lim_thresh)
return new_arr | Restrict the maximum and minimum values of arr |
def add_check(self, check_item):
self.checks.append(check_item)
for other in self.others:
other.add_check(check_item) | Adds a check universally. |
def _get_firefox_start_cmd(self):
start_cmd = ""
if platform.system() == "Darwin":
start_cmd = "/Applications/Firefox.app/Contents/MacOS/firefox-bin"
if not os.path.exists(start_cmd):
start_cmd = os.path.expanduser("~") + start_cmd
elif platform.system() == "Windows":
start_cmd = (self._find_exe_in_registry() or self._default_windows_location())
elif platform.system() == 'Java' and os._name == 'nt':
start_cmd = self._default_windows_location()
else:
for ffname in ["firefox", "iceweasel"]:
start_cmd = self.which(ffname)
if start_cmd is not None:
break
else:
raise RuntimeError(
"Could not find firefox in your system PATH." +
" Please specify the firefox binary location or install firefox")
return start_cmd | Return the command to start firefox. |
def backward_step(self):
logger.debug("Executing backward step ...")
self.run_to_states = []
self.set_execution_mode(StateMachineExecutionStatus.BACKWARD) | Take a backward step for all active states in the state machine |
def create_session(self, ticket, payload=None, expires=None):
assert isinstance(self.session_storage_adapter, CASSessionAdapter)
logging.debug('[CAS] Creating session for ticket {}'.format(ticket))
self.session_storage_adapter.create(
ticket,
payload=payload,
expires=expires,
) | Create a session record from a service ticket. |
def _ProcessSources(self, sources, parser_factory):
for source in sources:
for action, request in self._ParseSourceType(source):
yield self._RunClientAction(action, request, parser_factory,
source.path_type) | Iterates through sources yielding action responses. |
def read_utf8(fh, byteorder, dtype, count, offsetsize):
return fh.read(count).decode('utf-8') | Read tag data from file and return as unicode string. |
def _set_req_to_reinstall(self, req):
if not self.use_user_site or dist_in_usersite(req.satisfied_by):
req.conflicts_with = req.satisfied_by
req.satisfied_by = None | Set a requirement to be installed. |
def patched(attrs, updates):
orig = patch(attrs, updates.items())
try:
yield orig
finally:
patch(attrs, orig.items()) | A context in which some attributes temporarily have a modified value. |
def cdfout(data, file):
f = open(file, "w")
data.sort()
for j in range(len(data)):
y = old_div(float(j), float(len(data)))
out = str(data[j]) + ' ' + str(y) + '\n'
f.write(out)
f.close() | spits out the cdf for data to file |
def _are_nearby_parallel_boxes(self, b1, b2):
"Are two boxes nearby, parallel, and similar in width?"
if not self._are_aligned_angles(b1.angle, b2.angle):
return False
angle = min(b1.angle, b2.angle)
return abs(np.dot(b1.center - b2.center, [-np.sin(angle), np.cos(angle)])) < self.lineskip_tol * (
b1.height + b2.height) and (b1.width > 0) and (b2.width > 0) and (0.5 < b1.width / b2.width < 2.0) | Are two boxes nearby, parallel, and similar in width? |
def ensure_a_list(data):
if not data:
return []
if isinstance(data, (list, tuple, set)):
return list(data)
if isinstance(data, str):
data = trimmed_split(data)
return data
return [data] | Ensure data is a list or wrap it in a list |
def save_csv(self):
self.results.sort_values(by=self.column_ids, inplace=True)
self.results.reindex(columns=self.column_ids).to_csv(
self.csv_filepath, index=False) | Dump all results to CSV. |
def cli(ctx, env):
env.out("Welcome to the SoftLayer shell.")
env.out("")
formatter = formatting.HelpFormatter()
commands = []
shell_commands = []
for name in cli_core.cli.list_commands(ctx):
command = cli_core.cli.get_command(ctx, name)
if command.short_help is None:
command.short_help = command.help
details = (name, command.short_help)
if name in dict(routes.ALL_ROUTES):
shell_commands.append(details)
else:
commands.append(details)
with formatter.section('Shell Commands'):
formatter.write_dl(shell_commands)
with formatter.section('Commands'):
formatter.write_dl(commands)
for line in formatter.buffer:
env.out(line, newline=False) | Print shell help text. |
def adjust(color, attribute, percent):
r, g, b, a, type = parse_color(color)
r, g, b = hsl_to_rgb(*_adjust(rgb_to_hsl(r, g, b), attribute, percent))
return unparse_color(r, g, b, a, type) | Adjust an attribute of color by a percent |
def _logprior(self):
logj = self.logjacobian
logp = self.prior_distribution(**self.current_params) + logj
if numpy.isnan(logp):
logp = -numpy.inf
return logp | Calculates the log prior at the current parameters. |
def __BitList_to_String(self, data):
result = []
pos = 0
c = 0
while pos < len(data):
c += data[pos] << (7 - (pos % 8))
if (pos % 8) == 7:
result.append(c)
c = 0
pos += 1
if _pythonMajorVersion < 3:
return ''.join([ chr(c) for c in result ])
else:
return bytes(result) | Turn the list of bits -> data, into a string |
def _refresh_and_update(self):
if not self._operation.done:
self._operation = self._refresh()
self._set_result_from_operation() | Refresh the operation and update the result if needed. |
def _lint(self):
command = self._get_command()
process = subprocess.run(command, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
LOG.info('Finished %s', ' '.join(command))
stdout, stderr = self._get_output_lines(process)
return self._linter.parse(stdout), self._parse_stderr(stderr) | Run linter in a subprocess. |
def _write_docs(module_list, output_dir):
for module_meta in module_list:
directory = module_meta['directory']
if directory and not path.isdir(directory):
makedirs(directory)
file = open(module_meta['output'], 'w')
file.write(module_meta['content'])
file.close() | Write the document meta to our output location. |
def lsmod(self):
lines = shell_out("lsmod", timeout=0).splitlines()
return [line.split()[0].strip() for line in lines] | Return a list of kernel module names as strings. |
def rlmb_tiny_sv2p():
hparams = rlmb_ppo_tiny()
hparams.generative_model = "next_frame_sv2p"
hparams.generative_model_params = "next_frame_sv2p_tiny"
hparams.grayscale = False
return hparams | Tiny setting with a tiny sv2p model. |
def ping():
try:
response = salt.utils.http.query(
"{0}/ping".format(CONFIG[CONFIG_BASE_URL]),
decode_type='plain',
decode=True,
)
log.debug(
'marathon.info returned successfully: %s',
response,
)
if 'text' in response and response['text'].strip() == 'pong':
return True
except Exception as ex:
log.error(
'error calling marathon.info with base_url %s: %s',
CONFIG[CONFIG_BASE_URL],
ex,
)
return False | Is the marathon api responding? |
def _rlmb_tiny_overrides():
return dict(
epochs=1,
num_real_env_frames=128,
model_train_steps=2,
max_num_noops=1,
eval_max_num_noops=1,
generative_model_params="next_frame_tiny",
stop_loop_early=True,
resize_height_factor=2,
resize_width_factor=2,
wm_eval_rollout_ratios=[1],
rl_env_max_episode_steps=7,
eval_rl_env_max_episode_steps=7,
simulated_rollout_length=2,
eval_sampling_temps=[0.0, 1.0],
) | Parameters to override for tiny setting excluding agent-related hparams. |
def tickets(self, extra_params=None):
tickets = []
for space in self.api.spaces():
tickets += filter(
lambda ticket: ticket.get('assigned_to_id', None) == self['id'],
space.tickets(extra_params=extra_params)
)
return tickets | A User's tickets across all available spaces |
def _assemble_influence(stmt):
subj_str = _assemble_agent_str(stmt.subj.concept)
obj_str = _assemble_agent_str(stmt.obj.concept)
if stmt.subj.delta['polarity'] is not None:
subj_delta_str = ' decrease' if stmt.subj.delta['polarity'] == -1 \
else 'n increase'
subj_str = 'a%s in %s' % (subj_delta_str, subj_str)
if stmt.obj.delta['polarity'] is not None:
obj_delta_str = ' decrease' if stmt.obj.delta['polarity'] == -1 \
else 'n increase'
obj_str = 'a%s in %s' % (obj_delta_str, obj_str)
stmt_str = '%s causes %s' % (subj_str, obj_str)
return _make_sentence(stmt_str) | Assemble an Influence statement into text. |
def built_datetime(self):
from datetime import datetime
try:
return datetime.fromtimestamp(self.state.build_done)
except TypeError:
return None | Return the built time as a datetime object |
def db_insert(self):
assert self.has_db
coll = self.manager.db_connector.get_collection()
print("Mongodb collection %s with count %d", coll, coll.count())
start = time.time()
for work in self:
for task in work:
results = task.get_results()
pprint(results)
results.update_collection(coll)
results = work.get_results()
pprint(results)
results.update_collection(coll)
print("MongoDb update done in %s [s]" % time.time() - start)
results = self.get_results()
pprint(results)
results.update_collection(coll)
self.pickle_dump()
for d in coll.find():
pprint(d) | Insert results in the `MongDB` database. |
def whowas(self, nick, max="", server=""):
self.send_items('WHOWAS', nick, max, server) | Send a WHOWAS command. |
def record_is_valid(record):
"Checks if a record is valid for processing."
if record.CHROM.startswith('GL'):
return False
if 'DP' in record.INFO and record.INFO['DP'] < 5:
return False
return True | Checks if a record is valid for processing. |
def append_onto_file(self, file_name, msg):
with open(file_name, "a") as heart_file:
heart_file.write(msg)
heart_file.close() | Appends msg onto the Given File |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.