code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def ids_sharing_same_pgn(id_x, pgn_x, id_y, pgn_y):
for id_a, pgn_a in zip(id_x, pgn_x):
for id_b, pgn_b in zip(id_y, pgn_y):
if pgn_a == pgn_b:
yield (id_a, id_b) | module function_definition identifier parameters identifier identifier identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier identifier block if_stat... | Yield arbitration ids which has the same pgn. |
def collect(self, name, arr):
name = py_str(name)
if self.include_layer is not None and not self.include_layer(name):
return
handle = ctypes.cast(arr, NDArrayHandle)
arr = NDArray(handle, writable=False)
min_range = ndarray.min(arr).asscalar()
max_range = ndar... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement boolean_operator comparison_operator attribute identifier identifier none not_operator call attribute identifier identifier argument_li... | Callback function for collecting min and max values from an NDArray. |
def make_env_key(app_name, key):
key = key.replace('-', '_').replace(' ', '_')
return str("_".join((x.upper() for x in (app_name, key)))) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier argument_list string string_sta... | Creates an environment key-equivalent for the given key |
def handle(self, handler_name, request, suffix=''):
return self.runtime.handle(self, handler_name, request, suffix) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier string string_start string_end block return_statement call attribute attribute identifier identifier identifier argument_list identifier identifier identifier identifier | Handle `request` with this block's runtime. |
def volume_info(self, vol=None, type_filter=None):
'Get list of all volumes or info for the one specified.'
vols = yield self(join('volumes', vol))
if not isinstance(vols, list): vols = [vols]
if type_filter is not None:
vols = list(vol for vol in vols if vol['type'] == type_filter)
if vol is not None: def... | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block expression_statement string string_start string_content string_end expression_statement assignment identifier yield call identifier argument_list call identifier argument_list string str... | Get list of all volumes or info for the one specified. |
def handle_resourcelist(ltext, **kwargs):
base=kwargs.get('base', VERSA_BASEIRI)
model=kwargs.get('model')
iris = ltext.strip().split()
newlist = model.generate_resource()
for i in iris:
model.add(newlist, VERSA_BASEIRI + 'item', I(iri.absolutize(i, base)))
return newlist | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifie... | A helper that converts lists of resources from a textual format such as Markdown, including absolutizing relative IRIs |
def addReadGroupSet(self, readGroupSet):
id_ = readGroupSet.getId()
self._readGroupSetIdMap[id_] = readGroupSet
self._readGroupSetNameMap[readGroupSet.getLocalId()] = readGroupSet
self._readGroupSetIds.append(id_) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript attribute identifier identifier identifier identifier expression_statement assignment subscript attribute i... | Adds the specified readGroupSet to this dataset. |
def expand_paths(inputs):
seen = {}
for dirname in inputs:
dirname = normalize_path(dirname)
if dirname in seen:
continue
seen[dirname] = 1
if not os.path.isdir(dirname):
continue
files = os.listdir(dirname)
yield dirname, files
for... | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier identifier block continue_stat... | Yield sys.path directories that might contain "old-style" packages |
def _setfile(self, filename, length, offset):
source = open(filename, 'rb')
if offset is None:
offset = 0
if length is None:
length = os.path.getsize(source.name) * 8 - offset
byteoffset, offset = divmod(offset, 8)
bytelength = (length + byteoffset * 8 + o... | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment iden... | Use file as source of bits. |
def convert_to_sqlite(self, destination=None, method="shell", progress=False):
if progress: progress = tqdm.tqdm
else: progress = lambda x:x
if destination is None: destination = self.replace_extension('sqlite')
destination.remove()
if method == 'shell': return self.sq... | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier string string_start string_content string_end default_parameter identifier false block if_statement identifier block expression_statement assignment identifier attribute identifier identifier else_... | Who wants to use Access when you can deal with SQLite databases instead? |
def put_intent(self, intent_id, intent_json):
endpoint = self._intent_uri(intent_id)
return self._put(endpoint, intent_json) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier identifier | Send a put request to update the intent with intent_id |
def shorten_aead(aead):
head = aead.data[:4].encode('hex')
tail = aead.data[-4:].encode('hex')
return "%s...%s" % (head, tail) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute subscript attribute identifier identifier slice integer identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute subscript a... | Produce pretty-printable version of long AEAD. |
def main():
parser = argparse.ArgumentParser(description='%(prog)s add/remove Windows loopback adapters')
parser.add_argument('-a', "--add", nargs=3, action=parse_add_loopback(), help="add a Windows loopback adapter")
parser.add_argument("-r", "--remove", action="store", help="remove a Windows loopback adap... | module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start strin... | Entry point for the Windows loopback tool. |
def remove_all_static_host_mappings():
LOG.debug("remove_host_mapping() called")
session = bc.get_writer_session()
try:
mapping = _lookup_all_host_mappings(
session=session,
is_static=True)
for host in mapping:
session.delete(host)
... | module function_definition identifier parameters block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block expression_statement assignment i... | Remove all entries defined in config file from mapping data base. |
def _create_out_partition(self, tenant_id, tenant_name):
vrf_prof_str = self.serv_part_vrf_prof
self.dcnm_obj.create_partition(tenant_name, fw_const.SERV_PART_NAME,
None, vrf_prof_str,
desc="Service Partition") | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier none identifier keywo... | Function to create a service partition. |
def _make_chunk_size(self, req_size):
size = req_size
size += 2 * self._chunk_size_t_size
size = self._chunk_min_size if size < self._chunk_min_size else size
if size & self._chunk_align_mask:
size = (size & ~self._chunk_align_mask) + self._chunk_align_mask + 1
return... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier identifier expression_statement augmented_assignment identifier binary_operator integer attribute identifier identifier expression_statement assignment identifier conditional_expression attribute iden... | Takes an allocation size as requested by the user and modifies it to be a suitable chunk size. |
def parse_user(raw):
nick = raw
user = None
host = None
if protocol.HOST_SEPARATOR in raw:
raw, host = raw.split(protocol.HOST_SEPARATOR)
if protocol.USER_SEPARATOR in raw:
nick, user = raw.split(protocol.USER_SEPARATOR)
return nick, user, host | module function_definition identifier parameters identifier block expression_statement assignment identifier identifier expression_statement assignment identifier none expression_statement assignment identifier none if_statement comparison_operator attribute identifier identifier identifier block expression_statement a... | Parse nick(!user(@host)?)? structure. |
def apply_request_and_page_to_values(self, request, page=None):
value_is_set = False
for value in self._values:
value.apply_request_and_page(request, page) | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier false for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier | Use the request and page config to figure out which values are active |
def auto_register_search_models():
for config in models_config.get_all_configs():
if config.disable_search_index:
continue
search.register(
config.model.objects.get_queryset(),
ModelSearchAdapter,
fields=config.search_fields,
exclude=config... | module function_definition identifier parameters block for_statement identifier call attribute identifier identifier argument_list block if_statement attribute identifier identifier block continue_statement expression_statement call attribute identifier identifier argument_list call attribute attribute attribute identi... | Auto register all search models |
def cmd_average_waiting_time(self):
average = [
line.time_wait_queues
for line in self._valid_lines
if line.time_wait_queues >= 0
]
divisor = float(len(average))
if divisor > 0:
return sum(average) / float(len(average))
return 0 | module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension attribute identifier identifier for_in_clause identifier attribute identifier identifier if_clause comparison_operator attribute identifier identifier integer expression_statement assignment i... | Returns the average queue time of all, non aborted, requests. |
def stop(self):
self.running = False
try:
self.commands_thread.kill()
except:
pass
try:
self.lock.set()
if self.config["debug"]:
self.log("lock set, exiting")
for module in self.modules.values():
... | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier false try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list except_clause block pass_statement try_statement block expression_state... | Set the Event lock, this will break all threads' loops. |
def print_async_event(self, suffix, event):
if not isinstance(event, dict):
return
if self.opts.get('quiet', False):
return
if suffix in ('new',):
return
try:
outputter = self.opts.get('output', event.get('outputter', None) or event.get('re... | module function_definition identifier parameters identifier identifier identifier block if_statement not_operator call identifier argument_list identifier identifier block return_statement if_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end ... | Print all of the events with the prefix 'tag' |
def install_rpm_py():
python_path = sys.executable
cmd = '{0} install.py'.format(python_path)
exit_status = os.system(cmd)
if exit_status != 0:
raise Exception('Command failed: {0}'.format(cmd)) | module function_definition identifier parameters block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call at... | Install RPM Python binding. |
def cv_gradient(self,z):
gradient = np.zeros(np.sum(self.approx_param_no))
z_t = z.T
log_q = self.normal_log_q(z.T)
log_p = self.log_p(z.T)
grad_log_q = self.grad_log_q(z)
gradient = grad_log_q*(log_p-log_q)
alpha0 = alpha_recursion(np.zeros(np.sum(self.appr... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier attribute identifier id... | The control variate augmented Monte Carlo gradient estimate |
def decode(buff):
pp = list(map(ord, buff))
if 0 == len(pp) == 1:
pp = []
return pp | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier identifier if_statement comparison_operator integer call identifier argument_list identifier integer block expression_statement assignment i... | Transforms the raw buffer data read in into a list of bytes |
def attach(self):
s = self._sensor
self.update(s, s.read())
self._sensor.attach(self) | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list expression_statement call attribute attribute... | Attach strategy to its sensor and send initial update. |
def find_near(lat, lon, *, n=10, session=None):
search_params = {'npoints': n, 'clat': lat, 'clon': lon,
'Columns[]': ['Subregion', 'Notes', 'CollectionYear',
'ReservoirAge', 'ReservoirErr', 'C14age',
'C14err', 'LabID', 'D... | module function_definition identifier parameters identifier identifier keyword_separator default_parameter identifier integer default_parameter identifier none block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_conten... | Return n results for a given latitude and longitude |
def _getitem_with_mask(self, key, fill_value=dtypes.NA):
if fill_value is dtypes.NA:
fill_value = dtypes.get_fill_value(self.dtype)
dims, indexer, new_order = self._broadcast_indexes(key)
if self.size:
if isinstance(self._data, dask_array_type):
actual_ind... | module function_definition identifier parameters identifier identifier default_parameter identifier attribute identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attrib... | Index this Variable with -1 remapped to fill_value. |
def remove_gateway_router(self, router):
router_id = self._find_router_id(router)
return self.network_conn.remove_gateway_router(router=router_id) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier | Removes an external network gateway from the specified router |
def check_autosign_dir(self, keyid):
autosign_dir = os.path.join(self.opts['pki_dir'], 'minions_autosign')
expire_minutes = self.opts.get('autosign_timeout', 120)
if expire_minutes > 0:
min_time = time.time() - (60 * int(expire_minutes))
for root, dirs, filenames in salt.... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end string string_start string_content strin... | Check a keyid for membership in a autosign directory. |
def add_sensor(self, sensorid=None):
if sensorid is None:
sensorid = self._get_next_id()
if sensorid is not None and sensorid not in self.sensors:
self.sensors[sensorid] = Sensor(sensorid)
return sensorid if sensorid in self.sensors else None | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator comparison_operator identifier none compa... | Add a sensor to the gateway. |
def _get_table_start(self):
if self.documentation:
standardized_table_start = {
'object_id': {
'value': self.object_id,
'ordering': -1,
'line_number': 'NA',
'description': 'IRS-assigned object id',
... | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end dictionary pair string string_start string_content string_end attribute identifier identifier pair... | prefill the columns we need for all tables |
def create_interface(self):
return Interface(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | module function_definition identifier parameters identifier block return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier | Get an instance of interface services facade. |
def _ensure_array(self, key, value):
if key not in self._json_dict:
self._json_dict[key] = []
self._size += 2
self._ensure_field(key)
if len(self._json_dict[key]) > 0:
self._size += 2
if isinstance(value, str):
self._size += 2
s... | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier list expression_statement augmented_assignment attribute identifi... | Ensure an array field |
def _generate_feed(self, feed_data):
atom_feed = self._render_html('atom.xml', feed_data)
feed_path = os.path.join(os.getcwd(), 'public', 'atom.xml')
with codecs.open(feed_path, 'wb', 'utf-8') as f:
f.write(atom_feed) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier id... | render feed file with data |
def prep_value(self, value):
if value in MULTI_EMAIL_FIELD_EMPTY_VALUES:
return ""
elif isinstance(value, six.string_types):
return value
elif isinstance(value, list):
return "\n".join(value)
raise ValidationError('Invalid format.') | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier identifier block return_statement string string_start string_end elif_clause call identifier argument_list identifier attribute identifier identifier block return_statement identifier elif_clause cal... | Prepare value before effectively render widget |
def create_arj (archive, compression, cmd, verbosity, interactive, filenames):
cmdlist = [cmd, 'a', '-r']
if not interactive:
cmdlist.append('-y')
cmdlist.append(archive)
cmdlist.extend(filenames)
return cmdlist | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier list identifier string string_start string_content string_end string string_start string_content string_end if_statement not_operator identifier block expre... | Create an ARJ archive. |
def add_distdiff_optgroup(parser):
cpus = cpu_count()
og = parser.add_argument_group("Distribution Checking Options")
og.add_argument("--processes", type=int, default=cpus,
help="Number of child processes to spawn to handle"
" sub-reports. Set to 0 to disable multi-pr... | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute ident... | Option group relating to the use of a DistChange or DistReport |
def remove(self, dist):
while dist.location in self.paths:
self.paths.remove(dist.location)
self.dirty = True
Environment.remove(self, dist) | module function_definition identifier parameters identifier identifier block while_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_s... | Remove `dist` from the distribution map |
def handle_namespace_default(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
name = tokens[NAME]
self.raise_for_missing_default(line, position, name)
return tokens | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block expression_statement assignment identifier subscript identifier identifier expression_statement call attribut... | Handle parsing an identifier for the default namespace. |
def body_block_attribution(tag):
"extract the attribution content for figures, tables, videos"
attributions = []
if raw_parser.attrib(tag):
for attrib_tag in raw_parser.attrib(tag):
attributions.append(node_contents_str(attrib_tag))
if raw_parser.permissions(tag):
for permiss... | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier list if_statement call attribute identifier identifier argument_list identifier block for_statement identifier call attribute identifier identif... | extract the attribution content for figures, tables, videos |
def render_markdown(text, context=None):
if context is None or not isinstance(context, dict):
context = {}
markdown_html = _transform_markdown_into_html(text)
sanitised_markdown_html = _sanitise_markdown_html(markdown_html)
return mark_safe(sanitised_markdown_html) | module function_definition identifier parameters identifier default_parameter identifier none block if_statement boolean_operator comparison_operator identifier none not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier dictionary expression_statement assignme... | Turn markdown into HTML. |
def _set_init_params(self, qrs_amp_recent, noise_amp_recent, rr_recent,
last_qrs_ind):
self.qrs_amp_recent = qrs_amp_recent
self.noise_amp_recent = noise_amp_recent
self.qrs_thr = max(0.25*self.qrs_amp_recent
+ 0.75*self.noise_amp_recent,
... | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identif... | Set initial online parameters |
def status(self):
if all(os.path.exists(p.path) for p in self.parts): return 'splitted'
return False | module function_definition identifier parameters identifier block if_statement call identifier generator_expression call attribute attribute identifier identifier identifier argument_list attribute identifier identifier for_in_clause identifier attribute identifier identifier block return_statement string string_start ... | Has the splitting been done already ? |
def _gps_scale_factory(unit):
class FixedGPSScale(GPSScale):
name = str('{0}s'.format(unit.long_names[0] if unit.long_names else
unit.names[0]))
def __init__(self, axis, epoch=None):
super(FixedGPSScale, self).__init__(axis, epoch=epoch, unit=unit)
re... | module function_definition identifier parameters identifier block class_definition identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list call attribute string string_start string_content string_end identifier argument_list conditional_expression subscript att... | Construct a GPSScale for this unit |
def _labels_inertia(X, centers):
n_examples, n_features = X.shape
n_clusters, n_features = centers.shape
labels = np.zeros((n_examples,))
inertia = np.zeros((n_examples,))
for ee in range(n_examples):
dists = np.zeros((n_clusters,))
for cc in range(n_clusters):
dists[cc] ... | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier attribute identifier identifier expression_statement assignment identifier ca... | Compute labels and inertia with cosine distance. |
def ApprovalFind(object_id, token=None):
user = getpass.getuser()
object_id = rdfvalue.RDFURN(object_id)
try:
approved_token = security.Approval.GetApprovalForObject(
object_id, token=token, username=user)
print("Found token %s" % str(approved_token))
return approved_token
except access_cont... | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier try_statement block e... | Find approvals issued for a specific client. |
def fullname(self):
prefix = ""
if self.parent:
if self.parent.fullname:
prefix = self.parent.fullname + ":"
else:
return ""
return prefix + self.name | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_end if_statement attribute identifier identifier block if_statement attribute attribute identifier identifier identifier block expression_statement assignment identifier binary_operato... | includes the full path with parent names |
def verify_socket(interface, pub_port, ret_port):
addr_family = lookup_family(interface)
for port in pub_port, ret_port:
sock = socket.socket(addr_family, socket.SOCK_STREAM)
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((interface, int(port)))... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier for_statement identifier expression_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier... | Attempt to bind to the sockets to verify that they are available |
def from_response(cls, header_data, ignore_bad_cookies=False,
ignore_bad_attributes=True):
"Construct a Cookies object from response header data."
cookies = cls()
cookies.parse_response(
header_data,
ignore_bad_cookies=ignore_bad_cookies,
... | module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier true block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list expression_statement call attribut... | Construct a Cookies object from response header data. |
def union_overlapping(intervals):
disjoint_intervals = []
for interval in intervals:
if disjoint_intervals and disjoint_intervals[-1].overlaps(interval):
disjoint_intervals[-1] = disjoint_intervals[-1].union(interval)
else:
disjoint_intervals.append(interval)
return d... | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier identifier block if_statement boolean_operator identifier call attribute subscript identifier unary_operator integer identifier argument_list identifier block expression_statement a... | Union any overlapping intervals in the given set. |
def evaluate_list(molecules, ensemble_lookup, options):
stats = {}
if options.write_roc:
print(" Determining virtual screening performance and writing ROC data ... ")
print('')
else:
print(" Determining virtual screening performance ...")
print('')
for filename in sorted(... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier dictionary if_statement attribute identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call iden... | Evaluate a list of ensembles and return statistics and ROC plots if appropriate |
def on_ignored(self, metadata=None):
handler = self.handlers.get("on_ignored")
if callable(handler):
handler(metadata)
handler = self.handlers.get("on_summary")
if callable(handler):
handler() | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement call identifier argument_list identifier block... | Called when an IGNORED message has been received. |
def wait_to_start(self, allow_failure=False):
self._started.wait()
if self._crashed and not allow_failure:
self._thread.join()
raise RuntimeError('Setup failed, see {} Traceback'
'for details.'.format(self._thread.name)) | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement call attribute attribute identifier identifier identifier argument_list if_statement boolean_operator attribute identifier identifier not_operator identifier block expression_statement call attribut... | Wait for the thread to actually starts. |
def _set_bounds(self, bounds):
min_value, max_value = bounds
self.min_value = None
self.max_value = None
self.min_value = min_value
self.max_value = max_value | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier identifier expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none expression_statement assign... | Sets the boundaries for this parameter to min_value and max_value |
def create_osd_keyring(conn, cluster, key):
logger = conn.logger
path = '/var/lib/ceph/bootstrap-osd/{cluster}.keyring'.format(
cluster=cluster,
)
if not conn.remote_module.path_exists(path):
logger.warning('osd keyring does not exist yet, creating one')
conn.remote_module.write_... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier ... | Run on osd node, writes the bootstrap key if not there yet. |
def shannon(self, data):
entropy = 0
if data:
length = len(data)
seen = dict(((chr(x), 0) for x in range(0, 256)))
for byte in data:
seen[byte] += 1
for x in range(0, 256):
p_x = float(seen[chr(x)]) / length
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier integer if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list gener... | Performs a Shannon entropy analysis on a given block of data. |
def run_commands(self):
more = 0
prompt = sys.ps1
for command in self.commands:
try:
prompt = sys.ps2 if more else sys.ps1
try:
magictype(command, prompt_template=prompt, speed=self.speed)
except EOFError:
... | module function_definition identifier parameters identifier block expression_statement assignment identifier integer expression_statement assignment identifier attribute identifier identifier for_statement identifier attribute identifier identifier block try_statement block expression_statement assignment identifier co... | Automatically type and execute all commands. |
def locate(command, on):
location = find_page_location(command, on)
click.echo(location) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Locate the command's man page. |
def _restore(name, fields, value):
k = (name, fields)
cls = __cls.get(k)
if cls is None:
cls = collections.namedtuple(name, fields)
__cls[k] = cls
return cls(*value) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier tuple identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block e... | Restore an object of namedtuple |
def reset(self, hard=False):
if hard:
self.sendcommand(Vendapin.RESET, 1, 0x01)
time.sleep(2)
else:
self.sendcommand(Vendapin.RESET)
time.sleep(2)
response = self.receivepacket()
print('Vendapin.reset(soft): ' + str(response)) | module function_definition identifier parameters identifier default_parameter identifier false block if_statement identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier integer integer expression_statement call attribute identifier identifier argument_li... | reset the card dispense, either soft or hard based on boolean 2nd arg |
def master_key_required(func):
def ret(obj, *args, **kw):
conn = ACCESS_KEYS
if not (conn and conn.get('master_key')):
message = '%s requires the master key' % func.__name__
raise core.ParseError(message)
func(obj, *args, **kw)
return ret | module function_definition identifier parameters identifier block function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier identifier if_statement not_operator parenthesized_expression boolean_operator identif... | decorator describing methods that require the master key |
def _cache_init(self):
cache_ = cache.get(self.CACHE_ENTRY_NAME)
if cache_ is None:
categories = get_category_model().objects.order_by('sort_order')
ids = {category.id: category for category in categories}
aliases = {category.alias: category for category in categories... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute attribute call ... | Initializes local cache from Django cache if required. |
def assemble_cyjs():
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
stmts_json = body.get('statements')
stmts = stmts_from_json(stmts_json)
cja = CyJSAssembler()
cja.add_statements(stmts)
cja.make_model(groupin... | module function_definition identifier parameters block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement dictionary expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argu... | Assemble INDRA Statements and return Cytoscape JS network. |
def toxml(self, encoding="UTF-8"):
domtree = self.todom()
xmlstr = domtree.toxml(encoding).replace(
'<?xml version="1.0" encoding="%s"?>' % encoding,
'<?xml version="1.0" encoding="%s" standalone="yes"?>' % encoding)
domtree.unlink()
return xmlstr | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute call attribute identifier i... | Return the manifest as XML |
def shard(items, num_shards):
sharded = []
num_per_shard = len(items) // num_shards
start = 0
for _ in range(num_shards):
sharded.append(items[start:start + num_per_shard])
start += num_per_shard
remainder = len(items) % num_shards
start = len(items) - remainder
for i in range(remainder):
shar... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list expression_statement assignment identifier binary_operator call identifier argument_list identifier identifier expression_statement assignment identifier integer for_statement identifier call ide... | Split items into num_shards groups. |
def timeout(self, duration=3600):
self.room.check_owner()
self.conn.make_call("timeoutFile", self.fid, duration) | module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_cont... | Timeout the uploader of this file |
def combine_and_copy(f, files, group):
f[group] = np.concatenate([fi[group][:] if group in fi else \
np.array([], dtype=np.uint32) for fi in files]) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list list_comprehension conditional_expression subscript subscript identifier identifier slice comparison_operator identif... | Combine the same column from multiple files and save to a third |
def funding_info2marc(self, key, value):
return {
'a': value.get('agency'),
'c': value.get('grant_number'),
'f': value.get('project_number'),
} | module function_definition identifier parameters identifier identifier identifier block return_statement dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end pair string string_start string_content string_end call ... | Populate the ``536`` MARC field. |
def update_from_stats(self, stats):
sd = dict(stats)
for c in self.columns:
if c not in sd:
continue
stat = sd[c]
if stat.size and stat.size > c.size:
c.size = stat.size
c.lom = stat.lom | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier for_statement identifier attribute identifier identifier block if_statement comparison_operator identifier identifier block continue_statement expression_state... | Update columns based on partition statistics |
def _run_chunk(self, chunk, kernel_options, device_options, tuning_options):
self.dev = DeviceInterface(kernel_options.kernel_string, iterations=tuning_options.iterations, **device_options)
gpu_args = self.dev.ready_argument_list(kernel_options.arguments)
results = []
for element in chun... | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier dictionary_splat identif... | Benchmark a single kernel instance in the parameter space |
def initialize_labels(self, labels: Set[str]) -> Tuple[dict, dict]:
logger.debug("Creating mappings for labels")
label_to_index = {label: index for index, label in enumerate(
["pad"] + sorted(list(labels)))}
index_to_label = {index: phn for index, phn in enumerat... | module function_definition identifier parameters identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type generic_type identifier type_parameter type identifier type identifier block expression_statement call attribute identifier identifier argument_list string string_start... | Create mappings from label to index and index to label |
def loadconfig(self, keysuffix, obj):
subtree = self.get(keysuffix)
if subtree is not None and isinstance(subtree, ConfigTree):
for k,v in subtree.items():
if isinstance(v, ConfigTree):
if hasattr(obj, k) and not isinstance(getattr(obj, k), ConfigTree):
... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement boolean_operator comparison_operator identifier none call identifier argument_list identifier identifier block for... | Copy all configurations from this node into obj |
def mail_message(smtp_server, message, from_address, rcpt_addresses):
if smtp_server[0] == '/':
p = os.popen(smtp_server, 'w')
p.write(message)
p.close()
else:
import smtplib
server = smtplib.SMTP(smtp_server)
server.sendmail(from_address, rcpt_addresses, message)... | module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator subscript identifier integer string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier st... | Send mail using smtp. |
def getBool(t):
b = c_int()
if PL_get_long(t, byref(b)):
return bool(b.value)
else:
raise InvalidTypeError("bool") | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list if_statement call identifier argument_list identifier call identifier argument_list identifier block return_statement call identifier argument_list attribute identifier identifier e... | If t is of type bool, return it, otherwise raise InvalidTypeError. |
def status_bar(self):
print("")
self.msg.template(78)
print("| Repository Status")
self.msg.template(78) | module function_definition identifier parameters identifier block expression_statement call identifier argument_list string string_start string_end expression_statement call attribute attribute identifier identifier identifier argument_list integer expression_statement call identifier argument_list string string_start ... | Top view bar status |
def resolve_str(name_or_func, module, default):
assert isinstance(name_or_func, str)
resolved = resolve(name_or_func, module=module)
if isinstance(resolved, ModuleType):
if not hasattr(resolved, default):
raise ImportError("{}.{}".format(resolved.__name__, default))
resolved = ge... | module function_definition identifier parameters identifier identifier identifier block assert_statement call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier if_statement call identifier argument_li... | Resolve and return object from dotted name |
def rlc(self, r):
if not is_number(self.regs[r]):
self.set(r, None)
self.set_flag(None)
return
v_ = self.getv(self.regs[r]) & 0xFF
self.set(r, ((v_ << 1) & 0xFF) | (v_ >> 7)) | module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list subscript attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier none expression_statement call attribute iden... | Does a ROTATION to the LEFT <<| |
def regenerate_prefixes(self, *args):
nick = self.controller.client.user.nick
self.prefixes = set([
nick + ": ",
nick + ", ",
nick + " - ",
])
self.prefixes.update([p.lower() for p in self.prefixes])
if self.sigil:
self.prefixes.add... | module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement assignment identifier attribute attribute attribute attribute identifier identifier identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argume... | Regenerate the cache of command prefixes based on nick etc. |
def time_description(self):
tc = [t for t in self._p.time_coverage if t]
if not tc:
return ''
mn = min(tc)
mx = max(tc)
if not mn and not mx:
return ''
elif mn == mx:
return mn
else:
return "{} to {}".format(mn, mx) | module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier attribute attribute identifier identifier identifier if_clause identifier if_statement not_operator identifier block return_statement string string_start st... | String description of the year or year range |
def collect(self):
for app_name, tools_path in get_apps_tools().items():
self.stdout.write("Copying files from '{}'.".format(tools_path))
app_name = app_name.replace('.', '_')
app_destination_path = os.path.join(self.destination_path, app_name)
if not os.path.isdi... | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call attribute call identifier argument_list identifier argument_list block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start s... | Get tools' locations and copy them to a single location. |
def getLowerDetectionLimit(self):
ldl = self.getField('LowerDetectionLimit').get(self)
try:
return float(ldl)
except ValueError:
return 0 | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list identifier try_statement block return_statement call identifier argument_l... | Returns the Lower Detection Limit for this service as a floatable |
def remove_token(self, token_stack, token):
token_stack.reverse()
try:
token_stack.remove(token)
retval = True
except ValueError:
retval = False
token_stack.reverse()
return retval | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list try_statement block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier true except_cl... | Remove last occurance of token from stack |
def identifier(self):
if self.background_identifier is None:
idsum = self._identifier_data()
else:
idsum = hash_obj([self._identifier_data(),
self.background_identifier])
return idsum | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list else_clause block expression_statement assignment identifier call identifier argumen... | Return a unique identifier for the given data set |
def delete(self, roleId):
role = db.Role.find_one(Role.role_id == roleId)
if not role:
return self.make_response('No such role found', HTTP.NOT_FOUND)
if role.name in ('User', 'Admin'):
return self.make_response('Cannot delete the built-in roles', HTTP.BAD_REQUEST)
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list comparison_operator attribute identifier identifier identifier if_statement not_operator identifier block return_statement call ... | Delete a user role |
def subscribe(self, receiver):
"Subscribes an external handler to this channel."
log.debug('{0}.{1} subscribe to {2}'
.format(receiver.__module__, receiver.__name__, self))
self.signal.connect(receiver) | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifi... | Subscribes an external handler to this channel. |
def parseresponse(self, resp):
if sys.version_info.major > 2:
resp = resp.decode('utf-8')
if self.RESPONSE_TOKEN not in resp:
raise BustimeError("The Bustime API returned an invalid response: {}".format(resp))
elif self.ERROR_TOKEN in resp:
return self.errorha... | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute attribute identifier identifier identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_... | Parse an API response. |
def normalize(self):
cm = self.centerOfMass()
coords = self.coordinates()
if not len(coords):
return
pts = coords - cm
xyz2 = np.sum(pts * pts, axis=0)
scale = 1 / np.sqrt(np.sum(xyz2) / len(pts))
t = vtk.vtkTransform()
t.Scale(scale, scale, sc... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator call identifier argument_list identifier... | Shift actor's center of mass at origin and scale its average size to unit. |
def tasks(self):
return [StartActionItem(
self._task,
i,
self.state,
self.path,
self.raw) for i in range(len(self.raw))] | module function_definition identifier parameters identifier block return_statement list_comprehension call identifier argument_list attribute identifier identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier for_in_clause identifier call identifier argument... | Return task objects of the task control. |
def _fetch_xml(self, url):
with contextlib.closing(urlopen(url)) as f:
return xml.etree.ElementTree.parse(f).getroot() | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list call identifier argument_list identifier as_pattern_target identifier block return_statement call attribute call attribute attribute attribute i... | Fetch a url and parse the document's XML. |
def addrs_for_name(self, n):
if n not in self._name_mapping:
return
self._mark_updated_mapping(self._name_mapping, n)
to_discard = set()
for e in self._name_mapping[n]:
try:
if n in self[e].object.variables: yield e
else: to_discard... | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block return_statement expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier expression_statement assignme... | Returns addresses that contain expressions that contain a variable named `n`. |
def to_latex(self):
latex = r"[{} "
for attribute, value in self:
if attribute in ['speaker_model', 'is_in_commonground']: continue
value_l = value.to_latex()
if value_l == "": continue
latex += "{attribute:<15} & {value:<20} \\\\ \n".format(attribute=at... | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end for_statement pattern_list identifier identifier identifier block if_statement comparison_operator identifier list string string_start string_content string_end stri... | Returns a LaTeX representation of an attribute-value matrix |
def allow(self, channel, message):
return all(
filter(channel, message)
for filter in _load_filters()
) | module function_definition identifier parameters identifier identifier identifier block return_statement call identifier generator_expression call identifier argument_list identifier identifier for_in_clause identifier call identifier argument_list | Allow plugins to filter content. |
def earth_orientation(date):
x_p, y_p, s_prime = np.deg2rad(_earth_orientation(date))
return rot3(-s_prime) @ rot2(x_p) @ rot1(y_p) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list call identifier argument_list identifier return_statement binary_operator binary_operator call identifier argument_list unary... | Earth orientation as a rotating matrix |
def connection(self):
return {'host': self.host, 'namespace': self.namespace, 'username': self.username, 'password': self.password} | module function_definition identifier parameters identifier block return_statement dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute... | A property to retrieve the sampler connection information. |
def _morph_rgb(self, rgb1, rgb2, step=1):
pos1, pos2 = list(rgb1), list(rgb2)
indexes = [i for i, _ in enumerate(pos1)]
def step_value(a, b):
if a < b:
return step
if a > b:
return -step
return 0
steps = [step_value(pos1... | module function_definition identifier parameters identifier identifier identifier default_parameter identifier integer block expression_statement assignment pattern_list identifier identifier expression_list call identifier argument_list identifier call identifier argument_list identifier expression_statement assignmen... | Morph an rgb value into another, yielding each step along the way. |
def validate_number_attribute(
fully_qualified_name: str,
spec: Dict[str, Any],
attribute: str,
value_type: Union[Type[int], Type[float]] = int,
minimum: Optional[Union[int, float]] = None,
maximum: Optional[Union[int, float]] = None) -> Optional[InvalidNumberError]:
... | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier typed_parameter identifier type identifier typed_default_parameter identifier type generic_type identifier type_parameter typ... | Validates to ensure that the value is a number of the specified type, and lies with the specified range |
def copy_binder_files(app, exception):
if exception is not None:
return
if app.builder.name not in ['html', 'readthedocs']:
return
gallery_conf = app.config.sphinx_gallery_conf
binder_conf = check_binder_conf(gallery_conf.get('binder'))
if not len(binder_conf) > 0:
return
... | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block return_statement if_statement comparison_operator attribute attribute identifier identifier identifier list string string_start string_content string_end string string_start string_content... | Copy all Binder requirements and notebooks files. |
def count_end(teststr, testchar):
count = 0
x = len(teststr) - 1
while x >= 0 and teststr[x] == testchar:
count += 1
x -= 1
return count | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier integer expression_statement assignment identifier binary_operator call identifier argument_list identifier integer while_statement boolean_operator comparison_operator identifier integer comparison_o... | Count instances of testchar at end of teststr. |
def compute_adjacency_matrix(X, method='auto', **kwargs):
if method == 'auto':
if X.shape[0] > 10000:
method = 'cyflann'
else:
method = 'kd_tree'
return Adjacency.init(method, **kwargs).adjacency_graph(X.astype('float')) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end dictionary_splat_pattern identifier block if_statement comparison_operator identifier string string_start string_content string_end block if_statement comparison_operator subscript attr... | Compute an adjacency matrix with the given method |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.