code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def _parse_data(self, data, charset):
builder = TreeBuilder(numbermode=self._numbermode)
if isinstance(data,basestring):
xml.sax.parseString(data, builder)
else:
xml.sax.parse(data, builder)
return builder.root[self._root_element_name()] | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier if_statement call identifier argument_list identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier return_statement subscript attribute identifier identifier call attribute identifier identifier argument_list | Parse the xml data into dictionary. |
def showPopup(self):
nav = self.navigator()
nav.move(self.mapToGlobal(QPoint(0, self.height())))
nav.resize(400, 250)
nav.show() | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list call identifier argument_list integer call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list integer integer expression_statement call attribute identifier identifier argument_list | Displays the popup associated with this navigator. |
def detect_hooks():
flog.debug('Detecting hooks ...')
present = any([hasattr(hook, 'RENAMER') for hook in sys.meta_path])
if present:
flog.debug('Detected.')
else:
flog.debug('Not detected.')
return present | 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 identifier argument_list list_comprehension call identifier argument_list identifier string string_start string_content string_end for_in_clause identifier attribute identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier | Returns True if the import hooks are installed, False if not. |
def insertAnnouncement(self, announcement):
url = announcement.get('url', None)
try:
peers.Peer(url)
except:
raise exceptions.BadUrlException(url)
try:
models.Announcement.create(
url=announcement.get('url'),
attributes=json.dumps(announcement.get('attributes', {})),
remote_addr=announcement.get('remote_addr', None),
user_agent=announcement.get('user_agent', None))
except Exception as e:
raise exceptions.RepoManagerException(e) | 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 none try_statement block expression_statement call attribute identifier identifier argument_list identifier except_clause block raise_statement call attribute identifier identifier argument_list identifier try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end dictionary keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end none keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end none except_clause as_pattern identifier as_pattern_target identifier block raise_statement call attribute identifier identifier argument_list identifier | Adds an announcement to the registry for later analysis. |
def add(self, defn):
if defn.name not in self:
self[defn.name] = defn
else:
msg = "Duplicate packet name '%s'" % defn.name
log.error(msg)
raise util.YAMLError(msg) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment subscript identifier attribute identifier identifier identifier else_clause block expression_statement assignment identifier binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier raise_statement call attribute identifier identifier argument_list identifier | Adds the given Packet Definition to this Telemetry Dictionary. |
def ExpireObject(self, key):
node = self._hash.pop(key, None)
if node:
self._age.Unlink(node)
self.KillObject(node.data)
return node.data | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier none if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement attribute identifier identifier | Expire a specific object from cache. |
def _validate(self, writing=False):
box_ids = [box.box_id for box in self.box]
if len(box_ids) != 1 or box_ids[0] != 'flst':
msg = ("Fragment table boxes must have a single fragment list "
"box as a child box.")
self._dispatch_validation_error(msg, writing=writing) | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier list_comprehension attribute identifier identifier for_in_clause identifier attribute identifier identifier if_statement boolean_operator comparison_operator call identifier argument_list identifier integer comparison_operator subscript identifier integer string string_start string_content string_end block expression_statement assignment identifier parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier | Self-validate the box before writing. |
def binary_op(data, op, other, blen=None, storage=None, create='array',
**kwargs):
if hasattr(other, 'shape') and len(other.shape) == 0:
other = other[()]
if np.isscalar(other):
def f(block):
return op(block, other)
return map_blocks(data, f, blen=blen, storage=storage, create=create, **kwargs)
elif len(data) == len(other):
def f(a, b):
return op(a, b)
return map_blocks((data, other), f, blen=blen, storage=storage, create=create,
**kwargs)
else:
raise NotImplementedError('argument type not supported') | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier string string_start string_content string_end dictionary_splat_pattern identifier block if_statement boolean_operator call identifier argument_list identifier string string_start string_content string_end comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement assignment identifier subscript identifier tuple if_statement call attribute identifier identifier argument_list identifier block function_definition identifier parameters identifier block return_statement call identifier argument_list identifier identifier return_statement call identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier dictionary_splat identifier elif_clause comparison_operator call identifier argument_list identifier call identifier argument_list identifier block function_definition identifier parameters identifier identifier block return_statement call identifier argument_list identifier identifier return_statement call identifier argument_list tuple identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier dictionary_splat identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end | Compute a binary operation block-wise over `data`. |
def load(data_path):
with open(data_path, "r") as data_file:
raw_data = data_file.read()
data_file.close()
return raw_data | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list return_statement identifier | Extract data from provided file and return it as a string. |
def _read_config(conf_file=None):
if conf_file is None:
paths = ('/etc/supervisor/supervisord.conf', '/etc/supervisord.conf')
for path in paths:
if os.path.exists(path):
conf_file = path
break
if conf_file is None:
raise CommandExecutionError('No suitable config file found')
config = configparser.ConfigParser()
try:
config.read(conf_file)
except (IOError, OSError) as exc:
raise CommandExecutionError(
'Unable to read from {0}: {1}'.format(conf_file, exc)
)
return config | module function_definition identifier parameters default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier tuple string string_start string_content string_end string string_start string_content string_end for_statement identifier identifier block if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier identifier break_statement if_statement comparison_operator identifier none block raise_statement call 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 call attribute identifier identifier argument_list identifier except_clause as_pattern tuple identifier identifier as_pattern_target identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier return_statement identifier | Reads the config file using configparser |
def wherenotin(self, fieldname, value):
return self.wherein(fieldname, value, negate=True) | module function_definition identifier parameters identifier identifier identifier block return_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier true | Logical opposite of `wherein`. |
def storage(self):
annotation = get_portal_annotation()
if annotation.get(NUMBER_STORAGE) is None:
annotation[NUMBER_STORAGE] = OIBTree()
return annotation[NUMBER_STORAGE] | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list if_statement comparison_operator call attribute identifier identifier argument_list identifier none block expression_statement assignment subscript identifier identifier call identifier argument_list return_statement subscript identifier identifier | get the counter storage |
def inMicrolensRegion_main(args=None):
import argparse
parser = argparse.ArgumentParser(
description="Check if a celestial coordinate is "
"inside the K2C9 microlensing superstamp.")
parser.add_argument('ra', nargs=1, type=float,
help="Right Ascension in decimal degrees (J2000).")
parser.add_argument('dec', nargs=1, type=float,
help="Declination in decimal degrees (J2000).")
args = parser.parse_args(args)
if inMicrolensRegion(args.ra[0], args.dec[0]):
print("Yes! The coordinate is inside the K2C9 superstamp.")
else:
print("Sorry, the coordinate is NOT inside the K2C9 superstamp.") | module function_definition identifier parameters default_parameter identifier none block import_statement dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_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 integer keyword_argument identifier identifier 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 keyword_argument identifier integer keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call identifier argument_list subscript attribute identifier identifier integer subscript attribute identifier identifier integer block expression_statement call identifier argument_list string string_start string_content string_end else_clause block expression_statement call identifier argument_list string string_start string_content string_end | Exposes K2visible to the command line. |
def add_matplotlib_cmap(cm, name=None):
global cmaps
cmap = matplotlib_to_ginga_cmap(cm, name=name)
cmaps[cmap.name] = cmap | module function_definition identifier parameters identifier default_parameter identifier none block global_statement identifier expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment subscript identifier attribute identifier identifier identifier | Add a matplotlib colormap. |
def _tuple_requested(self, namespace_tuple):
if not isinstance(namespace_tuple[0], unicode):
encoded_db = unicode(namespace_tuple[0])
else:
encoded_db = namespace_tuple[0]
if not isinstance(namespace_tuple[1], unicode):
encoded_coll = unicode(namespace_tuple[1])
else:
encoded_coll = namespace_tuple[1]
if namespace_tuple is None:
return False
elif len(self._requested_namespaces) is 0:
return True
for requested_namespace in self._requested_namespaces:
if ((((requested_namespace[0]) == u'*') or
(encoded_db == requested_namespace[0])) and
(((requested_namespace[1]) == u'*') or
(encoded_coll == requested_namespace[1]))):
return True
return False | module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list subscript identifier integer identifier block expression_statement assignment identifier call identifier argument_list subscript identifier integer else_clause block expression_statement assignment identifier subscript identifier integer if_statement not_operator call identifier argument_list subscript identifier integer identifier block expression_statement assignment identifier call identifier argument_list subscript identifier integer else_clause block expression_statement assignment identifier subscript identifier integer if_statement comparison_operator identifier none block return_statement false elif_clause comparison_operator call identifier argument_list attribute identifier identifier integer block return_statement true for_statement identifier attribute identifier identifier block if_statement parenthesized_expression boolean_operator parenthesized_expression boolean_operator parenthesized_expression comparison_operator parenthesized_expression subscript identifier integer string string_start string_content string_end parenthesized_expression comparison_operator identifier subscript identifier integer parenthesized_expression boolean_operator parenthesized_expression comparison_operator parenthesized_expression subscript identifier integer string string_start string_content string_end parenthesized_expression comparison_operator identifier subscript identifier integer block return_statement true return_statement false | Helper for _namespace_requested. Supports limited wildcards |
def reset_term_stats(set_id, term_id, client_id, user_id, access_token):
found_sets = [user_set for user_set in get_user_sets(client_id, user_id)
if user_set.set_id == set_id]
if len(found_sets) != 1:
raise ValueError('{} set(s) found with id {}'.format(len(found_sets), set_id))
found_terms = [term for term in found_sets[0].terms if term.term_id == term_id]
if len(found_terms) != 1:
raise ValueError('{} term(s) found with id {}'.format(len(found_terms), term_id))
term = found_terms[0]
if term.image.url:
raise NotImplementedError('"{}" has an image and is thus not supported'.format(term))
print('Deleting "{}"...'.format(term))
delete_term(set_id, term_id, access_token)
print('Re-creating "{}"...'.format(term))
add_term(set_id, term, access_token)
print('Done') | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier call identifier argument_list identifier identifier if_clause comparison_operator attribute identifier identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier identifier expression_statement assignment identifier list_comprehension identifier for_in_clause identifier attribute subscript identifier integer identifier if_clause comparison_operator attribute identifier identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier identifier expression_statement assignment identifier subscript identifier integer if_statement attribute attribute identifier identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call identifier argument_list identifier identifier identifier expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call identifier argument_list identifier identifier identifier expression_statement call identifier argument_list string string_start string_content string_end | Reset the stats of a term by deleting and re-creating it. |
def addPeer(self):
self._openRepo()
try:
peer = peers.Peer(
self._args.url, json.loads(self._args.attributes))
except exceptions.BadUrlException:
raise exceptions.RepoManagerException("The URL for the peer was "
"malformed.")
except ValueError as e:
raise exceptions.RepoManagerException(
"The attributes message "
"was malformed. {}".format(e))
self._updateRepo(self._repo.insertPeer, peer) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier except_clause attribute identifier identifier block raise_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end except_clause as_pattern identifier as_pattern_target identifier block raise_statement call attribute identifier identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier identifier | Adds a new peer into this repo |
def _initGP(self):
if self._inference=='GP2KronSum':
signalPos = sp.where(sp.arange(self.n_randEffs)!=self.noisPos)[0][0]
gp = GP2KronSum(Y=self.Y, F=self.sample_designs, A=self.trait_designs,
Cg=self.trait_covars[signalPos], Cn=self.trait_covars[self.noisPos],
R=self.sample_covars[signalPos])
else:
mean = MeanKronSum(self.Y, self.sample_designs, self.trait_designs)
Iok = vec(~sp.isnan(mean.Y))[:,0]
if Iok.all(): Iok = None
covar = SumCov(*[KronCov(self.trait_covars[i], self.sample_covars[i], Iok=Iok) for i in range(self.n_randEffs)])
gp = GP(covar = covar, mean = mean)
self.gp = gp | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier subscript subscript call attribute identifier identifier argument_list comparison_operator call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier integer integer expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier subscript attribute identifier identifier identifier keyword_argument identifier subscript attribute identifier identifier attribute identifier identifier keyword_argument identifier subscript attribute identifier identifier identifier else_clause block expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement assignment identifier subscript call identifier argument_list unary_operator call attribute identifier identifier argument_list attribute identifier identifier slice integer if_statement call attribute identifier identifier argument_list block expression_statement assignment identifier none expression_statement assignment identifier call identifier argument_list list_splat list_comprehension call identifier argument_list subscript attribute identifier identifier identifier subscript attribute identifier identifier identifier keyword_argument identifier identifier for_in_clause identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment attribute identifier identifier identifier | Internal method for initialization of the GP inference objetct |
def trunc(x):
if isinstance(x, UncertainFunction):
mcpts = np.trunc(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.trunc(x) | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier return_statement call identifier argument_list identifier else_clause block return_statement call attribute identifier identifier argument_list identifier | Truncate the values to the integer value without rounding |
def h5features_convert(self, infile):
with h5py.File(infile, 'r') as f:
groups = list(f.keys())
for group in groups:
self._writer.write(
Reader(infile, group).read(),
self.groupname, append=True) | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list for_statement identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute call identifier argument_list identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier true | Convert a h5features file to the latest h5features version. |
def _propagate_packages(self):
for item in self.data:
if isinstance(item, LatexObject):
if isinstance(item, Container):
item._propagate_packages()
for p in item.packages:
self.packages.add(p) | module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block if_statement call identifier argument_list identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list for_statement identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Make sure packages get propagated. |
def __get_doc_block_lines(self):
line1 = None
line2 = None
i = 0
for line in self._routine_source_code_lines:
if re.match(r'\s*/\*\*', line):
line1 = i
if re.match(r'\s*\*/', line):
line2 = i
if self._is_start_of_stored_routine(line):
break
i += 1
return line1, line2 | module function_definition identifier parameters identifier block expression_statement assignment identifier none expression_statement assignment identifier none expression_statement assignment identifier integer for_statement identifier attribute identifier identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier block expression_statement assignment identifier identifier if_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier block expression_statement assignment identifier identifier if_statement call attribute identifier identifier argument_list identifier block break_statement expression_statement augmented_assignment identifier integer return_statement expression_list identifier identifier | Returns the start and end line of the DOcBlock of the stored routine code. |
def render_payment_form(self):
self.context[self.form_context_name] = self.payment_form_cls()
return TemplateResponse(self.request, self.payment_template, self.context) | module function_definition identifier parameters identifier block expression_statement assignment subscript attribute identifier identifier attribute identifier identifier call attribute identifier identifier argument_list return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier | Display the DirectPayment for entering payment information. |
def scale_values(numbers, num_lines=1, minimum=None, maximum=None):
"Scale input numbers to appropriate range."
filtered = [n for n in numbers if n is not None]
min_ = min(filtered) if minimum is None else minimum
max_ = max(filtered) if maximum is None else maximum
dv = max_ - min_
numbers = [max(min(n, max_), min_) if n is not None else None for n in numbers]
if dv == 0:
values = [4 * num_lines if x is not None else None for x in numbers]
elif dv > 0:
num_blocks = len(blocks) - 1
min_index = 1.
max_index = num_lines * num_blocks
values = [
((max_index - min_index) * (x - min_)) / dv + min_index
if not x is None else None for x in numbers
]
values = [round(v) or 1 if not v is None else None for v in values]
return values | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier none default_parameter identifier none block expression_statement string string_start string_content string_end expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause comparison_operator identifier none expression_statement assignment identifier conditional_expression call identifier argument_list identifier comparison_operator identifier none identifier expression_statement assignment identifier conditional_expression call identifier argument_list identifier comparison_operator identifier none identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier list_comprehension conditional_expression call identifier argument_list call identifier argument_list identifier identifier identifier comparison_operator identifier none none for_in_clause identifier identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier list_comprehension conditional_expression binary_operator integer identifier comparison_operator identifier none none for_in_clause identifier identifier elif_clause comparison_operator identifier integer block expression_statement assignment identifier binary_operator call identifier argument_list identifier integer expression_statement assignment identifier float expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier list_comprehension conditional_expression binary_operator binary_operator parenthesized_expression binary_operator parenthesized_expression binary_operator identifier identifier parenthesized_expression binary_operator identifier identifier identifier identifier not_operator comparison_operator identifier none none for_in_clause identifier identifier expression_statement assignment identifier list_comprehension conditional_expression boolean_operator call identifier argument_list identifier integer not_operator comparison_operator identifier none none for_in_clause identifier identifier return_statement identifier | Scale input numbers to appropriate range. |
def value_text(self):
search = self._selected.get()
for item in self._rbuttons:
if item.value == search:
return item.text
return "" | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list for_statement identifier attribute identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block return_statement attribute identifier identifier return_statement string string_start string_end | Sets or returns the option selected in a ButtonGroup by its text value. |
def init_index(self, app=None):
elasticindexes = self._get_indexes()
for index, settings in elasticindexes.items():
es = settings['resource']
if not es.indices.exists(index):
self.create_index(index, settings.get('index_settings'), es)
continue
else:
self.put_settings(app, index, settings.get('index_settings').get('settings'), es)
for mapping_type, mappings in settings.get('index_settings', {}).get('mappings').items():
self._put_resource_mapping(mapping_type, es,
properties=mappings,
index=index, doc_type=mapping_type)
return | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier continue_statement else_clause block expression_statement call attribute identifier identifier argument_list identifier identifier 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 identifier for_statement pattern_list identifier identifier call attribute call attribute call attribute identifier identifier argument_list string string_start string_content string_end dictionary identifier argument_list string string_start string_content string_end identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement | Create indexes and put mapping. |
async def wait_and_quit(loop):
from pylp.lib.tasks import running
if running:
await asyncio.wait(map(lambda runner: runner.future, running)) | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier identifier dotted_name identifier if_statement identifier block expression_statement await call attribute identifier identifier argument_list call identifier argument_list lambda lambda_parameters identifier attribute identifier identifier identifier | Wait until all task are executed. |
def _execute(self):
data = self.seed_fn()
for transform in self.transforms:
data = transform(data)
return list(data) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier return_statement call identifier argument_list identifier | Run the query, generating data from the `seed_fn` and performing transforms on the results. |
def _validate_all_tags_are_used(metadata):
tag_names = set([tag_name for tag_name, _ in metadata.tags])
filter_arg_names = set()
for location, _ in metadata.registered_locations:
for filter_info in metadata.get_filter_infos(location):
for filter_arg in filter_info.args:
if is_tag_argument(filter_arg):
filter_arg_names.add(get_directive_argument_name(filter_arg))
unused_tags = tag_names - filter_arg_names
if unused_tags:
raise GraphQLCompilationError(u'This GraphQL query contains @tag directives whose values '
u'are not used: {}. This is not allowed. Please either use '
u'them in a filter or remove them entirely.'
.format(unused_tags)) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list list_comprehension identifier for_in_clause pattern_list identifier identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list for_statement pattern_list identifier identifier attribute identifier identifier block for_statement identifier call attribute identifier identifier argument_list identifier block for_statement identifier attribute identifier identifier block if_statement call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement assignment identifier binary_operator identifier identifier if_statement identifier block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier | Ensure all tags are used in some filter. |
def read_remote_origin(repo_dir):
conf = ConfigParser()
conf.read(os.path.join(repo_dir, '.git/config'))
return conf.get('remote "origin"', 'url') | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end return_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end | Read the remote origin URL from the given git repo, or None if unset. |
def disable_requiretty_on_sudoers(log=False):
if log:
bookshelf2.logging_helpers.log_green(
'disabling requiretty on sudo calls')
comment_line('/etc/sudoers',
'^Defaults.*requiretty', use_sudo=True)
return True | module function_definition identifier parameters default_parameter identifier false block if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier true return_statement true | allow sudo calls through ssh without a tty |
def getThirdpartyLibs(self, libs, configuration = 'Development', includePlatformDefaults = True):
if includePlatformDefaults == True:
libs = self._defaultThirdpartyLibs() + libs
interrogator = self._getUE4BuildInterrogator()
return interrogator.interrogate(self.getPlatformIdentifier(), configuration, libs, self._getLibraryOverrides()) | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier true block if_statement comparison_operator identifier true block expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier call attribute identifier identifier argument_list | Retrieves the ThirdPartyLibraryDetails instance for Unreal-bundled versions of the specified third-party libraries |
def _deserialize(self, value, attr, data):
return super(DateString, self)._deserialize(value, attr,
data).isoformat() | module function_definition identifier parameters identifier identifier identifier identifier block return_statement call attribute call attribute call identifier argument_list identifier identifier identifier argument_list identifier identifier identifier identifier argument_list | Deserialize an ISO8601-formatted date. |
def build_and_install_wheel(python):
dist_type = "bdist_wheel" if not SDIST else "sdist"
return_code = run_command("{} setup.py {}".format(python, dist_type))
if return_code != 0:
print("Building and installing wheel failed.")
exit(return_code)
assert check_wheel_existence()
print("Wheel file exists.")
wheel = [file for file in os.listdir("dist") if file.endswith((".whl", ".tar.gz"))][0]
wheel = os.path.join("dist", wheel)
print("Wheel file:", wheel)
return_code = run_command("{} -m pip install --ignore-installed {}".format(python, wheel))
if return_code != 0:
print("Installation of wheel failed.")
exit(return_code)
print("Wheel file installed.") | module function_definition identifier parameters identifier block expression_statement assignment identifier conditional_expression string string_start string_content string_end not_operator identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier if_statement comparison_operator identifier integer block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list identifier assert_statement call identifier argument_list expression_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript list_comprehension identifier for_in_clause identifier call attribute identifier identifier argument_list string string_start string_content string_end if_clause call attribute identifier identifier argument_list tuple string string_start string_content string_end string string_start string_content string_end integer expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement call identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier if_statement comparison_operator identifier integer block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list identifier expression_statement call identifier argument_list string string_start string_content string_end | Build a binary distribution wheel and install it |
def unordered(x, y):
x = BigFloat._implicit_convert(x)
y = BigFloat._implicit_convert(y)
return mpfr.mpfr_unordered_p(x, y) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier identifier | Return True if x or y is a NaN and False otherwise. |
def RV_1(self):
return self.orbpop_long.RV * (self.orbpop_long.M2 / (self.orbpop_long.M1 + self.orbpop_long.M2)) | module function_definition identifier parameters identifier block return_statement binary_operator attribute attribute identifier identifier identifier parenthesized_expression binary_operator attribute attribute identifier identifier identifier parenthesized_expression binary_operator attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier | Instantaneous RV of star 1 with respect to system center-of-mass |
async def _send_generic_template(self, request: Request, stack: Stack):
gt = stack.get_layer(GenericTemplate)
payload = await gt.serialize(request)
msg = {
'attachment': {
'type': 'template',
'payload': payload
}
}
await self._add_qr(stack, msg, request)
await self._send(request, msg, stack) | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier await call attribute identifier identifier argument_list identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end 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 expression_statement await call attribute identifier identifier argument_list identifier identifier identifier expression_statement await call attribute identifier identifier argument_list identifier identifier identifier | Generates and send a generic template. |
def qual_name(self) -> QualName:
p, s, loc = self._key.partition(":")
return (loc, p) if s else (p, self.namespace) | module function_definition identifier parameters identifier type identifier block expression_statement assignment pattern_list identifier identifier identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end return_statement conditional_expression tuple identifier identifier identifier tuple identifier attribute identifier identifier | Return the receiver's qualified name. |
def get(geo_coord, mode=2, verbose=True):
if not isinstance(geo_coord, tuple) or not isinstance(geo_coord[0], float):
raise TypeError('Expecting a tuple')
_rg = RGeocoder(mode=mode, verbose=verbose)
return _rg.query([geo_coord])[0] | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier true block if_statement boolean_operator not_operator call identifier argument_list identifier identifier not_operator call identifier argument_list subscript identifier integer identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier return_statement subscript call attribute identifier identifier argument_list list identifier integer | Function to query for a single coordinate |
def on_message(msg, server):
text = msg.get("text", "")
match = re.findall(r"!gif (.*)", text)
if not match:
return
res = gif(match[0])
if not res:
return
attachment = {
"fallback": match[0],
"title": match[0],
"title_link": res,
"image_url": res
}
server.slack.post_message(
msg['channel'],
'',
as_user=server.slack.username,
attachments=json.dumps([attachment])) | 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 string string_start string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement not_operator identifier block return_statement expression_statement assignment identifier call identifier argument_list subscript identifier integer if_statement not_operator identifier block return_statement expression_statement assignment identifier dictionary pair string string_start string_content string_end subscript identifier integer pair string string_start string_content string_end subscript identifier integer 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 subscript identifier string string_start string_content string_end string string_start string_end keyword_argument identifier attribute attribute identifier identifier identifier keyword_argument identifier call attribute identifier identifier argument_list list identifier | handle a message and return an gif |
def get(self):
key = self.get_key_from_request()
result = self.get_storage().get(key)
return result if result else None | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list identifier return_statement conditional_expression identifier identifier none | Get the item from redis. |
def infer_compression(url):
compression_indicator = url[-2:]
mapping = dict(
gz='z',
bz='j',
xz='J',
)
return mapping.get(compression_indicator, 'z') | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript identifier slice unary_operator integer expression_statement assignment identifier call identifier argument_list keyword_argument identifier 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 return_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end | Given a URL or filename, infer the compression code for tar. |
def _tofloat(obj):
if "inf" in obj.lower().strip():
return obj
try:
return int(obj)
except ValueError:
try:
return float(obj)
except ValueError:
return obj | module function_definition identifier parameters identifier block if_statement comparison_operator string string_start string_content string_end call attribute call attribute identifier identifier argument_list identifier argument_list block return_statement identifier try_statement block return_statement call identifier argument_list identifier except_clause identifier block try_statement block return_statement call identifier argument_list identifier except_clause identifier block return_statement identifier | Convert to float if object is a float string. |
def status(self):
data = self._read()
self._status = YubiKeyUSBHIDStatus(data)
return self._status | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list identifier return_statement attribute identifier identifier | Poll YubiKey for status. |
def file_id(self):
if self.type.lower() == "directory":
return None
if self.file_uuid is None:
raise exceptions.MetsError(
"No FILEID: File %s does not have file_uuid set" % self.path
)
if self.is_aip:
return os.path.splitext(os.path.basename(self.path))[0]
return utils.FILE_ID_PREFIX + self.file_uuid | module function_definition identifier parameters identifier block if_statement comparison_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block return_statement none if_statement comparison_operator attribute identifier identifier none block raise_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier if_statement attribute identifier identifier block return_statement subscript call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier integer return_statement binary_operator attribute identifier identifier attribute identifier identifier | Returns the fptr @FILEID if this is not a Directory. |
def from_learner(cls, learn: Learner, ds_type:DatasetType=DatasetType.Valid):
"Create an instance of `ClassificationInterpretation`"
preds = learn.get_preds(ds_type=ds_type, with_loss=True)
return cls(learn, *preds) | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier attribute identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier true return_statement call identifier argument_list identifier list_splat identifier | Create an instance of `ClassificationInterpretation` |
def cnvkit_background(background_cnns, out_file, items, target_bed=None, antitarget_bed=None):
if not utils.file_exists(out_file):
with file_transaction(items[0], out_file) as tx_out_file:
cmd = [_get_cmd(), "reference", "-f", dd.get_ref_file(items[0]), "-o", tx_out_file]
gender = _get_batch_gender(items)
if gender:
cmd += ["--sample-sex", gender]
if len(background_cnns) == 0:
assert target_bed and antitarget_bed, "Missing CNNs and target BEDs for flat background"
cmd += ["-t", target_bed, "-a", antitarget_bed]
else:
cmd += background_cnns
do.run(_prep_cmd(cmd, tx_out_file), "CNVkit background")
return out_file | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier none block if_statement not_operator call attribute identifier identifier argument_list identifier block with_statement with_clause with_item as_pattern call identifier argument_list subscript identifier integer identifier as_pattern_target identifier block expression_statement assignment identifier list call identifier argument_list string string_start string_content string_end string string_start string_content string_end call attribute identifier identifier argument_list subscript identifier integer string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier if_statement identifier block expression_statement augmented_assignment identifier list string string_start string_content string_end identifier if_statement comparison_operator call identifier argument_list identifier integer block assert_statement boolean_operator identifier identifier string string_start string_content string_end expression_statement augmented_assignment identifier list string string_start string_content string_end identifier string string_start string_content string_end identifier else_clause block expression_statement augmented_assignment identifier identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier string string_start string_content string_end return_statement identifier | Calculate background reference, handling flat case with no normal sample. |
def _wrap_extraction(self, date_object: datetime.datetime,
original_text: str,
start_char: int,
end_char: int
) -> Extraction or None:
try:
resolution = self._settings[MIN_RESOLUTION] \
if self._settings[DATE_VALUE_RESOLUTION] == DateResolution.ORIGINAL \
else self._settings[DATE_VALUE_RESOLUTION]
e = Extraction(self._convert_to_iso_format(date_object, resolution=resolution),
start_char=start_char,
end_char=end_char,
extractor_name=self._name,
date_object=date_object,
original_date=original_text)
return e
except Exception as e:
warn('DateExtractor: Failed to wrap result ' + str(original_text) + ' with Extraction class.\n'
'Catch ' + str(e))
return None | module function_definition identifier parameters identifier typed_parameter identifier type attribute identifier identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type boolean_operator identifier none block try_statement block expression_statement assignment identifier conditional_expression subscript attribute identifier identifier identifier line_continuation comparison_operator subscript attribute identifier identifier identifier attribute identifier identifier line_continuation subscript attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list binary_operator binary_operator binary_operator string string_start string_content string_end call identifier argument_list identifier concatenated_string string string_start string_content escape_sequence string_end string string_start string_content string_end call identifier argument_list identifier return_statement none | wrap the final result as an Extraction and return |
def raster_field(self):
for field in self.model._meta.fields:
if isinstance(field, models.FileField):
return field
return False | module function_definition identifier parameters identifier block for_statement identifier attribute attribute attribute identifier identifier identifier identifier block if_statement call identifier argument_list identifier attribute identifier identifier block return_statement identifier return_statement false | Returns the raster FileField instance on the model. |
def load_object(s):
try:
m_path, o_name = s.rsplit('.', 1)
except ValueError:
raise ImportError('Cant import backend from path: {}'.format(s))
module = import_module(m_path)
return getattr(module, o_name) | module function_definition identifier parameters identifier block try_statement block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end integer except_clause identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier return_statement call identifier argument_list identifier identifier | Load backend by dotted path. |
def stripext (cmd, archive, verbosity, extension=""):
if verbosity >= 0:
print(util.stripext(archive)+extension)
return None | module function_definition identifier parameters identifier identifier identifier default_parameter identifier string string_start string_end block if_statement comparison_operator identifier integer block expression_statement call identifier argument_list binary_operator call attribute identifier identifier argument_list identifier identifier return_statement none | Print the name without suffix. |
def create_node(self, network, participant):
return self.models.MCMCPAgent(network=network, participant=participant) | module function_definition identifier parameters identifier identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier | Create a node for a participant. |
def log(self, level, *msg_elements):
self.report.log(self._threadlocal.current_workunit, level, *msg_elements) | module function_definition identifier parameters identifier identifier list_splat_pattern identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier identifier list_splat identifier | Log a message against the current workunit. |
def file_renamed(self, editor, new_filename):
if editor is None:
return
editor_id = editor.get_id()
if editor_id in list(self.editor_ids.values()):
root_item = self.editor_items[editor_id]
root_item.set_path(new_filename, fullpath=self.show_fullpath)
self.__sort_toplevel_items() | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier none block return_statement expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list | File was renamed, updating outline explorer tree |
def _connect_su(spec):
return {
'method': 'su',
'enable_lru': True,
'kwargs': {
'username': spec.become_user(),
'password': spec.become_pass(),
'python_path': spec.python_path(),
'su_path': spec.become_exe(),
'connect_timeout': spec.timeout(),
'remote_name': get_remote_name(spec),
}
} | module function_definition identifier parameters identifier block return_statement dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end true pair string string_start string_content string_end dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list pair string string_start string_content string_end call attribute identifier identifier argument_list pair string string_start string_content string_end call attribute identifier identifier argument_list pair string string_start string_content string_end call attribute identifier identifier argument_list pair string string_start string_content string_end call attribute identifier identifier argument_list pair string string_start string_content string_end call identifier argument_list identifier | Return ContextService arguments for su as a become method. |
def from_api_response(cls, reddit_session, json_dict):
json_dict['subreddits'] = [Subreddit(reddit_session, item['name'])
for item in json_dict['subreddits']]
return cls(reddit_session, None, None, json_dict) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end list_comprehension call identifier argument_list identifier subscript identifier string string_start string_content string_end for_in_clause identifier subscript identifier string string_start string_content string_end return_statement call identifier argument_list identifier none none identifier | Return an instance of the appropriate class from the json dict. |
def _add_pos1(token):
result = token.copy()
result['pos1'] = _POSMAP[token['pos'].split("(")[0]]
return result | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier subscript call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end integer return_statement identifier | Adds a 'pos1' element to a frog token. |
def create_firewall_rule(self, protocol, action, **kwargs):
body = {'protocol': protocol, 'action': action}
if 'tenant_id' in kwargs:
body['tenant_id'] = kwargs['tenant_id']
if 'name' in kwargs:
body['name'] = kwargs['name']
if 'description' in kwargs:
body['description'] = kwargs['description']
if 'ip_version' in kwargs:
body['ip_version'] = kwargs['ip_version']
if 'source_ip_address' in kwargs:
body['source_ip_address'] = kwargs['source_ip_address']
if 'destination_port' in kwargs:
body['destination_port'] = kwargs['destination_port']
if 'shared' in kwargs:
body['shared'] = kwargs['shared']
if 'enabled' in kwargs:
body['enabled'] = kwargs['enabled']
return self.network_conn.create_firewall_rule(body={'firewall_rule': body}) | module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end return_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier dictionary pair string string_start string_content string_end identifier | Create a new firlwall rule |
def hr_avg(self):
hr_data = self.hr_values()
return int(sum(hr_data) / len(hr_data)) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call identifier argument_list binary_operator call identifier argument_list identifier call identifier argument_list identifier | Average heart rate of the workout |
def to_xarray(self) -> "xarray.Dataset":
import xarray as xr
data_vars = {
"frequencies": xr.DataArray(self.frequencies, dims="bin"),
"errors2": xr.DataArray(self.errors2, dims="bin"),
"bins": xr.DataArray(self.bins, dims=("bin", "x01"))
}
coords = {}
attrs = {
"underflow": self.underflow,
"overflow": self.overflow,
"inner_missed": self.inner_missed,
"keep_missed": self.keep_missed
}
attrs.update(self._meta_data)
return xr.Dataset(data_vars, coords, attrs) | module function_definition identifier parameters identifier type string string_start string_content string_end block import_statement aliased_import dotted_name identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier string string_start string_content string_end pair string string_start string_content string_end call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier string string_start string_content string_end pair string string_start string_content string_end call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier tuple string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier dictionary 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 pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement call attribute identifier identifier argument_list identifier identifier identifier | Convert to xarray.Dataset |
def start(self):
self.log.info("Starting Insecure Session for Monitor %s" % self.monitor_id)
if self.socket is not None:
raise Exception("Socket already established for %s." % self)
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((self.client.hostname, PUSH_OPEN_PORT))
self.socket.setblocking(0)
except socket.error as exception:
self.socket.close()
self.socket = None
raise
self.send_connection_request() | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier try_statement block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list tuple attribute attribute identifier identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list integer except_clause as_pattern attribute identifier identifier as_pattern_target identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier none raise_statement expression_statement call attribute identifier identifier argument_list | Creates a TCP connection to Device Cloud and sends a ConnectionRequest message |
async def open(self):
self.store.register(self)
while not self.finished:
message = await self.messages.get()
await self.publish(message) | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier while_statement not_operator attribute identifier identifier block expression_statement assignment identifier await call attribute attribute identifier identifier identifier argument_list expression_statement await call attribute identifier identifier argument_list identifier | Register with the publisher. |
def http_methods(self, urls=None, **route_data):
def decorator(class_definition):
instance = class_definition
if isinstance(class_definition, type):
instance = class_definition()
router = self.urls(urls if urls else "/{0}".format(instance.__class__.__name__.lower()), **route_data)
for method in HTTP_METHODS:
handler = getattr(instance, method.lower(), None)
if handler:
http_routes = getattr(handler, '_hug_http_routes', ())
if http_routes:
for route in http_routes:
http(**router.accept(method).where(**route).route)(handler)
else:
http(**router.accept(method).route)(handler)
cli_routes = getattr(handler, '_hug_cli_routes', ())
if cli_routes:
for route in cli_routes:
cli(**self.where(**route).route)(handler)
return class_definition
return decorator | module function_definition identifier parameters identifier default_parameter identifier none dictionary_splat_pattern identifier block function_definition identifier parameters identifier block expression_statement assignment identifier identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list conditional_expression identifier identifier call attribute string string_start string_content string_end identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list dictionary_splat identifier for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list identifier call attribute identifier identifier argument_list none if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end tuple if_statement identifier block for_statement identifier identifier block expression_statement call call identifier argument_list dictionary_splat attribute call attribute call attribute identifier identifier argument_list identifier identifier argument_list dictionary_splat identifier identifier argument_list identifier else_clause block expression_statement call call identifier argument_list dictionary_splat attribute call attribute identifier identifier argument_list identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end tuple if_statement identifier block for_statement identifier identifier block expression_statement call call identifier argument_list dictionary_splat attribute call attribute identifier identifier argument_list dictionary_splat identifier identifier argument_list identifier return_statement identifier return_statement identifier | Creates routes from a class, where the class method names should line up to HTTP METHOD types |
def _is_custom_manager_attribute(node):
attrname = node.attrname
if not name_is_from_qs(attrname):
return False
for attr in node.get_children():
inferred = safe_infer(attr)
funcdef = getattr(inferred, '_proxied', None)
if _is_custom_qs_manager(funcdef):
return True
return False | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier if_statement not_operator call identifier argument_list identifier block return_statement false for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end none if_statement call identifier argument_list identifier block return_statement true return_statement false | Checks if the attribute is a valid attribute for a queryset manager. |
def validate_json(f):
@wraps(f)
def wrapper(*args, **kw):
instance = args[0]
try:
if request.get_json() is None:
ret_dict = instance._create_ret_object(instance.FAILURE,
None, True,
instance.MUST_JSON)
instance.logger.error(instance.MUST_JSON)
return jsonify(ret_dict), 400
except BadRequest:
ret_dict = instance._create_ret_object(instance.FAILURE, None,
True,
instance.MUST_JSON)
instance.logger.error(instance.MUST_JSON)
return jsonify(ret_dict), 400
instance.logger.debug("JSON is valid")
return f(*args, **kw)
return wrapper | module function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier subscript identifier integer try_statement block if_statement comparison_operator call attribute identifier identifier argument_list none block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier none true attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier return_statement expression_list call identifier argument_list identifier integer except_clause identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier none true attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier return_statement expression_list call identifier argument_list identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end return_statement call identifier argument_list list_splat identifier dictionary_splat identifier return_statement identifier | Validate that the call is JSON. |
def print_row_perc_table(table, row_labels, col_labels):
r1c1, r1c2, r2c1, r2c2 = map(float, table)
row1 = r1c1 + r1c2
row2 = r2c1 + r2c2
blocks = [
(r1c1, row1),
(r1c2, row1),
(r2c1, row2),
(r2c2, row2)]
new_table = []
for cell, row in blocks:
try:
x = cell / row
except ZeroDivisionError:
x = 0
new_table.append(x)
s = print_2x2_table(new_table, row_labels, col_labels, fmt="%.2f")
s = s.splitlines(True)
del s[5]
return ''.join(s) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier identifier call identifier argument_list identifier identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier list tuple identifier identifier tuple identifier identifier tuple identifier identifier tuple identifier identifier expression_statement assignment identifier list for_statement pattern_list identifier identifier identifier block try_statement block expression_statement assignment identifier binary_operator identifier identifier except_clause identifier block expression_statement assignment identifier integer expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list true delete_statement subscript identifier integer return_statement call attribute string string_start string_end identifier argument_list identifier | given a table, print the percentages rather than the totals |
def hosting_devices_removed(self, context, payload):
try:
if payload['hosting_data']:
if payload['hosting_data'].keys():
self.process_services(removed_devices_info=payload)
except KeyError as e:
LOG.error("Invalid payload format for received RPC message "
"`hosting_devices_removed`. Error is %(error)s. Payload "
"is %(payload)s", {'error': e, 'payload': payload}) | module function_definition identifier parameters identifier identifier identifier block try_statement block if_statement subscript identifier string string_start string_content string_end block if_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list block expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier | Deal with hosting device removed RPC message. |
def flavor_extra_delete(request, flavor_id, keys):
flavor = _nova.novaclient(request).flavors.get(flavor_id)
return flavor.unset_keys(keys) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute call attribute identifier identifier argument_list identifier identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier | Unset the flavor extra spec keys. |
def query(self, query, *parameters, **kwargs):
cursor = self._cursor()
try:
self._execute(cursor, query, parameters or None, kwargs)
if cursor.description:
column_names = [column.name for column in cursor.description]
res = [Row(zip(column_names, row)) for row in cursor.fetchall()]
cursor.close()
return res
except:
cursor.close()
raise | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block expression_statement call attribute identifier identifier argument_list identifier identifier boolean_operator identifier none identifier if_statement attribute identifier identifier block expression_statement assignment identifier list_comprehension attribute identifier identifier for_in_clause identifier attribute identifier identifier expression_statement assignment identifier list_comprehension call identifier argument_list call identifier argument_list identifier identifier for_in_clause identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list return_statement identifier except_clause block expression_statement call attribute identifier identifier argument_list raise_statement | Returns a row list for the given query and parameters. |
def update(self, user, **kwargs):
yield self.get_parent()
if not self.parent.editable:
err = 'Cannot update child of {} resource'.format(self.parent.state.name)
raise exceptions.Unauthorized(err)
yield super(SubResource, self).update(user, **kwargs) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement yield call attribute identifier identifier argument_list if_statement not_operator attribute attribute identifier identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute attribute attribute identifier identifier identifier identifier raise_statement call attribute identifier identifier argument_list identifier expression_statement yield call attribute call identifier argument_list identifier identifier identifier argument_list identifier dictionary_splat identifier | If parent resource is not an editable state, should not be able to update |
def _print_header(self):
header = " Iter Dir "
if self.constraints is not None:
header += ' SC CC'
header += " Function"
if self.convergence_condition is not None:
header += self.convergence_condition.get_header()
header += " Time"
self._screen("-"*(len(header)), newline=True)
self._screen(header, newline=True)
self._screen("-"*(len(header)), newline=True) | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end if_statement comparison_operator attribute identifier identifier none block expression_statement augmented_assignment identifier string string_start string_content string_end expression_statement augmented_assignment identifier string string_start string_content string_end if_statement comparison_operator attribute identifier identifier none block expression_statement augmented_assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement augmented_assignment identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression call identifier argument_list identifier keyword_argument identifier true expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier true expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression call identifier argument_list identifier keyword_argument identifier true | Print the header for screen logging |
def wrap(string, length, indent):
newline = "\n" + " " * indent
return newline.join((string[i : i + length] for i in range(0, len(string), length))) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content escape_sequence string_end binary_operator string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list generator_expression subscript identifier slice identifier binary_operator identifier identifier for_in_clause identifier call identifier argument_list integer call identifier argument_list identifier identifier | Wrap a string at a line length |
def unpack_variable(var):
if var.dataType == stream.STRUCTURE:
return None, struct_to_dtype(var), 'Structure'
elif var.dataType == stream.SEQUENCE:
log.warning('Sequence support not implemented!')
dt = data_type_to_numpy(var.dataType, var.unsigned)
if var.dataType == stream.OPAQUE:
type_name = 'opaque'
elif var.dataType == stream.STRING:
type_name = 'string'
else:
type_name = dt.name
if var.data:
log.debug('Storing variable data: %s %s', dt, var.data)
if var.dataType == stream.STRING:
data = var.data
else:
data = np.frombuffer(var.data, dtype=dt.newbyteorder('>'))
else:
data = None
return data, dt, type_name | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block return_statement expression_list none call identifier argument_list identifier string string_start string_content string_end elif_clause comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier string string_start string_content string_end elif_clause comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier attribute identifier identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment identifier none return_statement expression_list identifier identifier identifier | Unpack an NCStream Variable into information we can use. |
def write_bit(self, b):
if b:
b = 1
else:
b = 0
shift = self.bitcount % 8
if shift == 0:
self.bits.append(0)
self.bits[-1] |= (b << shift)
self.bitcount += 1 | module function_definition identifier parameters identifier identifier block if_statement identifier block expression_statement assignment identifier integer else_clause block expression_statement assignment identifier integer expression_statement assignment identifier binary_operator attribute identifier identifier integer if_statement comparison_operator identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list integer expression_statement augmented_assignment subscript attribute identifier identifier unary_operator integer parenthesized_expression binary_operator identifier identifier expression_statement augmented_assignment attribute identifier identifier integer | Write a boolean value. |
def _handle_response(response, command, id_xpath='./id', **kwargs):
_response_switch = {
'insert': ModifyResponse,
'replace': ModifyResponse,
'partial-replace': ModifyResponse,
'update': ModifyResponse,
'delete': ModifyResponse,
'search-delete': SearchDeleteResponse,
'reindex': Response,
'backup': Response,
'restore': Response,
'clear': Response,
'status': StatusResponse,
'search': SearchResponse,
'retrieve': ListResponse,
'similar': ListResponse,
'lookup': LookupResponse,
'alternatives': AlternativesResponse,
'list-words': WordsResponse,
'list-first': ListResponse,
'list-last': ListResponse,
'retrieve-last': ListResponse,
'retrieve-first': ListResponse,
'show-history': None,
'list-paths': ListPathsResponse,
'list-facets': ListFacetsResponse}
try:
request_class = _response_switch[command]
except KeyError:
request_class = Response
return request_class(response, id_xpath, **kwargs) | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end dictionary_splat_pattern identifier 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 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 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 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 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 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 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 none pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier try_statement block expression_statement assignment identifier subscript identifier identifier except_clause identifier block expression_statement assignment identifier identifier return_statement call identifier argument_list identifier identifier dictionary_splat identifier | Initialize the corect Response object from the response string based on the API command type. |
def scatter_group(ax, key, imask, adata, Y, projection='2d', size=3, alpha=None):
mask = adata.obs[key].cat.categories[imask] == adata.obs[key].values
color = adata.uns[key + '_colors'][imask]
if not isinstance(color[0], str):
from matplotlib.colors import rgb2hex
color = rgb2hex(adata.uns[key + '_colors'][imask])
if not is_color_like(color):
raise ValueError('"{}" is not a valid matplotlib color.'.format(color))
data = [Y[mask, 0], Y[mask, 1]]
if projection == '3d': data.append(Y[mask, 2])
ax.scatter(*data,
marker='.',
alpha=alpha,
c=color,
edgecolors='none',
s=size,
label=adata.obs[key].cat.categories[imask],
rasterized=settings._vector_friendly)
return mask | module function_definition identifier parameters identifier identifier identifier identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier integer default_parameter identifier none block expression_statement assignment identifier comparison_operator subscript attribute attribute subscript attribute identifier identifier identifier identifier identifier identifier attribute subscript attribute identifier identifier identifier identifier expression_statement assignment identifier subscript subscript attribute identifier identifier binary_operator identifier string string_start string_content string_end identifier if_statement not_operator call identifier argument_list subscript identifier integer identifier block import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list subscript subscript attribute identifier identifier binary_operator identifier string string_start string_content string_end identifier if_statement not_operator call identifier argument_list identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier list subscript identifier identifier integer subscript identifier identifier integer if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list subscript identifier identifier integer expression_statement call attribute identifier identifier argument_list list_splat identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier subscript attribute attribute subscript attribute identifier identifier identifier identifier identifier identifier keyword_argument identifier attribute identifier identifier return_statement identifier | Scatter of group using representation of data Y. |
def precondition(self):
return self.tlang.nplurals == self.slang.nplurals and \
super(PrintfValidator, self).precondition() | module function_definition identifier parameters identifier block return_statement boolean_operator comparison_operator attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier line_continuation call attribute call identifier argument_list identifier identifier identifier argument_list | Check if the number of plurals in the two languages is the same. |
def disable_vlan_on_trunk_int(self, nexus_host, vlanid, intf_type,
interface, is_native):
starttime = time.time()
path_snip, body_snip = self._get_vlan_body_on_trunk_int(
nexus_host, vlanid, intf_type, interface,
is_native, True, False)
self.send_edit_string(nexus_host, path_snip, body_snip)
self.capture_and_print_timeshot(
starttime, "delif",
switch=nexus_host) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier identifier identifier identifier identifier true false expression_statement call attribute identifier identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end keyword_argument identifier identifier | Disable a VLAN on a trunk interface. |
def find_state_op_colocation_error(graph, reported_tags=None):
state_op_types = list_registered_stateful_ops_without_inputs()
state_op_map = {op.name: op for op in graph.get_operations()
if op.type in state_op_types}
for op in state_op_map.values():
for colocation_group in op.colocation_groups():
if not (colocation_group.startswith(tf.compat.as_bytes("loc:@")) and
tf.compat.as_str_any(colocation_group[5:]) in state_op_map):
tags_prefix = ("" if reported_tags is None else
"in the graph for tags %s, " % reported_tags)
return (
"A state-holding node x of a module's graph (e.g., a Variable op) "
"must not be subject to a tf.colocate_with(y) constraint "
"unless y is also a state-holding node.\n"
"Details: %snode '%s' has op '%s', which counts as state-holding, "
"but Operation.colocation_groups() == %s. " %
(tags_prefix, op.name, op.type, op.colocation_groups()))
return None | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier dictionary_comprehension pair attribute identifier identifier identifier for_in_clause identifier call attribute identifier identifier argument_list if_clause comparison_operator attribute identifier identifier identifier for_statement identifier call attribute identifier identifier argument_list block for_statement identifier call attribute identifier identifier argument_list block if_statement not_operator parenthesized_expression boolean_operator call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end comparison_operator call attribute attribute identifier identifier identifier argument_list subscript identifier slice integer identifier block expression_statement assignment identifier parenthesized_expression conditional_expression string string_start string_end comparison_operator identifier none binary_operator string string_start string_content string_end identifier return_statement parenthesized_expression binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content escape_sequence string_end string string_start string_content string_end string string_start string_content string_end tuple identifier attribute identifier identifier attribute identifier identifier call attribute identifier identifier argument_list return_statement none | Returns error message for colocation of state ops, or None if ok. |
def broadcast(self, command, *args, **kwargs):
criterion = kwargs.pop('criterion', self.BROADCAST_FILTER_ALL)
for index, user in items(self.users()):
if criterion(user, command, *args, **kwargs):
self.notify(user, command, *args, **kwargs) | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier for_statement pattern_list identifier identifier call identifier argument_list call attribute identifier identifier argument_list block if_statement call identifier argument_list identifier identifier list_splat identifier dictionary_splat identifier block expression_statement call attribute identifier identifier argument_list identifier identifier list_splat identifier dictionary_splat identifier | Notifies each user with a specified command. |
def _get_resources(self, resource, obj, params=None, map=None, **kwargs):
r = self._http_resource('GET', resource, params=params)
d_items = self._resource_deserialize(r.content.decode("utf-8"))
items = [obj.new_from_dict(item, h=self, **kwargs) for item in d_items]
if map is None:
map = KeyedListResource
list_resource = map(items=items)
list_resource._h = self
list_resource._obj = obj
list_resource._kwargs = kwargs
return list_resource | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier none dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list identifier keyword_argument identifier identifier dictionary_splat identifier for_in_clause identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier return_statement identifier | Returns a list of mapped objects from an HTTP resource. |
def _changeMs(self, line):
try:
last_space_pos = line.rindex(' ')
except ValueError:
return line
else:
end_str = line[last_space_pos:]
new_string = line
if end_str[-2:] == 'ms' and int(end_str[:-2]) >= 1000:
ms = int(end_str[:-2])
new_string = (line[:last_space_pos] +
' (' + self._msToString(ms) + ')' +
line[last_space_pos:])
return new_string | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end except_clause identifier block return_statement identifier else_clause block expression_statement assignment identifier subscript identifier slice identifier expression_statement assignment identifier identifier if_statement boolean_operator comparison_operator subscript identifier slice unary_operator integer string string_start string_content string_end comparison_operator call identifier argument_list subscript identifier slice unary_operator integer integer block expression_statement assignment identifier call identifier argument_list subscript identifier slice unary_operator integer expression_statement assignment identifier parenthesized_expression binary_operator binary_operator binary_operator binary_operator subscript identifier slice identifier string string_start string_content string_end call attribute identifier identifier argument_list identifier string string_start string_content string_end subscript identifier slice identifier return_statement identifier | Change the ms part in the string if needed. |
def to_function(var_instance, lineno=None):
assert isinstance(var_instance, SymbolVAR)
from symbols import FUNCTION
var_instance.__class__ = FUNCTION
var_instance.class_ = CLASS.function
var_instance.reset(lineno=lineno)
return var_instance | module function_definition identifier parameters identifier default_parameter identifier none block assert_statement call identifier argument_list identifier identifier import_from_statement dotted_name identifier dotted_name identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier return_statement identifier | Converts a var_instance to a function one |
def det_n(x):
assert x.ndim == 3
assert x.shape[1] == x.shape[2]
if x.shape[1] == 1:
return x[:,0,0]
result = np.zeros(x.shape[0])
for permutation in permutations(np.arange(x.shape[1])):
sign = parity(permutation)
result += np.prod([x[:, i, permutation[i]]
for i in range(x.shape[1])], 0) * sign
sign = - sign
return result | module function_definition identifier parameters identifier block assert_statement comparison_operator attribute identifier identifier integer assert_statement comparison_operator subscript attribute identifier identifier integer subscript attribute identifier identifier integer if_statement comparison_operator subscript attribute identifier identifier integer integer block return_statement subscript identifier slice integer integer expression_statement assignment identifier call attribute identifier identifier argument_list subscript attribute identifier identifier integer for_statement identifier call identifier argument_list call attribute identifier identifier argument_list subscript attribute identifier identifier integer block expression_statement assignment identifier call identifier argument_list identifier expression_statement augmented_assignment identifier binary_operator call attribute identifier identifier argument_list list_comprehension subscript identifier slice identifier subscript identifier identifier for_in_clause identifier call identifier argument_list subscript attribute identifier identifier integer integer identifier expression_statement assignment identifier unary_operator identifier return_statement identifier | given N matrices, return N determinants |
def connect(self):
vvv("ESTABLISH CONNECTION FOR USER: %s" % self.runner.remote_user, host=self.host)
self.common_args = []
extra_args = C.ANSIBLE_SSH_ARGS
if extra_args is not None:
self.common_args += shlex.split(extra_args)
else:
self.common_args += ["-o", "ControlMaster=auto",
"-o", "ControlPersist=60s",
"-o", "ControlPath=/tmp/ansible-ssh-%h-%p-%r"]
self.common_args += ["-o", "StrictHostKeyChecking=no"]
if self.port is not None:
self.common_args += ["-o", "Port=%d" % (self.port)]
if self.runner.private_key_file is not None:
self.common_args += ["-o", "IdentityFile="+os.path.expanduser(self.runner.private_key_file)]
if self.runner.remote_pass:
self.common_args += ["-o", "GSSAPIAuthentication=no",
"-o", "PubkeyAuthentication=no"]
else:
self.common_args += ["-o", "KbdInteractiveAuthentication=no",
"-o", "PasswordAuthentication=no"]
self.common_args += ["-o", "User="+self.runner.remote_user]
return self | module function_definition identifier parameters identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end attribute attribute identifier identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment attribute identifier identifier list expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block expression_statement augmented_assignment attribute identifier identifier call attribute identifier identifier argument_list identifier else_clause block expression_statement augmented_assignment attribute identifier identifier 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 expression_statement augmented_assignment attribute identifier identifier list string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator attribute identifier identifier none block expression_statement augmented_assignment attribute identifier identifier list string string_start string_content string_end binary_operator string string_start string_content string_end parenthesized_expression attribute identifier identifier if_statement comparison_operator attribute attribute identifier identifier identifier none block expression_statement augmented_assignment attribute identifier identifier list string string_start string_content string_end binary_operator string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier if_statement attribute attribute identifier identifier identifier block expression_statement augmented_assignment attribute identifier identifier 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 else_clause block expression_statement augmented_assignment attribute identifier identifier 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 expression_statement augmented_assignment attribute identifier identifier list string string_start string_content string_end binary_operator string string_start string_content string_end attribute attribute identifier identifier identifier return_statement identifier | connect to the remote host |
def requirements():
requirements_list = []
with open('requirements.txt') as requirements:
for install in requirements:
requirements_list.append(install.strip())
return requirements_list | module function_definition identifier parameters block expression_statement assignment identifier list with_statement with_clause with_item as_pattern call identifier argument_list string string_start string_content string_end as_pattern_target identifier block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list return_statement identifier | Build the requirements list for this project |
def create_dataset_file(root_dir, data):
file_path = os.path.join(root_dir, '{dataset_type}', '{dataset_name}.py')
context = (
_HEADER + _DATASET_DEFAULT_IMPORTS + _CITATION
+ _DESCRIPTION + _DATASET_DEFAULTS
)
with gfile.GFile(file_path.format(**data), 'w') as f:
f.write(context.format(**data)) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier parenthesized_expression binary_operator binary_operator binary_operator binary_operator identifier identifier identifier identifier identifier with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list call attribute identifier identifier argument_list dictionary_splat identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list dictionary_splat identifier | Create a new dataset from a template. |
def _return_samples(return_type, samples):
if return_type.lower() == "dataframe":
if HAS_PANDAS:
return pandas.DataFrame.from_records(samples)
else:
warn("Pandas installation not found. Returning numpy.recarray object")
return samples
else:
return samples | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end block if_statement identifier block return_statement call attribute attribute identifier identifier identifier argument_list identifier else_clause block expression_statement call identifier argument_list string string_start string_content string_end return_statement identifier else_clause block return_statement identifier | A utility function to return samples according to type |
def mset_list(item, index, value):
'set mulitple items via index of int, slice or list'
if isinstance(index, (int, slice)):
item[index] = value
else:
map(item.__setitem__, index, value) | module function_definition identifier parameters identifier identifier identifier block expression_statement string string_start string_content string_end if_statement call identifier argument_list identifier tuple identifier identifier block expression_statement assignment subscript identifier identifier identifier else_clause block expression_statement call identifier argument_list attribute identifier identifier identifier identifier | set mulitple items via index of int, slice or list |
def coinbase_tx(cls, public_key_sec, coin_value, coinbase_bytes=b'', version=1, lock_time=0):
tx_in = cls.TxIn.coinbase_tx_in(script=coinbase_bytes)
COINBASE_SCRIPT_OUT = "%s OP_CHECKSIG"
script_text = COINBASE_SCRIPT_OUT % b2h(public_key_sec)
script_bin = BitcoinScriptTools.compile(script_text)
tx_out = cls.TxOut(coin_value, script_bin)
return cls(version, [tx_in], [tx_out], lock_time) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier string string_start string_end default_parameter identifier integer default_parameter identifier integer block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier binary_operator identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier return_statement call identifier argument_list identifier list identifier list identifier identifier | Create the special "first in block" transaction that includes the mining fees. |
def loads(self, string):
"Decompress the passed-in compact script and return the result."
script_class = self.get_script_class()
script = self._load(BytesIO(string), self._protocol, self._version)
return script_class(script) | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier attribute identifier identifier attribute identifier identifier return_statement call identifier argument_list identifier | Decompress the passed-in compact script and return the result. |
def __update_keyboard(self, milliseconds):
if Ragnarok.get_world().Keyboard.is_clicked(self.move_up_button):
self.move_up()
elif Ragnarok.get_world().Keyboard.is_clicked(self.move_down_button):
self.move_down()
elif Ragnarok.get_world().Keyboard.is_clicked(self.select_button):
self.gui_buttons[self.current_index].clicked_action()
for button in self.gui_buttons:
button.update(milliseconds) | module function_definition identifier parameters identifier identifier block if_statement call attribute attribute call attribute identifier identifier argument_list identifier identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list elif_clause call attribute attribute call attribute identifier identifier argument_list identifier identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list elif_clause call attribute attribute call attribute identifier identifier argument_list identifier identifier argument_list attribute identifier identifier block expression_statement call attribute subscript attribute identifier identifier attribute identifier identifier identifier argument_list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier | Use the keyboard to control selection of the buttons. |
def timesteps(self, horizon: int) -> tf.Tensor:
start, limit, delta = horizon - 1, -1, -1
timesteps_range = tf.range(start, limit, delta, dtype=tf.float32)
timesteps_range = tf.expand_dims(timesteps_range, -1)
batch_timesteps = tf.stack([timesteps_range] * self.batch_size)
return batch_timesteps | module function_definition identifier parameters identifier typed_parameter identifier type identifier type attribute identifier identifier block expression_statement assignment pattern_list identifier identifier identifier expression_list binary_operator identifier integer unary_operator integer unary_operator integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier unary_operator integer expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator list identifier attribute identifier identifier return_statement identifier | Returns the input tensor for the given `horizon`. |
def RetrieveIP4Info(self, ip):
if ip.is_private:
return (IPInfo.INTERNAL, "Internal IP address.")
try:
res = socket.getnameinfo((str(ip), 0), socket.NI_NAMEREQD)
return (IPInfo.EXTERNAL, res[0])
except (socket.error, socket.herror, socket.gaierror):
return (IPInfo.EXTERNAL, "Unknown IP address.") | module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block return_statement tuple attribute identifier identifier string string_start string_content string_end try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list tuple call identifier argument_list identifier integer attribute identifier identifier return_statement tuple attribute identifier identifier subscript identifier integer except_clause tuple attribute identifier identifier attribute identifier identifier attribute identifier identifier block return_statement tuple attribute identifier identifier string string_start string_content string_end | Retrieves information for an IP4 address. |
def remove_phenotype(self, ind_obj, phenotypes=None):
if phenotypes is None:
logger.info("delete all phenotypes related to %s", ind_obj.ind_id)
self.query(PhenotypeTerm).filter_by(ind_id=ind_obj.id).delete()
else:
for term in ind_obj.phenotypes:
if term.phenotype_id in phenotypes:
logger.info("delete phenotype: %s from %s",
term.phenotype_id, ind_obj.ind_id)
self.session.delete(term)
logger.debug('persist removals')
self.save()
for case_obj in ind_obj.cases:
self.update_hpolist(case_obj) | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call attribute call attribute call attribute identifier identifier argument_list identifier identifier argument_list keyword_argument identifier attribute identifier identifier identifier argument_list else_clause block for_statement identifier attribute identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier | Remove multiple phenotypes from an individual. |
def wp_loop(self):
loader = self.wploader
if loader.count() < 2:
print("Not enough waypoints (%u)" % loader.count())
return
wp = loader.wp(loader.count()-2)
if wp.command == mavutil.mavlink.MAV_CMD_DO_JUMP:
print("Mission is already looped")
return
wp = mavutil.mavlink.MAVLink_mission_item_message(0, 0, 0, 0, mavutil.mavlink.MAV_CMD_DO_JUMP,
0, 1, 1, -1, 0, 0, 0, 0, 0)
loader.add(wp)
self.loading_waypoints = True
self.loading_waypoint_lasttime = time.time()
self.master.waypoint_count_send(self.wploader.count())
print("Closed loop on mission") | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator call attribute identifier identifier argument_list integer block expression_statement call identifier argument_list binary_operator string string_start string_content string_end call attribute identifier identifier argument_list return_statement expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator call attribute identifier identifier argument_list integer if_statement comparison_operator attribute identifier identifier attribute attribute identifier identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end return_statement expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list integer integer integer integer attribute attribute identifier identifier identifier integer integer integer unary_operator integer integer integer integer integer integer expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier true expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list expression_statement call identifier argument_list string string_start string_content string_end | close the loop on a mission |
def stream(self, sha):
hexsha, typename, size, stream = self._git.stream_object_data(bin_to_hex(sha))
return OStream(hex_to_bin(hexsha), typename, size, stream) | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier identifier identifier call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier return_statement call identifier argument_list call identifier argument_list identifier identifier identifier identifier | For now, all lookup is done by git itself |
def _cm_handle_canonical_id(canonical_id, current_id, cloud_type):
devices = GCMDevice.objects.filter(cloud_message_type=cloud_type)
if devices.filter(registration_id=canonical_id, active=True).exists():
devices.filter(registration_id=current_id).update(active=False)
else:
devices.filter(registration_id=current_id).update(registration_id=canonical_id) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier if_statement call attribute call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier true identifier argument_list block expression_statement call attribute call attribute identifier identifier argument_list keyword_argument identifier identifier identifier argument_list keyword_argument identifier false else_clause block expression_statement call attribute call attribute identifier identifier argument_list keyword_argument identifier identifier identifier argument_list keyword_argument identifier identifier | Handle situation when FCM server response contains canonical ID |
def authenticate(self, username=None, password=None, **kwargs):
try:
user = get_user_model().objects.filter(Q(username=username)|Q(email=username))[0]
if check_password(password, user.password):
return user
else:
return None
except Exception as e:
return None | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none dictionary_splat_pattern identifier block try_statement block expression_statement assignment identifier subscript call attribute attribute call identifier argument_list identifier identifier argument_list binary_operator call identifier argument_list keyword_argument identifier identifier call identifier argument_list keyword_argument identifier identifier integer if_statement call identifier argument_list identifier attribute identifier identifier block return_statement identifier else_clause block return_statement none except_clause as_pattern identifier as_pattern_target identifier block return_statement none | Allow users to log in with their email address or username. |
def read(self):
assert os.path.isfile(self.file_path), 'No such file exists: ' + str(self.file_path)
with open(self.file_path, 'r') as f:
reader = csv_builtin.reader(f)
loaded_data = list(reader)
return juggle_types(loaded_data) | module function_definition identifier parameters identifier block assert_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier binary_operator string string_start string_content string_end call identifier argument_list attribute identifier identifier with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier return_statement call identifier argument_list identifier | Reads CSV file and returns list of contents |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.