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_statement comparison_operator identifier identifier block expression_statement yield tuple identifier identifier | 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 = ndarray.max(arr).asscalar()
if name in self.min_max_dict:
cur_min_max = self.min_max_dict[name]
self.min_max_dict[name] = (min(cur_min_max[0], min_range),
max(cur_min_max[1], max_range))
else:
self.min_max_dict[name] = (min_range, max_range)
if self.logger is not None:
self.logger.info("Collecting layer %s min_range=%f, max_range=%f"
% (name, min_range, max_range)) | 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_list identifier block return_statement expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier false expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement assignment subscript attribute identifier identifier identifier tuple call identifier argument_list subscript identifier integer identifier call identifier argument_list subscript identifier integer identifier else_clause block expression_statement assignment subscript attribute identifier identifier identifier tuple identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier identifier | 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_start string_content string_end string string_start string_content string_end return_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list generator_expression call attribute identifier identifier argument_list for_in_clause identifier tuple identifier identifier | 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: defer.returnValue(vols[0] if vols else None)
defer.returnValue(vols) | 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 string_start string_content string_end identifier if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier generator_expression identifier for_in_clause identifier identifier if_clause comparison_operator subscript identifier string string_start string_content string_end identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list conditional_expression subscript identifier integer identifier none expression_statement call attribute identifier identifier argument_list identifier | 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 identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier binary_operator identifier string string_start string_content string_end call identifier argument_list call attribute identifier identifier argument_list identifier identifier return_statement identifier | 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 identifier identifier call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | 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 name in files:
if not name.endswith('.pth'):
continue
if name in ('easy-install.pth', 'setuptools.pth'):
continue
f = open(os.path.join(dirname, name))
lines = list(yield_lines(f))
f.close()
for line in lines:
if not line.startswith("import"):
line = normalize_path(line.rstrip())
if line not in seen:
seen[line] = 1
if not os.path.isdir(line):
continue
yield line, os.listdir(line) | 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_statement expression_statement assignment subscript identifier identifier integer if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block continue_statement expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement yield expression_list identifier identifier for_statement identifier identifier block if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block continue_statement if_statement comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end block continue_statement expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list for_statement identifier identifier block if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list if_statement comparison_operator identifier identifier block expression_statement assignment subscript identifier identifier integer if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block continue_statement expression_statement yield expression_list identifier call attribute identifier identifier argument_list identifier | 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 + offset + 7) // 8 - byteoffset
m = MmapByteArray(source, bytelength, byteoffset)
if length + byteoffset * 8 + offset > m.filelength * 8:
raise CreationError("File is not long enough for specified "
"length and offset.")
self._datastore = ConstByteStore(m, length, offset) | 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 identifier integer if_statement comparison_operator identifier none block expression_statement assignment identifier binary_operator binary_operator call attribute attribute identifier identifier identifier argument_list attribute identifier identifier integer identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier integer expression_statement assignment identifier binary_operator binary_operator parenthesized_expression binary_operator binary_operator binary_operator identifier binary_operator identifier integer identifier integer integer identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier if_statement comparison_operator binary_operator binary_operator identifier binary_operator identifier integer identifier binary_operator attribute identifier identifier integer block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute identifier identifier call identifier argument_list identifier identifier identifier | 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.sqlite_by_shell(destination)
if method == 'object': return self.sqlite_by_object(destination, progress)
if method == 'dataframe': return self.sqlite_by_df(destination, progress) | 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_clause block expression_statement assignment identifier lambda lambda_parameters identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list if_statement comparison_operator identifier string string_start string_content string_end block return_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier string string_start string_content string_end block return_statement call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator identifier string string_start string_content string_end block return_statement call attribute identifier identifier argument_list identifier identifier | 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 attribute identifier identifier slice unary_operator integer identifier argument_list string string_start string_content string_end return_statement binary_operator string string_start string_content string_end tuple identifier identifier | 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 adapter")
try:
args = parser.parse_args()
except argparse.ArgumentTypeError as e:
raise SystemExit(e)
devcon_path = shutil.which("devcon")
if not devcon_path:
raise SystemExit("Could not find devcon.exe")
from win32com.shell import shell
if not shell.IsUserAnAdmin():
raise SystemExit("You must run this script as an administrator")
try:
if args.add:
add_loopback(devcon_path, args.add[0], args.add[1], args.add[2])
if args.remove:
remove_loopback(devcon_path, args.remove)
except SystemExit as e:
print(e)
os.system("pause") | 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 string_content string_end string string_start string_content string_end keyword_argument identifier integer keyword_argument identifier call identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list except_clause as_pattern attribute identifier identifier as_pattern_target identifier block raise_statement call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end import_from_statement dotted_name identifier identifier dotted_name identifier if_statement not_operator call attribute identifier identifier argument_list block raise_statement call identifier argument_list string string_start string_content string_end try_statement block if_statement attribute identifier identifier block expression_statement call identifier argument_list identifier subscript attribute identifier identifier integer subscript attribute identifier identifier integer subscript attribute identifier identifier integer if_statement attribute identifier identifier block expression_statement call identifier argument_list identifier attribute identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end | 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)
session.flush()
except c_exc.NexusHostMappingNotFound:
pass | 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 identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier true for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list except_clause attribute identifier identifier block pass_statement | 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 keyword_argument identifier string string_start string_content string_end | 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 size | 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 identifier identifier comparison_operator identifier attribute identifier identifier identifier if_statement binary_operator identifier attribute identifier identifier block expression_statement assignment identifier binary_operator binary_operator parenthesized_expression binary_operator identifier unary_operator attribute identifier identifier attribute identifier identifier integer return_statement identifier | 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 assignment pattern_list identifier identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list attribute identifier identifier return_statement expression_list identifier identifier identifier | 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.search_exclude_fields,
) | 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 identifier identifier identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier | 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 identifier call identifier argument_list call identifier argument_list identifier if_statement comparison_operator identifier integer block return_statement binary_operator call identifier argument_list identifier call identifier argument_list call identifier argument_list identifier return_statement integer | 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.kill()
except:
pass | 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_statement call attribute attribute identifier identifier identifier argument_list if_statement subscript attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list except_clause block pass_statement | 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('return').get('outputter'))
except AttributeError:
outputter = None
if suffix == 'ret':
if isinstance(event.get('return'), dict) \
and set(event['return']) == set(('data', 'outputter')):
event_data = event['return']['data']
outputter = event['return']['outputter']
else:
event_data = event['return']
else:
event_data = {'suffix': suffix, 'event': event}
salt.output.display_output(event_data, outputter, self.opts) | 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 false block return_statement if_statement comparison_operator identifier tuple string string_start string_content string_end block return_statement try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end boolean_operator call attribute identifier identifier argument_list string string_start string_content string_end none call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list string string_start string_content string_end except_clause identifier block expression_statement assignment identifier none if_statement comparison_operator identifier string string_start string_content string_end block if_statement boolean_operator call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end identifier line_continuation comparison_operator call identifier argument_list subscript identifier string string_start string_content string_end call identifier argument_list tuple string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end else_clause block expression_statement assignment identifier subscript identifier string string_start string_content string_end else_clause block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier attribute identifier identifier | 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 attribute identifier identifier argument_list identifier if_statement comparison_operator identifier integer block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier | 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.approx_param_no)), grad_log_q, gradient, np.sum(self.approx_param_no))
vectorized = gradient - ((alpha0/np.var(grad_log_q,axis=1))*grad_log_q.T).T
return np.mean(vectorized,axis=1) | 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 identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator identifier parenthesized_expression binary_operator identifier identifier expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier identifier identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier binary_operator identifier attribute parenthesized_expression binary_operator parenthesized_expression binary_operator identifier call attribute identifier identifier argument_list identifier keyword_argument identifier integer attribute identifier identifier identifier return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier integer | 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 identifier list return_statement identifier | 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 identifier identifier identifier argument_list identifier | 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', 'Delta13C', 'nextime',
'Genus', 'Species', 'Feeding', 'Name']}
resp = _query_near(session=session, **search_params)
df = _response_to_dataframe(resp)
df_clean = _clean_dataframe(df)
return df_clean | 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_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier dictionary_splat identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier return_statement identifier | 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_indexer = indexing.posify_mask_indexer(indexer)
else:
actual_indexer = indexer
data = as_indexable(self._data)[actual_indexer]
chunks_hint = getattr(data, 'chunks', None)
mask = indexing.create_mask(indexer, self.shape, chunks_hint)
data = duck_array_ops.where(mask, fill_value, data)
else:
mask = indexing.create_mask(indexer, self.shape)
data = np.broadcast_to(fill_value, getattr(mask, 'shape', ()))
if new_order:
data = np.moveaxis(data, range(len(new_order)), new_order)
return self._finalize_indexing_result(dims, data) | 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 attribute identifier identifier expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list identifier if_statement attribute identifier identifier block if_statement call identifier argument_list attribute identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment identifier identifier expression_statement assignment identifier subscript call identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end none expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier call identifier argument_list identifier string string_start string_content string_end tuple if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier call identifier argument_list call identifier argument_list identifier identifier return_statement call attribute identifier identifier argument_list identifier identifier | 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.utils.path.os_walk(autosign_dir):
for f in filenames:
stub_file = os.path.join(autosign_dir, f)
mtime = os.path.getmtime(stub_file)
if mtime < min_time:
log.warning('Autosign keyid expired %s', stub_file)
os.remove(stub_file)
stub_file = os.path.join(autosign_dir, keyid)
if not os.path.exists(stub_file):
return False
os.remove(stub_file)
return True | 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 string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end integer if_statement comparison_operator identifier integer block expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list parenthesized_expression binary_operator integer call identifier argument_list identifier for_statement pattern_list identifier identifier identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier block for_statement identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block return_statement false expression_statement call attribute identifier identifier argument_list identifier return_statement true | 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 comparison_operator identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier call identifier argument_list identifier return_statement conditional_expression identifier comparison_operator identifier attribute identifier identifier none | 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',
'db_type': 'String(18)'
},
'ein': {
'value': self.ein,
'ordering': -2,
'line_number': 'NA',
'description': 'IRS employer id number',
'db_type': 'String(9)'
}
}
if self.documentId:
standardized_table_start['documentId'] = {
'value': self.documentId,
'description': 'Document ID',
'ordering': 0
}
else:
standardized_table_start = {
'object_id': self.object_id,
'ein': self.ein
}
if self.documentId:
standardized_table_start['documentId'] = self.documentId
return standardized_table_start | 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 string string_start string_content string_end unary_operator integer pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end unary_operator integer pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end if_statement attribute identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end integer else_clause block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier return_statement identifier | 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
self._size += len(str(value))
self._json_dict[key].append(value) | 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 identifier identifier integer expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator call identifier argument_list subscript attribute identifier identifier identifier integer block expression_statement augmented_assignment attribute identifier identifier integer if_statement call identifier argument_list identifier identifier block expression_statement augmented_assignment attribute identifier identifier integer expression_statement augmented_assignment attribute identifier identifier call identifier argument_list call identifier argument_list identifier expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list identifier | 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 identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier | 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 call identifier argument_list identifier identifier block return_statement call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier raise_statement call identifier argument_list string string_start string_content string_end | 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 expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | 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-processing."
" Defaults to the number of CPUs (%r)" % cpus)
og.add_argument("--shallow", action="store_true", default=False,
help="Check only that the files of this dist have"
"changed, do not infer the meaning")
og.add_argument("--ignore-filenames", action="append", default=[],
help="file glob to ignore. Can be specified multiple"
" times")
og.add_argument("--ignore-trailing-whitespace",
action="store_true", default=False,
help="ignore trailing whitespace when comparing text"
" files") | 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 identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier false keyword_argument identifier concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier list keyword_argument identifier concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier false keyword_argument identifier concatenated_string string string_start string_content string_end string string_start string_content string_end | 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_statement assignment attribute identifier identifier true expression_statement call attribute identifier identifier argument_list identifier identifier | 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 attribute identifier identifier argument_list identifier identifier identifier return_statement identifier | 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 permissions_tag in raw_parser.permissions(tag):
attrib_string = ''
attrib_string = join_sentences(attrib_string,
node_contents_str(raw_parser.copyright_statement(permissions_tag)), '.')
if raw_parser.licence_p(permissions_tag):
for licence_p_tag in raw_parser.licence_p(permissions_tag):
attrib_string = join_sentences(attrib_string,
node_contents_str(licence_p_tag), '.')
if attrib_string != '':
attributions.append(attrib_string)
return attributions | 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 identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier if_statement call attribute identifier identifier argument_list identifier block for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement assignment identifier string string_start string_end expression_statement assignment identifier call identifier argument_list identifier call identifier argument_list call attribute identifier identifier argument_list identifier string string_start string_content string_end if_statement call attribute identifier identifier argument_list identifier block for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list identifier call identifier argument_list identifier string string_start string_content string_end if_statement comparison_operator identifier string string_start string_end block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | 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 assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier return_statement call identifier argument_list identifier | 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,
self.qrs_thr_min * self.transform_gain)
self.rr_recent = rr_recent
self.last_qrs_ind = last_qrs_ind
self.last_qrs_peak_num = None | 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 identifier call identifier argument_list binary_operator binary_operator float attribute identifier identifier binary_operator float attribute identifier identifier binary_operator attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier none | 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 string_content string_end return_statement false | 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)
return FixedGPSScale | 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 attribute identifier identifier integer attribute identifier identifier subscript attribute identifier identifier integer function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement identifier | 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] = 1 - X[ee, :].dot(centers[cc, :].T)
labels[ee] = np.argmin(dists)
inertia[ee] = dists[int(labels[ee])]
return labels, np.sum(inertia) | 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 call attribute identifier identifier argument_list tuple identifier expression_statement assignment identifier call attribute identifier identifier argument_list tuple identifier for_statement identifier call identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list tuple identifier for_statement identifier call identifier argument_list identifier block expression_statement assignment subscript identifier identifier binary_operator integer call attribute subscript identifier identifier slice identifier argument_list attribute subscript identifier identifier slice identifier expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier identifier subscript identifier call identifier argument_list subscript identifier identifier return_statement expression_list identifier call attribute identifier identifier argument_list identifier | 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_control.UnauthorizedAccess:
print("No token available for access to %s" % object_id) | 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 expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier return_statement identifier except_clause attribute identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier | 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_operator attribute attribute identifier identifier identifier string string_start string_content string_end else_clause block return_statement string string_start string_end return_statement binary_operator identifier attribute identifier identifier | 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)))
except Exception as exc:
msg = 'Unable to bind socket {0}:{1}'.format(interface, port)
if exc.args:
msg = '{0}, error: {1}'.format(msg, str(exc))
else:
msg = '{0}, this might not be a problem.'.format(msg)
msg += '; Is there another salt-master running?'
if is_console_configured():
log.warning(msg)
else:
sys.stderr.write('WARNING: {0}\n'.format(msg))
return False
finally:
sock.close()
return True | 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 argument_list identifier attribute identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier integer expression_statement call attribute identifier identifier argument_list tuple identifier call identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier if_statement attribute identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier call identifier argument_list identifier else_clause block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement augmented_assignment identifier string string_start string_content string_end if_statement call identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier return_statement false finally_clause block expression_statement call attribute identifier identifier argument_list return_statement true | 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,
ignore_bad_attributes=ignore_bad_attributes)
return 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 attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement identifier | 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 disjoint_intervals | 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 assignment subscript identifier unary_operator integer call attribute subscript identifier unary_operator integer identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | 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(ensemble_lookup.keys()):
metric_List = calculate_metrics(molecules, ensemble_lookup, filename, options)
stats[filename] = metric_List
output.write_summary(stats, options, fw_type = None)
if options.plot:
print(" Making plots ... ")
print
plotter(molecules, ensemble_lookup, options) | 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 identifier argument_list string string_start string_end else_clause block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list string string_start string_end for_statement identifier call identifier argument_list call attribute identifier identifier argument_list block expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier expression_statement assignment subscript identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier none if_statement attribute identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end expression_statement identifier expression_statement call identifier argument_list identifier identifier identifier | 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 expression_statement call identifier argument_list identifier 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 expression_statement call identifier argument_list | 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 attribute attribute identifier identifier identifier argument_list raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier | 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 assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier | 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_keyring(path, key) | 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 identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier 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
if p_x > 0:
entropy -= p_x * math.log(p_x, 2)
return (entropy / 8) | 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 generator_expression tuple call identifier argument_list identifier integer for_in_clause identifier call identifier argument_list integer integer for_statement identifier identifier block expression_statement augmented_assignment subscript identifier identifier integer for_statement identifier call identifier argument_list integer integer block expression_statement assignment identifier binary_operator call identifier argument_list subscript identifier call identifier argument_list identifier identifier if_statement comparison_operator identifier integer block expression_statement augmented_assignment identifier binary_operator identifier call attribute identifier identifier argument_list identifier integer return_statement parenthesized_expression binary_operator identifier integer | 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:
self.write("\n")
break
else:
if command.strip() == "exit()":
return
more = self.push(command)
except KeyboardInterrupt:
self.write("\nKeyboardInterrupt\n")
self.resetbuffer()
more = 0
sys.exit(1)
echo_prompt(prompt)
wait_for(RETURNS) | 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 conditional_expression attribute identifier identifier identifier attribute identifier identifier try_statement block expression_statement call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end break_statement else_clause block if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end block return_statement expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier integer expression_statement call attribute identifier identifier argument_list integer expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier | 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 expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment subscript identifier identifier identifier return_statement call identifier argument_list list_splat identifier | 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_list integer else_clause block expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list integer expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier | 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 identifier call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier binary_operator string string_start string_content string_end attribute identifier identifier raise_statement call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list identifier list_splat identifier dictionary_splat identifier return_statement identifier | 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 if category.alias}
parent_to_children = OrderedDict()
for category in categories:
parent_category = ids.get(category.parent_id, False)
parent_alias = None
if parent_category:
parent_alias = parent_category.alias
if parent_alias not in parent_to_children:
parent_to_children[parent_alias] = []
parent_to_children[parent_alias].append(category.id)
cache_ = {
self.CACHE_NAME_IDS: ids,
self.CACHE_NAME_PARENTS: parent_to_children,
self.CACHE_NAME_ALIASES: aliases
}
cache.set(self.CACHE_ENTRY_NAME, cache_, self.CACHE_TIMEOUT)
self._cache = cache_ | 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 identifier argument_list identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier dictionary_comprehension pair attribute identifier identifier identifier for_in_clause identifier identifier expression_statement assignment identifier dictionary_comprehension pair attribute identifier identifier identifier for_in_clause identifier identifier if_clause attribute identifier identifier expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier false expression_statement assignment identifier none if_statement identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment subscript identifier identifier list expression_statement call attribute subscript identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier dictionary pair attribute identifier identifier identifier pair attribute identifier identifier identifier pair attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier identifier | 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(grouping=True)
model_str = cja.print_cyjs_graph()
return model_str | 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 argument_list identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier true expression_statement assignment identifier call attribute identifier identifier argument_list return_statement identifier | 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 identifier argument_list identifier identifier argument_list binary_operator string string_start string_content string_end identifier binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list return_statement identifier | 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):
sharded[i].append(items[start + i])
assert sum([len(fs) for fs in sharded]) == len(items)
return sharded | 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 identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list subscript identifier slice identifier binary_operator identifier identifier expression_statement augmented_assignment identifier identifier expression_statement assignment identifier binary_operator call identifier argument_list identifier identifier expression_statement assignment identifier binary_operator call identifier argument_list identifier identifier for_statement identifier call identifier argument_list identifier block expression_statement call attribute subscript identifier identifier identifier argument_list subscript identifier binary_operator identifier identifier assert_statement comparison_operator call identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier identifier call identifier argument_list identifier return_statement identifier | 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_content string_end attribute identifier identifier identifier | 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 identifier identifier line_continuation call attribute identifier identifier argument_list list keyword_argument identifier attribute identifier identifier for_in_clause identifier identifier | 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 attribute identifier identifier argument_list string string_start string_content string_end pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end | 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_statement assignment identifier subscript identifier identifier if_statement boolean_operator attribute identifier identifier comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier | 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 chunk:
params = dict(OrderedDict(zip(tuning_options.tune_params.keys(), element)))
try:
time = self.dev.compile_and_benchmark(gpu_args, params, kernel_options, tuning_options)
params['time'] = time
results.append(params)
except Exception:
params['time'] = None
results.append(params)
return results | 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 identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier except_clause identifier block expression_statement assignment subscript identifier string string_start string_content string_end none expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | 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 enumerate(
["pad"] + sorted(list(labels)))}
return label_to_index, index_to_label | 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 string_content string_end expression_statement assignment identifier dictionary_comprehension pair identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list binary_operator list string string_start string_content string_end call identifier argument_list call identifier argument_list identifier expression_statement assignment identifier dictionary_comprehension pair identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list binary_operator list string string_start string_content string_end call identifier argument_list call identifier argument_list identifier return_statement expression_list identifier identifier | 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):
v.loadconfig(getattr(obj,k))
else:
setattr(obj, k, v)
elif not hasattr(obj, k):
setattr(obj, k, v) | 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_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement call identifier argument_list identifier identifier block if_statement boolean_operator call identifier argument_list identifier identifier not_operator call identifier argument_list call identifier argument_list identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier else_clause block expression_statement call identifier argument_list identifier identifier identifier elif_clause not_operator call identifier argument_list identifier identifier block expression_statement call identifier argument_list identifier identifier identifier | 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)
server.quit() | 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 string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list else_clause block import_statement dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list | 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 else_clause block raise_statement call identifier argument_list string string_start string_content string_end | 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 string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list integer | 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 = getattr(resolved, default)
if not callable(resolved):
raise TypeError("{!r} is not callable"
"".format(resolved))
return resolved | 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_list identifier identifier block if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier if_statement not_operator call identifier argument_list identifier block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_end identifier argument_list identifier return_statement identifier | 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 identifier identifier argument_list none return_statement expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list subscript attribute identifier identifier identifier integer expression_statement call attribute identifier identifier argument_list identifier binary_operator parenthesized_expression binary_operator parenthesized_expression binary_operator identifier integer integer parenthesized_expression binary_operator identifier integer | 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(self.sigil) | 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 argument_list list binary_operator identifier string string_start string_content string_end binary_operator identifier string string_start string_content string_end binary_operator identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list list_comprehension call attribute identifier identifier argument_list for_in_clause identifier attribute identifier identifier if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier | 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 string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier if_statement boolean_operator not_operator identifier not_operator identifier block return_statement string string_start string_end elif_clause comparison_operator identifier identifier block return_statement identifier else_clause block return_statement call attribute string string_start string_content string_end identifier argument_list identifier identifier | 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.isdir(app_destination_path):
os.mkdir(app_destination_path)
for root, dirs, files in os.walk(tools_path):
for dir_name in dirs:
dir_source_path = os.path.join(root, dir_name)
dir_destination_path = self.change_path_prefix(
dir_source_path, tools_path, self.destination_path, app_name
)
if not os.path.isdir(dir_destination_path):
os.mkdir(dir_destination_path)
for file_name in files:
file_source_path = os.path.join(root, file_name)
file_destination_path = self.change_path_prefix(
file_source_path, tools_path, self.destination_path, app_name
)
shutil.copy2(file_source_path, file_destination_path) | 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 string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier for_statement pattern_list identifier identifier identifier call attribute identifier identifier argument_list identifier block for_statement identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier attribute identifier identifier identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier for_statement identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier | 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_list identifier except_clause identifier block return_statement integer | 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_clause identifier block expression_statement assignment identifier false expression_statement call attribute identifier identifier argument_list return_statement identifier | 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 argument_list list call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier | 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)
db.session.delete(role)
db.session.commit()
auditlog(event='role.delete', actor=session['user'].username, data={'roleId': roleId})
return self.make_response({
'message': 'Role has been deleted',
'roleId': roleId
}) | 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 attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier if_statement comparison_operator attribute identifier identifier tuple string string_start string_content string_end string string_start string_content string_end block return_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier attribute subscript identifier string string_start string_content string_end identifier keyword_argument identifier dictionary pair string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end identifier | 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 identifier identifier attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | 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.errorhandle(resp)
else:
if self.format == 'json':
return xmltodict.parse(resp)[self.RESPONSE_TOKEN]
elif self.format == 'xml':
return resp | 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_statement comparison_operator attribute identifier identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier elif_clause comparison_operator attribute identifier identifier identifier block return_statement call attribute identifier identifier argument_list identifier else_clause block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement subscript call attribute identifier identifier argument_list identifier attribute identifier identifier elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement identifier | 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, scale)
t.Translate(-cm)
tf = vtk.vtkTransformPolyDataFilter()
tf.SetInputData(self.poly)
tf.SetTransform(t)
tf.Update()
return self.updateMesh(tf.GetOutput()) | 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 block return_statement expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator identifier identifier keyword_argument identifier integer expression_statement assignment identifier binary_operator integer call attribute identifier identifier argument_list binary_operator call attribute identifier identifier argument_list identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list unary_operator identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list | 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_list call identifier argument_list attribute identifier identifier | 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 identifier identifier identifier identifier argument_list identifier identifier argument_list | 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.add(e)
except KeyError:
to_discard.add(e)
self._name_mapping[n] -= 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 assignment identifier call identifier argument_list for_statement identifier subscript attribute identifier identifier identifier block try_statement block if_statement comparison_operator identifier attribute attribute subscript identifier identifier identifier identifier block expression_statement yield identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement augmented_assignment subscript attribute identifier identifier identifier identifier | 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=attribute, value=value_l)
latex += "]\n"
return latex | 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 string string_start string_content string_end block continue_statement expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier string string_start string_end block continue_statement expression_statement augmented_assignment identifier call attribute string string_start string_content escape_sequence escape_sequence escape_sequence string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end return_statement identifier | 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_operator identifier call identifier argument_list identifier call identifier argument_list identifier | 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 identifier identifier pair string string_start string_content string_end attribute identifier identifier | 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[x], pos2[x]) for x in indexes]
stepcnt = 0
while (pos1 != pos2):
stepcnt += 1
stop = yield tuple(pos1)
if stop:
break
for x in indexes:
if pos1[x] != pos2[x]:
pos1[x] += steps[x]
if (steps[x] < 0) and (pos1[x] < pos2[x]):
pos1[x] = pos2[x]
if (steps[x] > 0) and (pos1[x] > pos2[x]):
pos1[x] = pos2[x]
yield tuple(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 assignment identifier list_comprehension identifier for_in_clause pattern_list identifier identifier call identifier argument_list identifier function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier identifier block return_statement identifier if_statement comparison_operator identifier identifier block return_statement unary_operator identifier return_statement integer expression_statement assignment identifier list_comprehension call identifier argument_list subscript identifier identifier subscript identifier identifier for_in_clause identifier identifier expression_statement assignment identifier integer while_statement parenthesized_expression comparison_operator identifier identifier block expression_statement augmented_assignment identifier integer expression_statement assignment identifier yield call identifier argument_list identifier if_statement identifier block break_statement for_statement identifier identifier block if_statement comparison_operator subscript identifier identifier subscript identifier identifier block expression_statement augmented_assignment subscript identifier identifier subscript identifier identifier if_statement boolean_operator parenthesized_expression comparison_operator subscript identifier identifier integer parenthesized_expression comparison_operator subscript identifier identifier subscript identifier identifier block expression_statement assignment subscript identifier identifier subscript identifier identifier if_statement boolean_operator parenthesized_expression comparison_operator subscript identifier identifier integer parenthesized_expression comparison_operator subscript identifier identifier subscript identifier identifier block expression_statement assignment subscript identifier identifier subscript identifier identifier expression_statement yield call identifier argument_list identifier | 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]:
if attribute not in spec:
return
try:
value = value_type(spec[attribute])
if (minimum is not None and value < minimum) or (maximum is not None and value > maximum):
raise None
except:
return InvalidNumberError(fully_qualified_name, spec, attribute, value_type, minimum,
maximum) | 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 type generic_type identifier type_parameter type identifier type generic_type identifier type_parameter type identifier identifier typed_default_parameter identifier type generic_type identifier type_parameter type generic_type identifier type_parameter type identifier type identifier none typed_default_parameter identifier type generic_type identifier type_parameter type generic_type identifier type_parameter type identifier type identifier none type generic_type identifier type_parameter type identifier block if_statement comparison_operator identifier identifier block return_statement try_statement block expression_statement assignment identifier call identifier argument_list subscript identifier identifier if_statement boolean_operator parenthesized_expression boolean_operator comparison_operator identifier none comparison_operator identifier identifier parenthesized_expression boolean_operator comparison_operator identifier none comparison_operator identifier identifier block raise_statement none except_clause block return_statement call identifier argument_list identifier identifier identifier identifier identifier identifier | 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
logger.info('copying binder requirements...', color='white')
_copy_binder_reqs(app, binder_conf)
_copy_binder_notebooks(app) | 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 string_end block return_statement expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end if_statement not_operator comparison_operator call identifier argument_list identifier integer block return_statement expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement call identifier argument_list identifier identifier expression_statement call identifier argument_list identifier | 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_operator subscript identifier identifier identifier block expression_statement augmented_assignment identifier integer expression_statement augmented_assignment identifier integer return_statement identifier | 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 attribute identifier identifier integer integer block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier string string_start string_content string_end return_statement call attribute call attribute identifier identifier argument_list identifier dictionary_splat identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end | 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.