code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def call(self, methodname, *args, **kwargs):
for plugin in self._plugins:
method = getattr(plugin, methodname, None)
if method is None:
continue
yield method(*args, **kwargs) | Call a common method on all the plugins, if it exists. |
def frame_apply(obj, func, axis=0, broadcast=None,
raw=False, reduce=None, result_type=None,
ignore_failures=False,
args=None, kwds=None):
axis = obj._get_axis_number(axis)
if axis == 0:
klass = FrameRowApply
elif axis == 1:
klass = FrameColumn... | construct and return a row or column based frame apply object |
def cli(yamlfile, format, output, collections):
print(ShExGenerator(yamlfile, format).serialize(output=output, collections=collections)) | Generate a ShEx Schema for a biolink model |
def fatal(*tokens: Token, **kwargs: Any) -> None:
error(*tokens, **kwargs)
sys.exit(1) | Print an error message and call ``sys.exit`` |
def _set_axis(self, param, unit):
axisValues = []
for astroObject in self.objectList:
try:
value = eval('astroObject.{0}'.format(param))
except ac.HierarchyError:
value = np.nan
if unit is None:
axisValues.append(value)
... | this should take a variable or a function and turn it into a list by evaluating on each planet |
async def save(self):
old_tags = list(self._orig_data['tags'])
new_tags = list(self.tags)
self._changed_data.pop('tags', None)
await super(BlockDevice, self).save()
for tag_name in new_tags:
if tag_name not in old_tags:
await self._handler.add_tag(
... | Save this block device. |
def VCRuntimeRedist(self):
arch_subdir = self.pi.target_dir(x64=True)
if self.vc_ver < 15:
redist_path = self.si.VCInstallDir
vcruntime = 'redist%s\\Microsoft.VC%d0.CRT\\vcruntime%d0.dll'
else:
redist_path = self.si.VCInstallDir.replace('\\Tools', '\\Redist')
... | Microsoft Visual C++ runtime redistribuable dll |
def check_for_bypass_url(raw_creds, nova_args):
if 'BYPASS_URL' in raw_creds.keys():
bypass_args = ['--bypass-url', raw_creds['BYPASS_URL']]
nova_args = bypass_args + nova_args
return nova_args | Return a list of extra args that need to be passed on cmdline to nova. |
def header(self):
if self._block_header is None:
self._block_header = BlockHeader()
self._block_header.ParseFromString(self.block.header)
return self._block_header | Returns the header of the block |
def _read_color_and_depth_image(self):
frames = self._pipe.wait_for_frames()
if self._depth_align:
frames = self._align.process(frames)
depth_frame = frames.get_depth_frame()
color_frame = frames.get_color_frame()
if not depth_frame or not color_frame:
log... | Read a color and depth image from the device. |
def NetFxSDKLibraries(self):
if self.vc_ver < 14.0 or not self.si.NetFxSdkDir:
return []
arch_subdir = self.pi.target_dir(x64=True)
return [os.path.join(self.si.NetFxSdkDir, r'lib\um%s' % arch_subdir)] | Microsoft .Net Framework SDK Libraries |
def load_inventory_from_cache(self):
try:
self.inventory = self.cache.get_all_data_from_cache()
hosts = self.inventory['_meta']['hostvars']
except Exception as e:
print(
"Invalid inventory file %s. Please rebuild with -refresh-cache option."
... | Loads inventory from JSON on disk. |
def translate_detector(self, vector):
vector = np.array(vector, dtype=float)
self.pmts.pos_x += vector[0]
self.pmts.pos_y += vector[1]
self.pmts.pos_z += vector[2]
self.reset_caches() | Translate the detector by a given vector |
def _replace_scalar(self, scalar):
if not is_arg_scalar(scalar):
return scalar
name = scalar[1:]
return self.get_scalar_value(name) | Replace scalar name with scalar value |
def from_int(cls, retries, redirect=True, default=None):
if retries is None:
retries = default if default is not None else cls.DEFAULT
if isinstance(retries, Retry):
return retries
redirect = bool(redirect) and None
new_retries = cls(retries, redirect=redirect)
... | Backwards-compatibility for the old retries format. |
def print_fatal_results(results, level=0):
print_level(logger.critical, _RED + "[X] Fatal Error: %s", level, results.error) | Print fatal errors that occurred during validation runs. |
def run(
self,
cluster_config,
rg_parser,
partition_measurer,
cluster_balancer,
args,
):
self.cluster_config = cluster_config
self.args = args
with ZK(self.cluster_config) as self.zk:
self.log.debug(
... | Initialize cluster_config, args, and zk then call run_command. |
def log_middleware(store):
def wrapper(next_):
def log_dispatch(action):
print('Dispatch Action:', action)
return next_(action)
return log_dispatch
return wrapper | log all actions to console as they are dispatched |
def merge_chromosome_dfs(df_tuple):
plus_df, minus_df = df_tuple
index_cols = "Chromosome Bin".split()
count_column = plus_df.columns[0]
if plus_df.empty:
return return_other(minus_df, count_column, index_cols)
if minus_df.empty:
return return_other(plus_df, count_column, index_cols)... | Merges data from the two strands into strand-agnostic counts. |
def _get_field(xdmf_file, data_item):
shp = _get_dim(data_item)
h5file, group = data_item.text.strip().split(':/', 1)
icore = int(group.split('_')[-2]) - 1
fld = _read_group_h5(xdmf_file.parent / h5file, group).reshape(shp)
return icore, fld | Extract field from data item. |
def _compile_pattern(self, rule):
out = ''
for i, part in enumerate(self.syntax.split(rule)):
if i%3 == 0: out += re.escape(part.replace('\\:',':'))
elif i%3 == 1: out += '(?P<%s>' % part if part else '(?:'
else: out += '%s)' % (part or '[^/]+')
ret... | Return a regular expression with named groups for each wildcard. |
def update_password(self, user, password, skip_validation=False):
pwcol = self.options["password_column"]
pwhash = self.bcrypt.generate_password_hash(password)
if not skip_validation:
self.validate_password(user, password, pwhash)
if self.options['prevent_password_reuse']:
... | Updates the password of a user |
def delete_blob(call=None, kwargs=None):
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit(
'A container must be specified'
)
if 'blob' not in kwargs:
raise SaltCloudSystemExit(
'A blob must be specified'
)
... | Delete a blob from a container. |
def parse_unit(prop, dictionary, dt=None):
try:
dt = timezone.parse_datetime(dictionary.get('date_time'))
except TypeError:
dt = None
matches = [k for k in dictionary.keys() if prop in k]
try:
value = dictionary[matches[0]]
unit = re.search(r' \(([^)]+)\)', matches[0])
... | Do a fuzzy match for `prop` in the dictionary, taking into account unit suffix. |
def packageOf(self, dotted_name, packagelevel=None):
if '.' not in dotted_name:
return dotted_name
if not self.isPackage(dotted_name):
dotted_name = '.'.join(dotted_name.split('.')[:-1])
if packagelevel:
dotted_name = '.'.join(dotted_name.split('.')[:packagele... | Determine the package that contains ``dotted_name``. |
def transformer_base_vq_ada_32ex_packed():
hparams = transformer_base_v2()
expert_utils.update_hparams_for_vq_gating(hparams)
hparams.moe_num_experts = 32
hparams.gating_type = "vq"
hparams.batch_size = 5072
hparams.ffn_layer = "local_moe"
hparams.shared_embedding_and_softmax_weights = False
hparams.lea... | Set of hyperparameters for lm1b packed following tpu params. |
def smsc(self, smscNumber):
if smscNumber != self._smscNumber:
if self.alive:
self.write('AT+CSCA="{0}"'.format(smscNumber))
self._smscNumber = smscNumber | Set the default SMSC number to use when sending SMS messages |
def read_plain_boolean(file_obj, count):
return read_bitpacked(file_obj, count << 1, 1, logger.isEnabledFor(logging.DEBUG)) | Read `count` booleans using the plain encoding. |
def build(pattern=None, path='.'):
path = abspath(path)
c = Clay(path)
c.build(pattern) | Generates a static copy of the sources |
def __find_smallest(self):
minval = sys.maxsize
for i in range(self.n):
for j in range(self.n):
if (not self.row_covered[i]) and (not self.col_covered[j]):
if minval > self.C[i][j]:
minval = self.C[i][j]
return minval | Find the smallest uncovered value in the matrix. |
def size_to_content(self):
new_sizing = self.copy_sizing()
new_sizing.minimum_width = 0
new_sizing.maximum_width = 0
axes = self.__axes
if axes and axes.is_valid:
if axes.y_calibration and axes.y_calibration.units:
new_sizing.minimum_width = self.font_... | Size the canvas item to the proper width. |
def render(self):
tpl = '<xml>\n{data}\n</xml>'
nodes = []
msg_type = '<MsgType><![CDATA[{msg_type}]]></MsgType>'.format(
msg_type=self.type
)
nodes.append(msg_type)
for name, field in self._fields.items():
value = getattr(self, name, field.default... | Render reply from Python object to XML string |
def fig_height(self):
return (
4
+ len(self.data) * len(self.var_names)
- 1
+ 0.1 * sum(1 for j in self.plotters.values() for _ in j.iterator())
) | Figure out the height of this plot. |
def resolve(self, uri=None, **parts):
if uri:
result = self.__class__(urljoin(str(self), str(uri)))
else:
result = self.__class__(self)
for part, value in parts.items():
if part not in self.__all_parts__:
raise TypeError("Unknown URI component: " + part)
setattr(result, part, value)
return resul... | Attempt to resolve a new URI given an updated URI, partial or complete. |
async def _reset_vector(self):
self._logger.debug("sensor_graph subsystem task starting")
self.initialized.set()
while True:
stream, reading = await self._inputs.get()
try:
await process_graph_input(self.graph, stream, reading, self._executor)
... | Background task to initialize this system in the event loop. |
def _parse_check(self, rule):
for check_cls in (checks.FalseCheck, checks.TrueCheck):
check = check_cls()
if rule == str(check):
return check
try:
kind, match = rule.split(':', 1)
except Exception:
if self.raise_error:
... | Parse a single base check rule into an appropriate Check object. |
def sense_dep(self, target):
self.chipset.rf_configuration(0x02, b"\x0B\x0B\x0A")
return super(Device, self).sense_dep(target) | Search for a DEP Target in active or passive communication mode. |
def close(self):
self._closed = True
if self.receive_task:
self.receive_task.cancel()
if self.connection:
self.connection.close() | Close the underlying connection. |
def update_radii(self, radii):
self.radii = np.array(radii, dtype='float32')
prim_radii = self._gen_radii(self.radii)
self._radii_vbo.set_data(prim_radii)
self.widget.update() | Update the radii inplace |
def write_file(path, contents):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as file:
file.write(contents) | Write contents to a local file. |
def do_down(self, arg):
print "running down migration"
self.manager.run_one(arg, Direction.DOWN) | Run down migration with name or numeric id matching arg |
def kwargs_helper(kwargs):
args = []
for param, value in kwargs.items():
param = kw_subst.get(param, param)
args.append((param, value))
return args | This function preprocesses the kwargs dictionary to sanitize it. |
def job_started(self, job, queue):
job.hmset(start=str(datetime.utcnow()), status=STATUSES.RUNNING)
job.tries.hincrby(1)
self.log(self.job_started_message(job, queue))
if hasattr(job, 'on_started'):
job.on_started(queue) | Called just before the execution of the job |
def all(A, ax=None):
if isinstance(A, Poly):
out = numpy.zeros(A.shape, dtype=bool)
B = A.A
for key in A.keys:
out += all(B[key], ax)
return out
return numpy.all(A, ax) | Test if all values in A evaluate to True |
def constants(self):
constants = [ ]
for k in self.__slots__:
v = getattr(self, k)
if isinstance(v, IRExpr):
constants.extend(v.constants)
elif isinstance(v, IRConst):
constants.append(v)
return constants | A list of all of the constants that this expression ends up using. |
def _windows_wwns():
ps_cmd = r'Get-WmiObject -ErrorAction Stop ' \
r'-class MSFC_FibrePortHBAAttributes ' \
r'-namespace "root\WMI" | ' \
r'Select -Expandproperty Attributes | ' \
r'%{($_.PortWWN | % {"{0:x2}" -f $_}) -join ""}'
ret = []
cmd_ret = salt.mo... | Return Fibre Channel port WWNs from a Windows host. |
def char_pad_trunc(data, maxlen):
new_dataset = []
for sample in data:
if len(sample) > maxlen:
new_data = sample[:maxlen]
elif len(sample) < maxlen:
pads = maxlen - len(sample)
new_data = sample + ['PAD'] * pads
else:
new_data = sample
... | We truncate to maxlen or add in PAD tokens |
def map_permissions_check(view_func):
@wraps(view_func)
def wrapper(request, *args, **kwargs):
map_inst = get_object_or_404(Map, pk=kwargs['map_id'])
user = request.user
kwargs['map_inst'] = map_inst
if map_inst.edit_status >= map_inst.EDITORS:
can_edit = map_inst.can... | Used for URLs dealing with the map. |
def globals(self):
try:
return vars(__import__(self.module, fromlist=self.module.split('.')))
except ImportError:
if self.warn_import:
warnings.warn(ImportWarning(
'Cannot import module {} for SerializableFunction. Restricting to builtins.'.for... | Find the globals of `self` by importing `self.module` |
def cleanup():
for sck in list(Wdb._sockets):
try:
sck.close()
except Exception:
log.warn('Error in cleanup', exc_info=True) | Close all sockets at exit |
def resolve_node_modules(self):
'import the modules specified in init'
if not self.resolved_node_modules:
try:
self.resolved_node_modules = [
importlib.import_module(mod, self.node_package)
for mod in self.node_modules
]... | import the modules specified in init |
def retrieve_customer(self, handle, with_additional_data=False):
response = self.request(E.retrieveCustomerRequest(
E.handle(handle),
E.withAdditionalData(int(with_additional_data)),
))
return response.as_model(Customer) | Retrieve information of an existing customer. |
def enableGroup(self):
radioButtonListInGroup = PygWidgetsRadioButton.__PygWidgets__Radio__Buttons__Groups__Dicts__[self.group]
for radioButton in radioButtonListInGroup:
radioButton.enable() | Enables all radio buttons in the group. |
def build_source_files(self):
from .files import BuildSourceFileAccessor
return BuildSourceFileAccessor(self, self.dataset, self.source_fs) | Return acessors to the build files |
def _get_snapshot(name, suffix, array):
snapshot = name + '.' + suffix
try:
for snap in array.get_volume(name, snap=True):
if snap['name'] == snapshot:
return snapshot
except purestorage.PureError:
return None | Private function to check snapshot |
def getParameterByType(self, type):
result = None
for parameter in self.getParameters():
typeParam = parameter.getType()
if typeParam == type:
result = parameter
break
return result | Searchs a parameter by type and returns it. |
def read_blob(arg):
result = None
if arg == '@-':
result = sys.stdin.read()
elif any(arg.startswith('@{}://'.format(x)) for x in {'http', 'https', 'ftp', 'file'}):
if not requests:
raise error.UserError("You must 'pip install requests' to support @URL arguments.")
try:
... | Read a BLOB from given ``@arg``. |
def add_node(self, node):
num_agents = len(self.nodes(type=Agent))
curr_generation = int((num_agents - 1) / float(self.generation_size))
node.generation = curr_generation
if curr_generation == 0 and self.initial_source:
parent = self._select_oldest_source()
else:
... | Link to the agent from a parent based on the parent's fitness |
def create(self, model_obj):
model_obj = self._set_auto_fields(model_obj)
identifier = model_obj[self.entity_cls.meta_.id_field.field_name]
with self.conn['lock']:
self.conn['data'][self.schema_name][identifier] = model_obj
return model_obj | Write a record to the dict repository |
def _unpack_int_base128(varint, offset):
res = ord(varint[offset])
if ord(varint[offset]) >= 0x80:
offset += 1
res = ((res - 0x80) << 7) + ord(varint[offset])
if ord(varint[offset]) >= 0x80:
offset += 1
res = ((res - 0x80) << 7) + ord(v... | Implement Perl unpack's 'w' option, aka base 128 decoding. |
def explained_variance(pred:Tensor, targ:Tensor)->Rank0Tensor:
"Explained variance between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
var_pct = torch.var(targ - pred) / torch.var(targ)
return 1 - var_pct | Explained variance between `pred` and `targ`. |
def _bits_to_float(bits, lower=-90.0, middle=0.0, upper=90.0):
for i in bits:
if i:
lower = middle
else:
upper = middle
middle = (upper + lower) / 2
return middle | Convert GeoHash bits to a float. |
def _get_interpretation_description_and_output_type(interpretation, dtype):
type_string = dtype.__name__
name = "%s__%s" % (interpretation, type_string)
if not hasattr(_interpretations_class, name):
raise ValueError("No transform available for type '%s' with interpretation '%s'."
... | Returns the description and output type for a given interpretation. |
def closeEvent(self, event):
self.visibilityChanged.emit(0)
model = self.paramList.model()
model.hintRequested.disconnect()
model.rowsInserted.disconnect()
model.rowsRemoved.disconnect() | Emits a signal to update start values on components |
def close(self):
self.cancel()
self.logger.debug("Closing AMQP connection")
try:
self.connection.close()
except Exception, eee:
self.logger.warning("Received an error while trying to close AMQP connection: " + str(eee)) | Closes the internal connection. |
def polyline(document, coords):
"polyline with more then 2 vertices"
points = []
for i in range(0, len(coords), 2):
points.append("%s,%s" % (coords[i], coords[i+1]))
return setattribs(
document.createElement('polyline'),
points = ' '.join(points),
) | polyline with more then 2 vertices |
async def rename(self, name):
set_node_name = SetNodeName(pyvlx=self.pyvlx, node_id=self.node_id, name=name)
await set_node_name.do_api_call()
if not set_node_name.success:
raise PyVLXException("Unable to rename node")
self.name = name | Change name of node. |
def popen(command, tempFile):
fileHandle = open(tempFile, 'w')
logger.debug("Running the command: %s" % command)
sts = subprocess.call(command, shell=True, stdout=fileHandle, bufsize=-1)
fileHandle.close()
if sts != 0:
raise RuntimeError("Command: %s exited with non-zero status %i" % (comman... | Runs a command and captures standard out in the given temp file. |
def bug_suggestions(self, request, project, pk=None):
try:
job = Job.objects.get(repository__name=project, id=pk)
except ObjectDoesNotExist:
return Response("No job with id: {0}".format(pk), status=HTTP_404_NOT_FOUND)
return Response(get_error_summary(job)) | Gets a set of bug suggestions for this job |
def add(self, doc):
array = doc.to_array(self.attrs)
if len(array.shape) == 1:
array = array.reshape((array.shape[0], 1))
self.tokens.append(array)
spaces = doc.to_array(SPACY)
assert array.shape[0] == spaces.shape[0]
spaces = spaces.reshape((spaces.shape[0], ... | Add a doc's annotations to the binder for serialization. |
def _get_base_dataframe(df):
if isinstance(df, GroupedDataFrame):
base_df = GroupedDataFrame(
df.loc[:, df.plydata_groups], df.plydata_groups,
copy=True)
else:
base_df = pd.DataFrame(index=df.index)
return base_df | Remove all columns other than those grouped on |
def observer_update(self, message):
for action in ('added', 'changed', 'removed'):
for item in message[action]:
self.send_json(
{
'msg': action,
'observer': message['observer'],
'primary_key':... | Called when update from observer is received. |
def handle_parse_result(self, ctx, opts, args):
if 'sclize' in opts and not SclConvertor:
raise click.UsageError("Please install spec2scl package to "
"perform SCL-style conversion")
if self.name in opts and 'sclize' not in opts:
raise click.Usa... | Validate SCL related options before parsing. |
def create_instance(self, nova, image_name, instance_name, flavor):
self.log.debug('Creating instance '
'({}|{}|{})'.format(instance_name, image_name, flavor))
image = nova.glance.find_image(image_name)
flavor = nova.flavors.find(name=flavor)
instance = nova.server... | Create the specified instance. |
def setDefaultColorRamp(self, colorRampEnum=ColorRampEnum.COLOR_RAMP_HUE):
self._colorRamp = ColorRampGenerator.generateDefaultColorRamp(colorRampEnum) | Returns the color ramp as a list of RGB tuples |
def terminate(self):
for t in self._threads:
t.quit()
self._thread = []
self._workers = [] | Terminate all workers and threads. |
def newDocProp(self, name, value):
ret = libxml2mod.xmlNewDocProp(self._o, name, value)
if ret is None:raise treeError('xmlNewDocProp() failed')
__tmp = xmlAttr(_obj=ret)
return __tmp | Create a new property carried by a document. |
def extract_translations(self, string):
trans = []
for t in Lexer(string.decode("utf-8"), None).tokenize():
if t.token_type == TOKEN_BLOCK:
if not t.contents.startswith(
(self.tranz_tag, self.tranzchoice_tag)):
continue
... | Extract messages from Django template string. |
def render_binary(self, context, result):
context.response.app_iter = iter((result, ))
return True | Return binary responses unmodified. |
def url_dirname(url):
p = six.moves.urllib.parse.urlparse(url)
for e in [private.FILE_EXT_JSON, private.FILE_EXT_YAML]:
if p.path.endswith(e):
return six.moves.urllib.parse.urlunparse(
p[:2]+
(os.path.dirname(p.path),)+
p[3:]
)
... | Return the folder containing the '.json' file |
def _validate(self, writing=False):
if self.brand not in ['jp2 ', 'jpx ']:
msg = ("The file type brand was '{brand}'. "
"It should be either 'jp2 ' or 'jpx '.")
msg = msg.format(brand=self.brand)
if writing:
raise IOError(msg)
e... | Validate the box before writing to file. |
def _combined_services(cls):
combined = {}
for parent in reversed(cls.mro()):
combined.update(getattr(parent, "_services_requested", {}))
return combined | A dictionary that collects all _services_requested by all ancestors of this XBlock class. |
def fetchcolumnar(self):
self._wait_to_finish()
if not self._last_operation.is_columnar:
raise NotSupportedError("Server does not support columnar "
"fetching")
batches = []
while True:
batch = (self._last_operation.fetch(
... | Executes a fetchall operation returning a list of CBatches |
def remove_all_locks(self):
locks = list(self._locks.items())
locks.sort(key=lambda l: l[1].get_last_access())
for l in locks:
self._remove_lock(l[0]) | Removes all locks and ensures their content is written to disk. |
def collect_modules(self):
try:
res = {}
m = sys.modules
for k in m:
if ('.' in k) or k[0] == '_':
continue
if m[k]:
try:
d = m[k].__dict__
if "version" in ... | Collect up the list of modules in use |
def OnSafeModeExit(self, event):
self.main_window.main_menu.enable_file_approve(False)
self.main_window.grid.Refresh()
event.Skip() | Safe mode exit event handler |
def profile_rule(self, rule):
rule_str = self.reduce_string(rule)
if rule_str not in self.profile_info:
self.profile_info[rule_str] = 1
else:
self.profile_info[rule_str] += 1 | Bump count of the number of times _rule_ was used |
def search_overlap(self, point_list):
result = set()
for j in point_list:
self.search_point(j, result)
return result | Returns all intervals that overlap the point_list. |
def _get_exclusive_error_codes(cls, options):
codes = set(ErrorRegistry.get_error_codes())
checked_codes = None
if options.ignore is not None:
ignored = cls._expand_error_codes(options.ignore)
checked_codes = codes - ignored
elif options.select is not None:
... | Extract the error codes from the selected exclusive option. |
def contextMenuEvent(self, event):
menu = QtWidgets.QMenu(self)
for action in self.actions():
menu.addAction(action)
openAsMenu = self.createOpenAsMenu(parent=menu)
menu.insertMenu(self.closeItemAction, openAsMenu)
menu.exec_(event.globalPos()) | Creates and executes the context menu for the tree view |
def forward(self, method, type, path, data=None):
try:
action = "/{}/{}".format(type, path)
res = yield from self.http_query(method, action, data=data, timeout=None)
except aiohttp.ServerDisconnectedError:
log.error("Connection lost to %s during %s %s", self._id, meth... | Forward a call to the emulator on compute |
def unpack(destdir):
if not nav:
sys.exit(1)
ecode = 0
try:
anchore_print("Unpacking images: " + ' '.join(nav.get_images()))
result = nav.unpack(destdir=destdir)
if not result:
anchore_print_err("no images unpacked")
ecode = 1
else:
... | Unpack and Squash image to local filesystem |
def supported_operations(self):
return tuple(op for op in backend.FILE_OPS if self._operations & op) | All file operations supported by the camera. |
def _get_run_by_other_worker(worker):
task_sets = _get_external_workers(worker).values()
return functools.reduce(lambda a, b: a | b, task_sets, set()) | This returns a set of the tasks that are being run by other worker |
def create_page_from_template(template_file, output_path):
mkdir_p(os.path.dirname(output_path))
shutil.copy(os.path.join(livvkit.resource_dir, template_file), output_path) | Copy the correct html template file to the output directory |
def getElementById(id: str) -> Optional[Node]:
elm = Element._elements_with_id.get(id)
return elm | Get element with ``id``. |
def pk_names(cls):
if cls._cache_pk_names is None:
cls._cache_pk_names = cls._get_primary_key_names()
return cls._cache_pk_names | Primary key column name list. |
def insertReferenceSet(self, referenceSet):
try:
models.Referenceset.create(
id=referenceSet.getId(),
name=referenceSet.getLocalId(),
description=referenceSet.getDescription(),
assemblyid=referenceSet.getAssemblyId(),
is... | Inserts the specified referenceSet into this repository. |
def WriteBlobs(self, blob_id_data_map):
urns = {self._BlobUrn(blob_id): blob_id for blob_id in blob_id_data_map}
mutation_pool = data_store.DB.GetMutationPool()
existing = aff4.FACTORY.MultiOpen(
urns, aff4_type=aff4.AFF4MemoryStreamBase, mode="r")
for blob_urn, blob_id in iteritems(urns):
... | Creates or overwrites blobs. |
def __convert_node(node, default_value='', default_flags=vsflags()):
name = __get_attribute(node, 'Name')
logging.debug('Found %s named %s', node.tagName, name)
converted = {}
converted['name'] = name
converted['switch'] = __get_attribute(node, 'Switch')
converted['comment'] = __get_attribute(no... | Converts a XML node to a JSON equivalent. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.