code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def check_extraneous(config, schema):
if not isinstance(config, dict):
raise ValueError("Config {} is not a dictionary".format(config))
for k in config:
if k not in schema:
raise ValueError("Unexpected config key `{}` not in {}".format(
k, list(schema.keys())))
... | Make sure all items of config are in schema |
def bbox2wktpolygon(bbox):
minx = float(bbox[0])
miny = float(bbox[1])
maxx = float(bbox[2])
maxy = float(bbox[3])
return 'POLYGON((%.2f %.2f, %.2f %.2f, %.2f %.2f, %.2f %.2f, %.2f %.2f))' \
% (minx, miny, minx, maxy, maxx, maxy, maxx, miny, minx, miny) | Return OGC WKT Polygon of a simple bbox list of strings |
def _validate_class(self, cl):
if cl not in self.schema_def.attributes_by_class:
search_string = self._build_search_string(cl)
err = self.err(
"{0} - invalid class", self._field_name_from_uri(cl),
search_string=search_string)
return ValidationW... | return error if class `cl` is not found in the ontology |
def to_unit(self, values, unit, from_unit):
return self._to_unit_base('degC-days', values, unit, from_unit) | Return values converted to the unit given the input from_unit. |
def port_ranges():
try:
return _linux_ranges()
except (OSError, IOError):
try:
ranges = _bsd_ranges()
if ranges:
return ranges
except (OSError, IOError):
pass
return [DEFAULT_EPHEMERAL_PORT_RANGE] | Returns a list of ephemeral port ranges for current machine. |
def run(self):
global world
self.__is_running = True
while(self.__is_running):
self.__handle_events()
self.__clock.tick(self.preferred_fps)
elapsed_milliseconds = self.__clock.get_time()
if 2 in self.event_flags:
self.elapsed_milliseco... | Start the game loop |
def _default_dict(self):
options = {}
for attr, _, _, default, multi, _ in self._optiondict.values():
if multi and default is None:
options[attr] = []
else:
options[attr] = default
return options | Return a dictionary with the default for each option. |
def replace(code, pattern, goal):
finder = similarfinder.RawSimilarFinder(code)
matches = list(finder.get_matches(pattern))
ast = patchedast.get_patched_ast(code)
lines = codeanalyze.SourceLinesAdapter(code)
template = similarfinder.CodeTemplate(goal)
computer = _ChangeComputer(code, ast, lines,... | used by other refactorings |
def _add_links(self, links, key="href", proxy_key="proxyURL", endpoints=None):
if endpoints is None:
endpoints = ["likes", "replies", "shares", "self", "followers",
"following", "lists", "favorites", "members"]
if links.get("links"):
for endpoint in links... | Parses and adds block of links |
def css_classes(self, extra_classes=None):
if hasattr(extra_classes, 'split'):
extra_classes = extra_classes.split()
extra_classes = set(extra_classes or [])
field_css_classes = getattr(self.form, 'field_css_classes', None)
if hasattr(field_css_classes, 'split'):
... | Returns a string of space-separated CSS classes for the wrapping element of this input field. |
def update_class_by_type(old, new):
autoreload.update_class(old, new)
if isinstance2(old, new, AtomMeta):
update_atom_members(old, new) | Update declarative classes or fallback on default |
def sentence_spans(self):
if not self.is_tagged(SENTENCES):
self.tokenize_sentences()
return self.spans(SENTENCES) | The list of spans representing ``sentences`` layer elements. |
def apply_child_computation(self, child_msg: Message) -> 'BaseComputation':
child_computation = self.generate_child_computation(child_msg)
self.add_child_computation(child_computation)
return child_computation | Apply the vm message ``child_msg`` as a child computation. |
def _install_nukeassist(use_threaded_wrapper):
import nuke
if "--nukeassist" not in nuke.rawArgs:
raise ImportError
def threaded_wrapper(func, *args, **kwargs):
return nuke.executeInMainThreadWithResult(
func, args, kwargs)
_common_setup("NukeAssist", threaded_wrapper, use_th... | Helper function to The Foundry NukeAssist support |
def save_genome_fitness(self,
delimiter=' ',
filename='fitness_history.csv',
with_cross_validation=False):
with open(filename, 'w') as f:
w = csv.writer(f, delimiter=delimiter)
best_fitness = [c.fitness f... | Saves the population's best and average fitness. |
def hydra_breakpoints(in_bam, pair_stats):
in_bed = convert_bam_to_bed(in_bam)
if os.path.getsize(in_bed) > 0:
pair_bed = pair_discordants(in_bed, pair_stats)
dedup_bed = dedup_discordants(pair_bed)
return run_hydra(dedup_bed, pair_stats)
else:
return None | Detect structural variation breakpoints with hydra. |
def CreateDialectActions(dialect):
CompAction = SCons.Action.Action('$%sCOM ' % dialect, '$%sCOMSTR' % dialect)
CompPPAction = SCons.Action.Action('$%sPPCOM ' % dialect, '$%sPPCOMSTR' % dialect)
ShCompAction = SCons.Action.Action('$SH%sCOM ' % dialect, '$SH%sCOMSTR' % dialect)
ShCompPPAction = SCons.Act... | Create dialect specific actions. |
def create_kernel_manager_and_kernel_client(self, connection_file,
stderr_handle,
is_cython=False,
is_pylab=False,
is_sympy=... | Create kernel manager and client. |
def trunc_list(s: List) -> List:
if len(s) > max_list_size:
i = max_list_size // 2
j = i - 1
s = s[:i] + [ELLIPSIS] + s[-j:]
return s | Truncate lists to maximum length. |
def logWrite(self, string):
logFile = open(self.logFile, 'at')
logFile.write(string + '\n')
logFile.close() | Only write text to the log file, do not print |
def migrate(self, host, port, key, dest_db, timeout, *,
copy=False, replace=False):
if not isinstance(host, str):
raise TypeError("host argument must be str")
if not isinstance(timeout, int):
raise TypeError("timeout argument must be int")
if not isinstanc... | Atomically transfer a key from a Redis instance to another one. |
def nvrtcGetErrorString(self, code):
code_int = c_int(code)
res = self._lib.nvrtcGetErrorString(code_int)
return res.decode('utf-8') | Returns a text identifier for the given NVRTC status code. |
def _elapsed(self):
self.last_time = time.time()
return self.last_time - self.start | Returns elapsed time at update. |
def _create_trustdb(cls):
trustdb = os.path.join(cls.homedir, 'trustdb.gpg')
if not os.path.isfile(trustdb):
log.info("GnuPG complained that your trustdb file was missing. %s"
% "This is likely due to changing to a new homedir.")
log.info("Creating trustdb.gpg file in your GnuPG... | Create the trustdb file in our homedir, if it doesn't exist. |
def parallel_prep_region(samples, run_parallel):
file_key = "work_bam"
split_fn = _split_by_regions("bamprep", "-prep.bam", file_key)
extras = []
torun = []
for data in [x[0] for x in samples]:
if data.get("work_bam"):
data["align_bam"] = data["work_bam"]
if (not dd.get_r... | Perform full pre-variant calling BAM prep work on regions. |
def _event_duration(vevent):
if hasattr(vevent, 'dtend'):
return vevent.dtend.value - vevent.dtstart.value
elif hasattr(vevent, 'duration') and vevent.duration.value:
return vevent.duration.value
return timedelta(0) | unify dtend and duration to the duration of the given vevent |
def __focus(self, item):
cols = self.__get_display_columns()
for col in cols:
self.__event_info =(col,item)
self.event_generate('<<TreeviewInplaceEdit>>')
if col in self._inplace_widgets:
w = self._inplace_widgets[col]
w.bind('<Key-Tab>... | Called when focus item has changed |
def _has_expired(self):
expired = False
if hasattr(self, 'Expiration'):
now = datetime.datetime.utcnow()
expiration = datetime.datetime.strptime(self.Expiration, '%Y-%m-%dT%H:%M:%SZ')
expired = (now >= expiration)
else:
raise ValueError("ERROR: Req... | Has this HIT expired yet? |
def create_swag_from_ctx(ctx):
swag_opts = {}
if ctx.type == 'file':
swag_opts = {
'swag.type': 'file',
'swag.data_dir': ctx.data_dir,
'swag.data_file': ctx.data_file
}
elif ctx.type == 's3':
swag_opts = {
'swag.type': 's3',
... | Creates SWAG client from the current context. |
def lock(self, request, *args, **kwargs):
self.object = self.get_object()
success_url = self.get_success_url()
self.object.status = Topic.TOPIC_LOCKED
self.object.save()
messages.success(self.request, self.success_message)
return HttpResponseRedirect(success_url) | Locks the considered topic and retirects the user to the success URL. |
def convert_to_utf8(string):
if (isinstance(string, unicode)):
return string.encode('utf-8')
try:
u = unicode(string, 'utf-8')
except TypeError:
return str(string)
utf8 = u.encode('utf-8')
return utf8 | Convert string to UTF8 |
def ungap_sequences(records, gap_chars=GAP_TABLE):
logging.info('Applying _ungap_sequences generator: removing all gap characters')
for record in records:
yield ungap_all(record, gap_chars) | Remove gaps from sequences, given an alignment. |
def _infer_all_types(self):
self._initialize_graph_status_for_traversing()
for raw_name, initial_type in self.initial_types:
for scope in self.scopes:
if raw_name not in scope.variable_name_mapping:
continue
for onnx_name in scope.variable_... | Infer all variables' shapes in the computational graph. |
def process_topojson(self, name, layer, input_path):
output_path = os.path.join(TEMP_DIRECTORY, '%s.topojson' % name)
topojson_binary = 'node_modules/bin/topojson'
if not os.path.exists(topojson_binary):
topojson_binary = 'topojson'
topo_cmd = [
topojson_binary,
... | Process layer using topojson. |
def annotation_wrapper(annotation, doc=None):
def decorator(attr):
__cache__.setdefault(attr, []).append(annotation)
try:
if not hasattr(attr, '_coaster_annotations'):
setattr(attr, '_coaster_annotations', [])
attr._coaster_annotations.append(annotation)
... | Defines an annotation, which can be applied to attributes in a database model. |
def ObjectInitializedEventHandler(analysis, event):
wf.doActionFor(analysis, "initialize")
request = analysis.getRequest()
wf.doActionFor(request, "rollback_to_receive")
analysis.reindexObject(idxs="getServiceUID")
return | Actions to be done when an analysis is added in an Analysis Request |
def list_vips(self, retrieve_all=True, **_params):
return self.list('vips', self.vips_path, retrieve_all,
**_params) | Fetches a list of all load balancer vips for a project. |
def recentMatches(self, **criteria):
if not self.matches: return []
try:
maxMatches = criteria["maxMatches"]
del criteria["maxMatches"]
except AttributeError:
maxMatches = c.RECENT_MATCHES
alLMatches = self.matchSubset(**criteria)
matchTimes = ... | identify all recent matches for player given optional, additional criteria |
def export_datasource_schema(back_references):
data = dict_import_export.export_schema_to_dict(
back_references=back_references)
yaml.safe_dump(data, stdout, default_flow_style=False) | Export datasource YAML schema to stdout |
def to_device(b:Tensors, device:torch.device):
"Recursively put `b` on `device`."
device = ifnone(device, defaults.device)
if is_listy(b): return [to_device(o, device) for o in b]
if is_dict(b): return {k: to_device(v, device) for k, v in b.items()}
return b.to(device, non_blocking=True) | Recursively put `b` on `device`. |
def visit_while(self, node):
whiles = "while %s:\n%s" % (node.test.accept(self), self._stmt_list(node.body))
if node.orelse:
whiles = "%s\nelse:\n%s" % (whiles, self._stmt_list(node.orelse))
return whiles | return an astroid.While node as string |
def df(self, src):
return self._getStdOutCmd([self._hadoop_cmd, 'fs', '-df', self._full_hdfs_path(src)], True) | Perform ``df`` on a path |
def extendMarkdown(self, md, md_globals):
md.registerExtension(self)
md.preprocessors.add('fenced_code_block',
SpecialFencePreprocessor(md),
">normalize_whitespace") | Add FencedBlockPreprocessor to the Markdown instance. |
def cublasSdgmm(handle, mode, m, n, A, lda, x, incx, C, ldc):
status = _libcublas.cublasSdgmm(handle,
_CUBLAS_SIDE[mode],
m, n,
int(A), lda,
int(x), incx,
... | Matrix-diagonal matrix product for real general matrix. |
def peaks(x, y, lookahead=20, delta=0.00003):
_max, _min = peakdetect(y, x, lookahead, delta)
x_peaks = [p[0] for p in _max]
y_peaks = [p[1] for p in _max]
x_valleys = [p[0] for p in _min]
y_valleys = [p[1] for p in _min]
_peaks = [x_peaks, y_peaks]
_valleys = [x_valleys, y_valleys]
retu... | A wrapper around peakdetect to pack the return values in a nicer format |
def to_type(value, ptype):
if ptype == 'str':
return str(value)
elif ptype == 'int':
return int(value)
elif ptype == 'float':
return float(value)
elif ptype == 'bool':
if value.lower() == 'true':
return True
elif value.lower() == 'false':
r... | Convert value to ptype |
def dispatch_request(self, req):
log.debug("Dispatching request: {}".format(str(req)))
res = None
try:
req.validate()
except MissingFieldError as e:
res = APIMissingFieldErrorResponse(str(e))
if not res:
try:
res = req.dispatch(... | Dispatch a request object. |
def keys_values(self):
keys_values = []
for value in self.keys.values():
if isinstance(value, list):
keys_values += value
elif isinstance(value, basestring) and not value.startswith('-'):
keys_values.append(value)
elif isinstance(value,... | Key values might be a list or not, always return a list. |
def parse(string, language=None):
if language:
string = replace_word_tokens(string, language)
tokens = tokenize(string)
postfix = to_postfix(tokens)
return evaluate_postfix(postfix) | Return a solution to the equation in the input string. |
def parse_correlation(self, f):
s_names = None
data = list()
for l in f['f'].splitlines():
s = l.strip().split("\t")
if s_names is None:
s_names = [ x for x in s if x != '' ]
else:
data.append(s[1:])
if f['fn'] == 'corrM... | Parse RNA-SeQC correlation matrices |
def xml(self, fn=None, src='word/document.xml', XMLClass=XML, **params):
"return the src with the given transformation applied, if any."
if src in self.xml_cache: return self.xml_cache[src]
if src not in self.zipfile.namelist(): return
x = XMLClass(
fn=fn or (self.fn and ... | return the src with the given transformation applied, if any. |
async def setFormName(self, oldn, newn):
logger.info(f'Migrating [{oldn}] to [{newn}]')
async with self.getTempSlab():
i = 0
async for buid, valu in self.getFormTodo(oldn):
await self.editNodeNdef((oldn, valu), (newn, valu))
i = i + 1
... | Rename a form within all the layers. |
def error(self, err=None):
if self.state == 'half-open':
self.test_fail_count = min(self.test_fail_count + 1, 16)
self.errors.append(self.clock())
if len(self.errors) > self.maxfail:
time = self.clock() - self.errors.pop(0)
if time < self.time_unit:
... | Update the circuit breaker with an error event. |
def _make_interpolation_node(self, tag_type, tag_key, leading_whitespace):
if tag_type == '!':
return _CommentNode()
if tag_type == '=':
delimiters = tag_key.split()
self._change_delimiters(delimiters)
return _ChangeNode(delimiters)
if tag_type == ... | Create and return a non-section node for the parse tree. |
def read_fastq(filename):
if not filename:
return itertools.cycle((None,))
if filename == "-":
filename_fh = sys.stdin
elif filename.endswith('gz'):
if is_python3:
filename_fh = gzip.open(filename, mode='rt')
else:
filename_fh = BufferedReader(gzip.ope... | return a stream of FASTQ entries, handling gzipped and empty files |
def GetCountStopTimes(self):
cursor = self._schedule._connection.cursor()
cursor.execute(
'SELECT count(*) FROM stop_times WHERE trip_id=?', (self.trip_id,))
return cursor.fetchone()[0] | Return the number of stops made by this trip. |
def trim(self):
for key, value in list(iteritems(self.counters)):
if value.empty():
del self.counters[key] | Clear not used counters |
def _chk_fields(field_data, field_formatter):
if len(field_data) == len(field_formatter):
return
len_dat = len(field_data)
len_fmt = len(field_formatter)
msg = [
"FIELD DATA({d}) != FORMATTER({f})".format(d=len_dat, f=len_fmt),
"DAT({N}): {D}".format(N... | Check that expected fields are present. |
def on_any_event(self, event):
for delegate in self.delegates:
if hasattr(delegate, "on_any_event"):
delegate.on_any_event(event) | On any event method |
def safe_setattr(obj, name, value):
try:
setattr(obj, name, value)
return True
except AttributeError:
return False | Attempt to setattr but catch AttributeErrors. |
def _treat_devices_removed(self):
for device in self._removed_ports.copy():
eventlet.spawn_n(self._process_removed_port, device) | Process the removed devices. |
def isAvailable(self, requester, access):
debuglog("%s isAvailable(%s, %s): self.owners=%r"
% (self, requester, access, self.owners))
num_excl, num_counting = self._claimed_excl, self._claimed_counting
for idx, waiter in enumerate(self.waiting):
if waiter[0] is reque... | Return a boolean whether the lock is available for claiming |
def to_json(self):
obj = {
"vertices": [
{
"id": vertex.id,
"annotation": vertex.annotation,
}
for vertex in self.vertices
],
"edges": [
{
"id": edge.id... | Convert to a JSON string. |
def _from_dict(cls, _dict):
args = {}
if 'entities' in _dict:
args['entities'] = [
RelationEntity._from_dict(x) for x in (_dict.get('entities'))
]
if 'location' in _dict:
args['location'] = _dict.get('location')
if 'text' in _dict:
... | Initialize a RelationArgument object from a json dictionary. |
def _apply_cached_indexes(self, cached_indexes, persist=False):
for elt in ['valid_input_index', 'valid_output_index',
'index_array', 'distance_array']:
val = cached_indexes[elt]
if isinstance(val, tuple):
val = cached_indexes[elt][0]
elif ... | Reassign various resampler index attributes. |
def add_toolbars_to_menu(self, menu_title, actions):
view_menu = self.menus[6]
if actions == self.toolbars and view_menu:
toolbars = []
for toolbar in self.toolbars:
action = toolbar.toggleViewAction()
toolbars.append(action)
add... | Add toolbars to a menu. |
def addVariantSet(self, variantSet):
id_ = variantSet.getId()
self._variantSetIdMap[id_] = variantSet
self._variantSetNameMap[variantSet.getLocalId()] = variantSet
self._variantSetIds.append(id_) | Adds the specified variantSet to this dataset. |
def ping_directories(self, request, queryset, messages=True):
for directory in settings.PING_DIRECTORIES:
pinger = DirectoryPinger(directory, queryset)
pinger.join()
if messages:
success = 0
for result in pinger.results:
if ... | Ping web directories for selected entries. |
def top_view(self):
self.msg.template(78)
print("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}".format(
"| Package", " " * 17,
"New Version", " " * 8,
"Arch", " " * 4,
"Build", " " * 2,
"Repos", " " * 10,
"Size"))
self.msg.template(78) | Print packages status bar |
def _setup_ipc(self):
log.debug('Setting up the internal IPC proxy')
self.ctx = zmq.Context()
self.sub = self.ctx.socket(zmq.SUB)
self.sub.bind(PUB_PX_IPC_URL)
self.sub.setsockopt(zmq.SUBSCRIBE, b'')
log.debug('Setting HWM for the proxy frontend: %d', self.hwm)
tr... | Setup the IPC PUB and SUB sockets for the proxy. |
def zoom_out_pixel(self, curr_pixel):
low_frag = curr_pixel[0]
high_frag = curr_pixel[1]
level = curr_pixel[2]
str_level = str(level)
if level < self.n_level - 1:
low_super = self.spec_level[str_level]["fragments_dict"][low_frag][
"super_index"
... | return the curr_frag at a lower resolution |
def yara_match(file_path, rules):
print('New Extracted File: {:s}'.format(file_path))
print('Mathes:')
pprint(rules.match(file_path)) | Callback for a newly extracted file |
def _on_changed(self):
page = self._get_page()
if not page.flag_autosave:
page.flag_changed = True
self._update_gui_text_tabs() | Slot for changed events |
def _add_parent_cnt(self, hdr, goobj, c2ps):
if goobj.id in c2ps:
parents = c2ps[goobj.id]
if 'prt_pcnt' in self.present or parents and len(goobj.parents) != len(parents):
assert len(goobj.parents) == len(set(goobj.parents))
hdr.append("p{N}".format(N=len(... | Add the parent count to the GO term box for if not all parents are plotted. |
def use_comparative_hierarchy_view(self):
self._hierarchy_view = COMPARATIVE
for session in self._get_provider_sessions():
try:
session.use_comparative_hierarchy_view()
except AttributeError:
pass | Pass through to provider HierarchyLookupSession.use_comparative_hierarchy_view |
def next_bit_address(self):
if self._current_bit_address == "":
if self._is_16bit:
return "{0}.{1}".format(
self.next_address(),
"00")
return "{0}.{1}".format(
self.next_address(),
"0")
if sel... | Gets the next boolean address |
def clamp(self, clampVal):
if self.x > clampVal:
self.x = clampVal
if self.y > clampVal:
self.y = clampVal
if self.z > clampVal:
self.z = clampVal
if self.w > clampVal:
self.w = clampVal | Clamps all the components in the vector to the specified clampVal. |
def qual(obj):
return u'{}.{}'.format(obj.__class__.__module__, obj.__class__.__name__) | Return fully qualified name of a class. |
def writeString(self, u):
s = self.context.getBytesForString(u)
self.writeBytes(s) | Write a unicode to the data stream. |
def write_pidfile(pidfile):
pid = os.getpid()
if pidfile:
with open(pidfile, "w", encoding="utf-8") as fobj:
fobj.write(six.u(str(pid)))
return pid | write current pid to pidfile. |
def _get_temp(self, content):
temp = None
for line in content.splitlines():
if not temp:
match = TEMP_NEEDLE.match(line)
if match:
temp = match.group(1).strip()
continue
else:
match = TEMP_END... | Get the string that points to a specific base16 scheme. |
def update_records(self, domain, records):
if not isinstance(records, list):
raise TypeError("Expected records of type list")
uri = "/domains/%s/records" % utils.get_id(domain)
resp, resp_body = self._async_call(uri, method="PUT",
body={"records": records},
... | Modifies an existing records for a domain. |
def to_element(self, root_name=None):
if not root_name:
root_name = self.nodename
elem = ElementTreeBuilder.Element(root_name)
for attrname in self.serializable_attributes():
try:
value = self.__dict__[attrname]
except KeyError:
... | Serialize this `Resource` instance to an XML element. |
def check_uniqe(self, obj_class, error_msg=_('Must be unique'), **kwargs):
if obj_class.objects.filter(**kwargs).exclude(pk=self.instance.pk):
raise forms.ValidationError(error_msg) | check if this object is unique |
def remove(self, spec_or_id, multi=True, *args, **kwargs):
if multi:
return self.delete_many(spec_or_id)
return self.delete_one(spec_or_id) | Backwards compatibility with remove |
def add_button(self, name, button_class=wtf_fields.SubmitField, **options):
self._buttons[name] = button_class(**options) | Adds a button to the form. |
def _parse_sacct(sacct_jobs: List[dict], jobs_count: int=None):
failed_jobs = sacct_api.filter_jobs(sacct_jobs, failed=True)
completed_jobs = [job for job in sacct_jobs if job['is_completed']]
last_job_end = completed_jobs[-1]['end'] if len(completed_jobs) > 0 else None
data = {
... | Parse out info from Sacct log. |
def net_recv(ws, conn):
in_data = conn.recv(RECEIVE_BYTES)
if not in_data:
print('Received 0 bytes (connection closed)')
ws.receive_data(None)
else:
print('Received {} bytes'.format(len(in_data)))
ws.receive_data(in_data) | Read pending data from network into websocket. |
def userinfo_json(request, user_id):
data = {'first_name': '',
'last_name': '',
'email': '',
'slug': '',
'bio': '',
'phone': '',
'is_active': False}
try:
member = StaffMember.objects.get(pk=user_id)
for key in data.keys():
... | Return the user's information in a json object |
def unique_string(length=UUID_LENGTH):
string = str(uuid4()) * int(math.ceil(length / float(UUID_LENGTH)))
return string[:length] if length else string | Generate a unique string |
def local_session(factory):
factory_region = getattr(factory, 'region', 'global')
s = getattr(CONN_CACHE, factory_region, {}).get('session')
t = getattr(CONN_CACHE, factory_region, {}).get('time')
n = time.time()
if s is not None and t + (60 * 45) > n:
return s
s = factory()
setattr(... | Cache a session thread local for up to 45m |
def _get_site_amplification_term(self, C, vs30):
f_s = np.zeros_like(vs30)
idx = np.logical_and(vs30 < 800.0, vs30 >= 360.0)
f_s[idx] = C["eB"]
idx = np.logical_and(vs30 < 360.0, vs30 >= 180.0)
f_s[idx] = C["eC"]
idx = vs30 < 180.0
f_s[idx] = C["eD"]
retur... | Returns the site amplification given Eurocode 8 site classification |
def add_permission(self, role, name):
if self.has_permission(role, name):
return True
targetGroup = AuthGroup.objects(role=role, creator=self.client).first()
if not targetGroup:
return False
permission = AuthPermission.objects(name=name).update(
ad... | authorize a group for something |
def print_user(self, user):
status = "active"
token = user.token
if token in ['finished', 'revoked']:
status = token
if token is None:
token = ''
subid = "%s\t%s[%s]" %(user.id, token, status)
print(subid)
return subid | print a relational database user |
def _get_item_class(self, url):
if '/layers/' in url:
return Layer
elif '/tables/' in url:
return Table
elif '/sets/' in url:
return Set
else:
raise NotImplementedError("No support for catalog results of type %s" % url) | Return the model class matching a URL |
def _WriteAttributes(self):
if "w" not in self.mode:
return
if self.urn is None:
raise ValueError("Storing of anonymous AFF4 objects not supported.")
to_set = {}
for attribute_name, value_array in iteritems(self.new_attributes):
to_set_list = to_set.setdefault(attribute_name, [])
... | Write the dirty attributes to the data store. |
def _remove_lead_trail_false(bool_list):
for i in (0, -1):
while bool_list and not bool_list[i]:
bool_list.pop(i)
return bool_list | Remove leading and trailing false's from a list |
def create_shield_layer(shield, hashcode):
return pgnreader.parse_pagan_file(('%s%spgn%s' % (PACKAGE_DIR, os.sep, os.sep)) + shield + '.pgn', hashcode, sym=False, invert=False) | Creates the layer for shields. |
def isSequence(arg):
if hasattr(arg, "strip"):
return False
if hasattr(arg, "__getslice__"):
return True
if hasattr(arg, "__iter__"):
return True
return False | Check if input is iterable. |
def isVisible(self, instance, mode='view', default="visible", field=None):
vis_dic = getattr(aq_base(self), 'visible', _marker)
state = default
if vis_dic is _marker:
return state
if type(vis_dic) is DictType:
state = vis_dic.get(mode, state)
elif not vis_dic:
state = 'invisi... | decide if a field is visible in a given mode -> 'state'. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.