code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def from_id(reddit_session, subreddit_id):
pseudo_data = {'id': subreddit_id,
'permalink': '/comments/{0}'.format(subreddit_id)}
return Submission(reddit_session, pseudo_data) | Return an edit-only submission object based on the id. |
def unoptimize_scope(self, frame):
if frame.identifiers.declared:
self.writeline('%sdummy(%s)' % (
unoptimize_before_dead_code and 'if 0: ' or '',
', '.join('l_' + name for name in frame.identifiers.declared)
)) | Disable Python optimizations for the frame. |
def regions(self):
regions = []
elem = self.dimensions["region"].elem
for option_elem in elem.find_all("option"):
region = option_elem.text.strip()
regions.append(region)
return regions | Get a list of all regions |
def add_node(self, node):
if self.controllers.get(node.controller_type, None):
raise RuntimeError("Cannot add node {} to the node group. A node for {} group is already assigned".format(
node,
node.controller_type
))
self.nodes.append(node)
... | A a Node object to the group. Only one node per cgroup is supported |
def find_poor_default_arg(node):
poor_defaults = [
ast.Call,
ast.Dict,
ast.DictComp,
ast.GeneratorExp,
ast.List,
ast.ListComp,
ast.Set,
ast.SetComp,
]
return (
isinstance(node, ast.FunctionDef)
and any((n for n in node.args.defa... | Finds poor default args |
def fail_eof(self, end_tokens=None, lineno=None):
stack = list(self._end_token_stack)
if end_tokens is not None:
stack.append(end_tokens)
return self._fail_ut_eof(None, stack, lineno) | Like fail_unknown_tag but for end of template situations. |
def write_def_decl(self, node, identifiers):
funcname = node.funcname
namedecls = node.get_argument_expressions()
nameargs = node.get_argument_expressions(as_call=True)
if not self.in_def and (
len(self.identifiers.locally_assigned) > 0 or
... | write a locally-available callable referencing a top-level def |
def pvalues(self):
self.compute_statistics()
lml_alts = self.alt_lmls()
lml_null = self.null_lml()
lrs = -2 * lml_null + 2 * asarray(lml_alts)
from scipy.stats import chi2
chi2 = chi2(df=1)
return chi2.sf(lrs) | Association p-value for candidate markers. |
def convert(self, value, param, ctx):
self.gandi = ctx.obj
choices = [choice.replace('*', '') for choice in self.choices]
value = value.replace('*', '')
if value in choices:
return value
new_value = '%s 64 bits' % value
if new_value in choices:
ret... | Try to find correct disk image regarding version. |
def serialize(dictionary):
data = []
for key, value in dictionary.items():
data.append('{0}="{1}"'.format(key, value))
return ', '.join(data) | Turn dictionary into argument like string. |
def _index_local_ref(fasta_file, cortex_dir, stampy_dir, kmers):
base_out = os.path.splitext(fasta_file)[0]
cindexes = []
for kmer in kmers:
out_file = "{0}.k{1}.ctx".format(base_out, kmer)
if not file_exists(out_file):
file_list = "{0}.se_list".format(base_out)
with ... | Pre-index a generated local reference sequence with cortex_var and stampy. |
def _hashfile(self,filename,blocksize=65536):
logger.debug("Hashing file %s"%(filename))
hasher=hashlib.sha256()
afile=open(filename,'rb')
buf=afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
return hasher.he... | Hashes the file and returns hash |
def url_prefixed(regex, view, name=None):
return url(r'^%(app_prefix)s%(regex)s' % {
'app_prefix': APP_PREFIX, 'regex': regex}, view, name=name) | Returns a urlpattern prefixed with the APP_NAME in debug mode. |
def _aggregate_func(self, aggregate):
funcs = {"sum": add, "min": min, "max": max}
func_name = aggregate.lower() if aggregate else 'sum'
try:
return funcs[func_name]
except KeyError:
raise TypeError("Unsupported aggregate: {}".format(aggregate)) | Return a suitable aggregate score function. |
def insertDatastore(self, index, store):
if not isinstance(store, Datastore):
raise TypeError("stores must be of type %s" % Datastore)
self._stores.insert(index, store) | Inserts datastore `store` into this collection at `index`. |
def get(search="unsigned"):
plugins = []
for i in os.walk('/usr/lib/nagios/plugins'):
for f in i[2]:
plugins.append(f)
return plugins | List all available plugins |
def _convert_epoch_anchor(cls, reading):
delta = datetime.timedelta(seconds=reading.value)
return cls._EpochReference + delta | Convert a reading containing an epoch timestamp to datetime. |
def _windowsLdmodSources(target, source, env, for_signature):
return _dllSources(target, source, env, for_signature, 'LDMODULE') | Get sources for loadable modules. |
def pretty_print(self):
pt = PrettyTable()
if len(self) == 0:
pt._set_field_names(['Sorry,'])
pt.add_row([TRAIN_NOT_FOUND])
else:
pt._set_field_names(self.headers)
for train in self.trains:
pt.add_row(train)
print(pt) | Use `PrettyTable` to perform formatted outprint. |
def stop(self):
if self.uiautomator_process and self.uiautomator_process.poll() is None:
res = None
try:
res = urllib2.urlopen(self.stop_uri)
self.uiautomator_process.wait()
except:
self.uiautomator_process.kill()
fi... | Stop the rpc server. |
def _uncamelize(self, s):
res = ''
if s:
for i in range(len(s)):
if i > 0 and s[i].lower() != s[i]:
res += '_'
res += s[i].lower()
return res | Convert a camel-cased string to using underscores |
def map(self, f, preservesPartitioning=False):
def func(iterator):
return map(f, iterator)
return self.mapPartitions(func, preservesPartitioning) | Return a new DStream by applying a function to each element of DStream. |
def parse_assembly(llvmir, context=None):
if context is None:
context = get_global_context()
llvmir = _encode_string(llvmir)
strbuf = c_char_p(llvmir)
with ffi.OutputString() as errmsg:
mod = ModuleRef(
ffi.lib.LLVMPY_ParseAssembly(context, strbuf, errmsg),
contex... | Create Module from a LLVM IR string |
def wrap_stub(elf_file):
print('Wrapping ELF file %s...' % elf_file)
e = esptool.ELFFile(elf_file)
text_section = e.get_section('.text')
try:
data_section = e.get_section('.data')
except ValueError:
data_section = None
stub = {
'text': text_section.data,
'text_s... | Wrap an ELF file into a stub 'dict' |
def enable_vxlan_feature(self, nexus_host, nve_int_num, src_intf):
starttime = time.time()
self.send_edit_string(nexus_host, snipp.PATH_VXLAN_STATE,
(snipp.BODY_VXLAN_STATE % "enabled"))
self.send_edit_string(nexus_host, snipp.PATH_VNSEG_STATE,
... | Enable VXLAN on the switch. |
def add_tracked_motors(self, tracked_motors):
new_mockup_motors = map(self.get_mockup_motor, tracked_motors)
self.tracked_motors = list(set(self.tracked_motors + new_mockup_motors)) | Add new motors to the recording |
def read (self, stream):
self._data = stream.read(self._size)
if len(self._data) >= self._size:
values = struct.unpack(self._format, self._data)
else:
values = None, None, None, None, None, None, None
if values[0] == 0xA1B2C3D4 or values[0] == 0xA1B23C4D:
... | Reads PCapGlobalHeader data from the given stream. |
def update_name(self, force=False, create_term=False, report_unchanged=True):
updates = []
self.ensure_identifier()
name_term = self.find_first('Root.Name')
if not name_term:
if create_term:
name_term = self['Root'].new_term('Root.Name','')
else:
... | Generate the Root.Name term from DatasetName, Version, Origin, TIme and Space |
def write_pdb(self, mol, filename, name=None, num=None):
scratch = tempfile.gettempdir()
with ScratchDir(scratch, copy_to_current_on_exit=False) as _:
mol.to(fmt="pdb", filename="tmp.pdb")
bma = BabelMolAdaptor.from_file("tmp.pdb", "pdb")
num = num or 1
name = nam... | dump the molecule into pdb file with custom residue name and number. |
def connection_class(self, adapter):
if self.adapters.get(adapter):
return self.adapters[adapter]
try:
class_prefix = getattr(
__import__('db.' + adapter, globals(), locals(),
['__class_prefix__']), '__class_prefix__')
driver... | Get connection class by adapter |
def add_person_entity(self, entity, instances_json):
check_type(instances_json, dict, [entity.plural])
entity_ids = list(map(str, instances_json.keys()))
self.persons_plural = entity.plural
self.entity_ids[self.persons_plural] = entity_ids
self.entity_counts[self.persons_plural] ... | Add the simulation's instances of the persons entity as described in ``instances_json``. |
def deactivate():
if hasattr(_mode, "current_state"):
del _mode.current_state
if hasattr(_mode, "schema"):
del _mode.schema
for k in connections:
con = connections[k]
if hasattr(con, 'reset_schema'):
con.reset_schema() | Deactivate a state in this thread. |
def as_spinmode(cls, obj):
if isinstance(obj, cls):
return obj
else:
try:
return _mode2spinvars[obj]
except KeyError:
raise KeyError("Wrong value for spin_mode: %s" % str(obj)) | Converts obj into a `SpinMode` instance |
def generate_matching_datasets(self, data_slug):
matching_hubs = VERTICAL_HUB_MAP[data_slug]['hubs']
return Dataset.objects.filter(hub_slug__in=matching_hubs) | Return datasets that belong to a vertical by querying hubs. |
def crypto_key_version_path(
cls, project, location, key_ring, crypto_key, crypto_key_version
):
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}",
project=... | Return a fully-qualified crypto_key_version string. |
def next(self):
item = six.next(self._item_iter)
result = self._item_to_value(self._parent, item)
self._remaining -= 1
return result | Get the next value in the page. |
def load(self):
lg.info('Loading ' + str(self.xml_file))
update_annotation_version(self.xml_file)
xml = parse(self.xml_file)
return xml.getroot() | Load xml from file. |
def _read_imu(self):
self._init_imu()
attempts = 0
success = False
while not success and attempts < 3:
success = self._imu.IMURead()
attempts += 1
time.sleep(self._imu_poll_interval)
return success | Internal. Tries to read the IMU sensor three times before giving up |
def allocate_mid(mids):
i = 0
while True:
mid = str(i)
if mid not in mids:
mids.add(mid)
return mid
i += 1 | Allocate a MID which has not been used yet. |
def reward_bonus(self, assignment_id, amount, reason):
from psiturk.amt_services import MTurkServices
self.amt_services = MTurkServices(
self.aws_access_key_id,
self.aws_secret_access_key,
self.config.getboolean(
'Shell Parameters', 'launch_in_sandbox_... | Reward the Turker with a bonus. |
def _build_matrix_non_uniform(p, q, coords, k):
A = [[1] * (p+q+1)]
for i in range(1, p + q + 1):
line = [(coords[k+j] - coords[k])**i for j in range(-p, q+1)]
A.append(line)
return np.array(A) | Constructs the equation matrix for the finite difference coefficients of non-uniform grids at location k |
def scan(context, root_dir):
root_dir = root_dir or context.obj['root']
config_files = Path(root_dir).glob('*/analysis/*_config.yaml')
for config_file in config_files:
LOG.debug("found analysis config: %s", config_file)
with config_file.open() as stream:
context.invoke(log_cmd, c... | Scan a directory for analyses. |
def parse_bookmark_node (node):
if node["type"] == "url":
yield node["url"], node["name"]
elif node["type"] == "folder":
for child in node["children"]:
for entry in parse_bookmark_node(child):
yield entry | Parse one JSON node of Chromium Bookmarks. |
def info(ctx):
dev = ctx.obj['dev']
controller = ctx.obj['controller']
slot1, slot2 = controller.slot_status
click.echo('Slot 1: {}'.format(slot1 and 'programmed' or 'empty'))
click.echo('Slot 2: {}'.format(slot2 and 'programmed' or 'empty'))
if dev.is_fips:
click.echo('FIPS Approved Mod... | Display status of YubiKey Slots. |
def queue_stats(self, queue, tags):
for mname, pymqi_value in iteritems(metrics.queue_metrics()):
try:
mname = '{}.queue.{}'.format(self.METRIC_PREFIX, mname)
m = queue.inquire(pymqi_value)
self.gauge(mname, m, tags=tags)
except pymqi.Error... | Grab stats from queues |
def main(path_dir, requirements_name):
click.echo("\nWARNING: Uninstall libs it's at your own risk!")
click.echo('\nREMINDER: After uninstall libs, update your requirements '
'file.\nUse the `pip freeze > requirements.txt` command.')
click.echo('\n\nList of installed libs and your dependencie... | Console script for imports. |
def intSubset(self):
ret = libxml2mod.xmlGetIntSubset(self._o)
if ret is None:raise treeError('xmlGetIntSubset() failed')
__tmp = xmlDtd(_obj=ret)
return __tmp | Get the internal subset of a document |
def shell(self):
click.echo(click.style("NOTICE!", fg="yellow", bold=True) + " This is a " + click.style("local", fg="green", bold=True) + " shell, inside a " + click.style("Zappa", bold=True) + " object!")
self.zappa.shell()
return | Spawn a debug shell. |
def resolve_config(self):
conf = self.load_config(self.force_default)
for k in conf['hues']:
conf['hues'][k] = getattr(KEYWORDS, conf['hues'][k])
as_tuples = lambda name, obj: namedtuple(name, obj.keys())(**obj)
self.hues = as_tuples('Hues', conf['hues'])
self.opts = as_tuples('Options', conf[... | Resolve configuration params to native instances |
def rollback(self, revision):
print("Rolling back..")
self.zappa.rollback_lambda_function_version(
self.lambda_name, versions_back=revision)
print("Done!") | Rollsback the currently deploy lambda code to a previous revision. |
def start(self):
setproctitle('oq-zworkerpool %s' % self.ctrl_url[6:])
self.workers = []
for _ in range(self.num_workers):
sock = z.Socket(self.task_out_port, z.zmq.PULL, 'connect')
proc = multiprocessing.Process(target=self.worker, args=(sock,))
proc.start()
... | Start worker processes and a control loop |
def attach(cls, name, vhost, remote_name):
paas_access = cls.get('paas_access')
if not paas_access:
paas_info = cls.info(name)
paas_access = '%s@%s' \
% (paas_info['user'], paas_info['git_server'])
remote_url = 'ssh+git://%s/%s.git' % (paas_acces... | Attach an instance's vhost to a remote from the local repository. |
def BytesIO(*args, **kwargs):
raw = sync_io.BytesIO(*args, **kwargs)
return AsyncBytesIOWrapper(raw) | BytesIO constructor shim for the async wrapper. |
def strip_stop(tokens, start, result):
for e in result:
for child in e.iter():
if child.text.endswith('.'):
child.text = child.text[:-1]
return result | Remove trailing full stop from tokens. |
def merge(a, b):
"merges b into a recursively if a and b are dicts"
for key in b:
if isinstance(a.get(key), dict) and isinstance(b.get(key), dict):
merge(a[key], b[key])
else:
a[key] = b[key]
return a | merges b into a recursively if a and b are dicts |
def from_ip(cls, ip):
result = cls.list({'items_per_page': 500})
webaccs = {}
for webacc in result:
for server in webacc['servers']:
webaccs[server['ip']] = webacc['id']
return webaccs.get(ip) | Retrieve webacc id associated to a webacc ip |
def apt_cache(in_memory=True, progress=None):
from apt import apt_pkg
apt_pkg.init()
if in_memory:
apt_pkg.config.set("Dir::Cache::pkgcache", "")
apt_pkg.config.set("Dir::Cache::srcpkgcache", "")
return apt_pkg.Cache(progress) | Build and return an apt cache. |
def GetCalendarDatesFieldValuesTuples(self):
result = []
for date_tuple in self.GenerateCalendarDatesFieldValuesTuples():
result.append(date_tuple)
result.sort()
return result | Return a list of date execeptions |
def readfp(self, fp, filename=None):
warnings.warn(
"This method will be removed in future versions. "
"Use 'parser.read_file()' instead.",
DeprecationWarning, stacklevel=2
)
self.read_file(fp, source=filename) | Deprecated, use read_file instead. |
def add_http_basic_auth(url,
user=None,
password=None,
https_only=False):
if user is None and password is None:
return url
else:
urltuple = urlparse(url)
if https_only and urltuple.scheme != 'https':
rais... | Return a string with http basic auth incorporated into it |
def update_warning_menu(self):
editor = self.get_current_editor()
check_results = editor.get_current_warnings()
self.warning_menu.clear()
filename = self.get_current_filename()
for message, line_number in check_results:
error = 'syntax' in message
t... | Update warning list menu |
def _has_message(self):
sep = protocol.MINIMAL_LINE_SEPARATOR.encode(self.encoding)
return sep in self._receive_buffer | Whether or not we have messages available for processing. |
def convex_hull_image(image):
labels = image.astype(int)
points, counts = convex_hull(labels, np.array([1]))
output = np.zeros(image.shape, int)
for i in range(counts[0]):
inext = (i+1) % counts[0]
draw_line(output, points[i,1:], points[inext,1:],1)
output = fill_labeled_holes(output... | Given a binary image, return an image of the convex hull |
def move_examples(root, lib_dir):
all_pde = files_multi_pattern(root, INO_PATTERNS)
lib_pde = files_multi_pattern(lib_dir, INO_PATTERNS)
stray_pde = all_pde.difference(lib_pde)
if len(stray_pde) and not len(lib_pde):
log.debug(
'examples found outside lib dir, moving them: %s', stray... | find examples not under lib dir, and move into ``examples`` |
def _read_stepfiles_list(path_prefix, path_suffix=".index", min_steps=0):
stepfiles = []
for filename in _try_twice_tf_glob(path_prefix + "*-[0-9]*" + path_suffix):
basename = filename[:-len(path_suffix)] if path_suffix else filename
try:
steps = int(basename.rsplit("-")[-1])
except ValueError:
... | Return list of StepFiles sorted by step from files at path_prefix. |
def skip_status(*skipped):
def decorator(func):
@functools.wraps(func)
def _skip_status(self, *args, **kwargs):
if self.status not in skipped:
return func(self, *args, **kwargs)
return _skip_status
return decorator | Decorator to skip this call if we're in one of the skipped states. |
def extract_tree_block(self):
"iterate through data file to extract trees"
lines = iter(self.data)
while 1:
try:
line = next(lines).strip()
except StopIteration:
break
if line.lower() == "begin trees;":
w... | iterate through data file to extract trees |
def call_spellchecker(cmd, input_text=None, encoding=None):
process = get_process(cmd)
if input_text is not None:
for line in input_text.splitlines():
offset = 0
end = len(line)
while True:
chunk_end = offset + 0x1fff
m = None if chunk_... | Call spell checker with arguments. |
def _already_cutoff_filtered(in_file, filter_type):
filter_file = "%s-filter%s.vcf.gz" % (utils.splitext_plus(in_file)[0], filter_type)
return utils.file_exists(filter_file) | Check if we have a pre-existing cutoff-based filter file from previous VQSR failure. |
def newline(self):
self.write(self.term.move_down)
self.write(self.term.clear_bol) | Effects a newline by moving the cursor down and clearing |
def update_priority(self, tree_idx_list, priority_list):
for tree_idx, priority, segment_tree in zip(tree_idx_list, priority_list, self.segment_trees):
segment_tree.update(tree_idx, priority) | Update priorities of the elements in the tree |
def autodecode(self, a_bytes):
try:
analysis = chardet.detect(a_bytes)
if analysis["confidence"] >= 0.75:
return (self.decode(a_bytes, analysis["encoding"])[0],
analysis["encoding"])
else:
raise Exception("Failed to dete... | Automatically detect encoding, and decode bytes. |
def manifests_parse(self):
self.manifests = []
for manifest_path in self.find_manifests():
if self.manifest_path_is_old(manifest_path):
print("fw: Manifest (%s) is old; consider 'manifest download'" % (manifest_path))
manifest = self.manifest_parse(manifest_path)
... | parse manifests present on system |
def resource_redirect(id):
resource = get_resource(id)
return redirect(resource.url.strip()) if resource else abort(404) | Redirect to the latest version of a resource given its identifier. |
def error_wrap(func):
def f(*args, **kw):
code = func(*args, **kw)
check_error(code, context="client")
return f | Parses a s7 error code returned the decorated function. |
def parse_numtuple(s,intype,length=2,scale=1):
if intype == int:
numrx = intrx_s;
elif intype == float:
numrx = fltrx_s;
else:
raise NotImplementedError("Not implemented for type: {}".format(
intype));
if parse_utuple(s, numrx, length=length) is None:
raise Va... | parse a string into a list of numbers of a type |
def convert(self, value, view):
is_mapping = isinstance(self.template, MappingTemplate)
for candidate in self.allowed:
try:
if is_mapping:
if isinstance(candidate, Filename) and \
candidate.relative_to:
n... | Ensure that the value follows at least one template. |
def run_console(*, locals=None, banner=None, serve=None, prompt_control=None):
loop = InteractiveEventLoop(
locals=locals,
banner=banner,
serve=serve,
prompt_control=prompt_control)
asyncio.set_event_loop(loop)
try:
loop.run_forever()
except KeyboardInterrupt:
... | Run the interactive event loop. |
def paths(self):
paths = self._cfg.get('paths')
if not paths:
raise ValueError('Paths Object has no values, You need to define them in your swagger file')
for path in paths:
if not path.startswith('/'):
raise ValueError('Path object {0} should start with /... | returns an iterator for the relative resource paths specified in the swagger file |
def _follow_link(self, value):
seen_keys = set()
while True:
link_key = self._link_for_value(value)
if not link_key:
return value
assert link_key not in seen_keys, 'circular symlink reference'
seen_keys.add(link_key)
value = super(SymlinkDatastore, self).get(link_key) | Returns given `value` or, if it is a symlink, the `value` it names. |
def zip(what, archive_zip='', risk_file=''):
if os.path.isdir(what):
oqzip.zip_all(what)
elif what.endswith('.xml') and '<logicTree' in open(what).read(512):
oqzip.zip_source_model(what, archive_zip)
elif what.endswith('.xml') and '<exposureModel' in open(what).read(512):
oqzip.zip_e... | Zip into an archive one or two job.ini files with all related files |
def flush(self):
now = time.time()
to_remove = []
for k, entry in self.pool.items():
if entry.timestamp < now:
entry.client.close()
to_remove.append(k)
for k in to_remove:
del self.pool[k] | remove all stale clients from pool |
def working_dir(val, **kwargs):
try:
is_abs = os.path.isabs(val)
except AttributeError:
is_abs = False
if not is_abs:
raise SaltInvocationError('\'{0}\' is not an absolute path'.format(val))
return val | Must be an absolute path |
def save_text_to_file(content: str, path: str):
with open(path, mode='w') as text_file:
text_file.write(content) | Saves text to file |
def survival(value=t, lam=lam, f=failure):
return sum(f * log(lam) - lam * value) | Exponential survival likelihood, accounting for censoring |
def delete_index(self, refresh=False, ignore=None):
es = connections.get_connection("default")
index = self.__class__.search_objects.mapping.index
doc_type = self.__class__.search_objects.mapping.doc_type
es.delete(index, doc_type, id=self.pk, refresh=refresh, ignore=ignore) | Removes the object from the index if `indexed=False` |
def build_class_graph(modules, klass=None, graph=None):
if klass is None:
class_graph = nx.DiGraph()
for name, classmember in inspect.getmembers(modules, inspect.isclass):
if issubclass(classmember, Referent) and classmember is not Referent:
TaxonomyCe... | Builds up a graph of the DictCell subclass structure |
def merge_consecutive_self_time(frame, options):
if frame is None:
return None
previous_self_time_frame = None
for child in frame.children:
if isinstance(child, SelfTimeFrame):
if previous_self_time_frame:
previous_self_time_frame.self_time += child.self_time
... | Combines consecutive 'self time' frames |
def _check(self, accepted):
total = []
if 1 in self.quickresponse:
total = total + self.quickresponse[1]
if (1, 0) in self.quickresponse:
total = total + self.quickresponse[(1, 0)]
for key in total:
if (key.id == 1 or key.id == (1, 0)) and key.type == ... | _check for string existence |
def parse_subcommands(parser, subcommands, argv):
subparsers = parser.add_subparsers(dest='subparser_name')
parser_help = subparsers.add_parser(
'help', help='Detailed help for actions using `help <action>`')
parser_help.add_argument('action', nargs=1)
modules = [
name for _, name, _ in ... | Setup all sub-commands |
def _get_parselypage(self, body):
parser = ParselyPageParser()
ret = None
try:
parser.feed(body)
except HTMLParseError:
pass
if parser.ppage is None:
return
ret = parser.ppage
if ret:
ret = {parser.original_unescape(... | extract the parsely-page meta content from a page |
def _method_complete(self, result):
if isinstance(result, PrettyTensor):
self._head = result
return self
elif isinstance(result, Loss):
return result
elif isinstance(result, PrettyTensorTupleMixin):
self._head = result[0]
return result
else:
self._head = self._head.wi... | Called after an extention method with the result. |
def _findObject(self, img):
from imgProcessor.imgSignal import signalMinimum
i = img > signalMinimum(img)
i = minimum_filter(i, 4)
return boundingBox(i) | Create a bounding box around the object within an image |
def read_requirements():
reqs_path = os.path.join('.', 'requirements.txt')
install_reqs = parse_requirements(reqs_path, session=PipSession())
reqs = [str(ir.req) for ir in install_reqs]
return reqs | parses requirements from requirements.txt |
def _parse_json(cls, resources, exactly_one=True):
if not len(resources['features']):
return None
if exactly_one:
return cls.parse_resource(resources['features'][0])
else:
return [cls.parse_resource(resource) for resource
in resources['feat... | Parse display name, latitude, and longitude from a JSON response. |
def create_marking_iobject(self,
uid=None,
timestamp=timezone.now(),
metadata_dict=None,
id_namespace_uri=DINGOS_DEFAULT_ID_NAMESPACE_URI,
iobject_family_name=DINGOS... | A specialized version of create_iobject with defaults set such that a default marking object is created. |
def refresh(self):
table = self.tableType()
search = nativestring(self._pywidget.text())
if search == self._lastSearch:
return
self._lastSearch = search
if not search:
return
if search in self._cache:
records = self._cache[s... | Refreshes the contents of the completer based on the current text. |
def push(self, data):
data, self._partial = self._partial + data, ''
parts = NLCRE_crack.split(data)
self._partial = parts.pop()
if not self._partial and parts and parts[-1].endswith('\r'):
self._partial = parts.pop(-2)+parts.pop()
lines = []
for i in range(le... | Push some new data into this object. |
def delete_attribute_group(group_id, **kwargs):
user_id = kwargs['user_id']
try:
group_i = db.DBSession.query(AttrGroup).filter(AttrGroup.id==group_id).one()
group_i.project.check_write_permission(user_id)
db.DBSession.delete(group_i)
db.DBSession.flush()
log.info("Group ... | Delete an attribute group. |
def load(self, optional_cfg_files=None):
optional_cfg_files = optional_cfg_files or []
if self._loaded:
raise RuntimeError("INTERNAL ERROR: Attempt to load configuration twice!")
try:
namespace = {}
self._set_defaults(namespace, optional_cfg_files)
... | Actually load the configuation from either the default location or the given directory. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.