code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def _settings_from_args(self, args):
if not args:
return {}
from_args = {}
if args.yes:
from_args['require_confirmation'] = not args.yes
if args.debug:
from_args['debug'] = args.debug
if args.repeat:
from_args['repeat'] = args.repea... | module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block return_statement dictionary expression_statement assignment identifier dictionary if_statement attribute identifier identifier block expression_statement assignment subscript identifier string string_... | Loads settings from args. |
def request_set_sensor_inactive(self, req, sensor_name):
sensor = self.get_sensor(sensor_name)
ts, status, value = sensor.read()
sensor.set_value(value, sensor.INACTIVE, ts)
return('ok',) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_lis... | Set sensor status to inactive |
def _connect(self, database=None):
conn_args = {
'host': self.config['host'],
'user': self.config['user'],
'password': self.config['password'],
'port': self.config['port'],
'sslmode': self.config['sslmode'],
}
if database:
c... | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier dictionary pair string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end pair string string_start st... | Connect to given database |
def feature_union(names, steps, weights):
steps, times = zip(*map(_maybe_timed, steps))
fit_time = sum(times)
if any(s is FIT_FAILURE for s in steps):
fit_est = FIT_FAILURE
else:
fit_est = FeatureUnion(list(zip(names, steps)), transformer_weights=weights)
return fit_est, fit_time | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list list_splat call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list... | Reconstruct a FeatureUnion from names, steps, and weights |
def reset_config_files():
print("*** Reset Spyder settings to defaults ***", file=STDERR)
for fname in SAVED_CONFIG_FILES:
cfg_fname = get_conf_path(fname)
if osp.isfile(cfg_fname) or osp.islink(cfg_fname):
os.remove(cfg_fname)
elif osp.isdir(cfg_fname):
sh... | module function_definition identifier parameters block expression_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_... | Remove all config files |
def add_auth (self, user=None, password=None, pattern=None):
if not user or not pattern:
log.warn(LOG_CHECK,
_("missing user or URL pattern in authentication data."))
return
entry = dict(
user=user,
password=password,
pattern=re.com... | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block if_statement boolean_operator not_operator identifier not_operator identifier block expression_statement call attribute identifier identifier argument_l... | Add given authentication data. |
def _change_bios_setting(self, properties):
keys = properties.keys()
headers, bios_uri, settings = self._check_bios_resource(keys)
if not self._operation_allowed(headers, 'PATCH'):
headers, bios_uri, _ = self._get_bios_settings_resource(settings)
self._validate_if_patch_s... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list identifier if_statem... | Change the bios settings to specified values. |
def rows(self) -> List[List[str]]:
return [list(d.values()) for d in self.data] | module function_definition identifier parameters identifier type generic_type identifier type_parameter type generic_type identifier type_parameter type identifier block return_statement list_comprehension call identifier argument_list call attribute identifier identifier argument_list for_in_clause identifier attribut... | Returns the table rows. |
def print_virt_table(self, data):
table = prettytable.PrettyTable()
keys = sorted(data.keys())
table.add_column('Keys', keys)
table.add_column('Values', [data.get(i) for i in keys])
for tbl in table.align.keys():
table.align[tbl] = 'l'
self.printer(table) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement call... | Print a vertical pretty table from data. |
def _get_uri(self):
if not self.service.exists():
logging.warning("Service does not yet exist.")
return self.service.settings.data['uri'] | module function_definition identifier parameters identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement subscript attri... | Will return the uri for an existing instance. |
def _get_bandfile(self, **options):
path = self.bandfilenames[self.bandname]
if not os.path.exists(path):
raise IOError("Couldn't find an existing file for this band ({band}): {path}".format(
band=self.bandname, path=path))
self.filename = path
return | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier subscript attribute identifier identifier attribute identifier identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list ide... | Get the VIIRS rsr filename |
def _read_atlas_zonefile( zonefile_path, zonefile_hash ):
with open(zonefile_path, "rb") as f:
data = f.read()
if zonefile_hash is not None:
if not verify_zonefile( data, zonefile_hash ):
log.debug("Corrupt zonefile '%s'" % zonefile_hash)
return None
return data | module function_definition identifier parameters identifier 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 iden... | Read and verify an atlas zone file |
def normalize(input, case_mapping=protocol.DEFAULT_CASE_MAPPING):
if case_mapping not in protocol.CASE_MAPPINGS:
raise pydle.protocol.ProtocolViolation('Unknown case mapping ({})'.format(case_mapping))
input = input.lower()
if case_mapping in ('rfc1459', 'rfc1459-strict'):
input = input.repl... | module function_definition identifier parameters identifier default_parameter identifier attribute identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block raise_statement call attribute attribute identifier identifier identifier argument_list call attribute string s... | Normalize input according to case mapping. |
def _transform_result(self, result):
if self._transform_func:
result = self._transform_func(result)
return result or None | module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement boolean_operator identifier none | Calls transform function on result. |
def _is_playlist_in_config_dir(self):
if path.dirname(self.stations_file) == self.stations_dir:
self.foreign_file = False
self.foreign_filename_only_no_extension = ''
else:
self.foreign_file = True
self.foreign_filename_only_no_extension = self.stations_fi... | module function_definition identifier parameters identifier block if_statement comparison_operator call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier false expression_statement assignmen... | Check if a csv file is in the config dir |
def ip_cmd(self, name):
if not self.container_exists(name=name):
exit('Unknown container {0}'.format(name))
ip = self.get_container_ip(name)
if not ip:
exit("Failed to get network address for"
" container {0}".format(name))
else:
echo(... | module function_definition identifier parameters identifier identifier block if_statement not_operator call attribute identifier identifier argument_list keyword_argument identifier identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifie... | Print ip of given container |
def _write_branch_and_tag_to_meta_yaml(self):
with open(self.meta_yaml.replace("meta", "template"), 'r') as infile:
dat = infile.read()
newdat = dat.format(**{'tag': self.tag, 'branch': self.branch})
with open(self.meta_yaml, 'w') as outfile:
outfile.write(newdat) | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end string strin... | Write branch and tag to meta.yaml by editing in place |
def delete(self, item, dry_run=None):
return self.backend.delete(item, dry_run=dry_run) | module function_definition identifier parameters identifier identifier default_parameter identifier none block return_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier | Delete an item in backend. |
def do_move_to(self, element, decl, pseudo):
target = serialize(decl.value).strip()
step = self.state[self.state['current_step']]
elem = self.current_target().tree
actions = step['actions']
for pos, action in enumerate(reversed(actions)):
if action[0] == 'move' and ac... | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list attribute identifier identifier identifier argument_list expression_statement assignment identifier subscript attribute identifier id... | Implement move-to declaration. |
def _update_record(self, identifier=None, rtype=None, name=None, content=None):
return self._change_record_sets('UPSERT', rtype, name, content) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block return_statement call attribute identifier identifier argument_list string string_start string_content string_end iden... | Update a record from the hosted zone. |
def format(self, record):
for key in ('instance', 'color'):
if key not in record.__dict__:
record.__dict__[key] = ''
if record.__dict__.get('request_id', None):
self._fmt = CONF.logging_context_format_string
else:
self._fmt = CONF.logging_defau... | module function_definition identifier parameters identifier identifier block for_statement identifier tuple string string_start string_content string_end string string_start string_content string_end block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment ... | Uses contextstring if request_id is set, otherwise default. |
def noglobals(fn):
return type(fn)(
getattr(fn, 'func_code', getattr(fn, '__code__')),
{'__builtins__': builtins},
getattr(fn, 'func_name', getattr(fn, '__name__')),
getattr(fn, 'func_defaults', getattr(fn, '__defaults__')),
getattr(fn, 'func_closure', getattr(fn, '__closure_... | module function_definition identifier parameters identifier block return_statement call call identifier argument_list identifier argument_list call identifier argument_list identifier string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end dic... | decorator for functions that dont get access to globals |
def listen(identifier):
context = Context()
process = WebProcess(identifier)
context.spawn(process)
log.info("Launching PID %s", process.pid)
return process, context | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_sta... | Launch a listener and return the compactor context. |
def mods(self, uuid):
picker = lambda x: x.get('mods', {})
return self._get(('mods', uuid), picker) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier lambda lambda_parameters identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary return_statement call attribute identifier identifier ar... | Return a mods record for a given uuid |
def asset_path(cls, organization, asset):
return google.api_core.path_template.expand(
"organizations/{organization}/assets/{asset}",
organization=organization,
asset=asset,
) | module function_definition identifier parameters identifier identifier identifier block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifie... | Return a fully-qualified asset string. |
def width_rect_weir(FlowRate, Height):
ut.check_range([FlowRate, ">0", "Flow rate"], [Height, ">0", "Height"])
return ((3 / 2) * FlowRate
/ (con.VC_ORIFICE_RATIO * np.sqrt(2 * gravity.magnitude) * Height ** (3 / 2))
) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list list identifier string string_start string_content string_end string string_start string_content string_end list identifier string string_start string_content string_end s... | Return the width of a rectangular weir. |
def _initialize_counters(model_class, name, bases, attrs):
model_class._counters = []
for k, v in attrs.iteritems():
if isinstance(v, Counter):
model_class._counters.append(k) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment attribute identifier identifier list for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement call identifier argument_list ide... | Stores the list of counter fields. |
def mkdir_recursive(dirname):
parent = os.path.dirname(dirname)
if parent != "":
if not os.path.exists(parent):
mkdir_recursive(parent)
if not os.path.exists(dirname):
os.mkdir(dirname)
elif not os.path.exists(dirname):
os.mkdir(dirname) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier string string_start string_end block if_statement not_operator call attribute attrib... | makes all the directories along a given path, if they do not exist |
def strip_magics(source):
filtered=[]
for line in source.splitlines():
if not line.startswith('%') or line.startswith('%%'):
filtered.append(line)
return '\n'.join(filtered) | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list block if_statement boolean_operator not_operator call attribute identifier identifier argument_list string string_start string_con... | Given the source of a cell, filter out all cell and line magics. |
def _clean_alignment(args):
logger.info("Clean bam file with highly repetitive reads with low counts. sum(counts)/n_hits > 1%")
bam_file, seq_obj = clean_bam_file(args.afile, args.mask)
logger.info("Using %s file" % bam_file)
detect_complexity(bam_file, args.ref, args.out)
return bam_file, seq_obj | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment pattern_list identifier identifier call identifier argument_list attribute identifier identifier attribu... | Prepare alignment for cluster detection. |
def lock(resources, *args, **kwargs):
if not resources:
client = redis.Redis(decode_responses=True, **kwargs)
resources = find_resources(client)
if not resources:
return
locker = Locker(**kwargs)
while len(resources) > 1:
pid = os.fork()
resources = resources[:1] ... | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier true dictionary_splat i... | Lock resources from the command line, for example for maintenance. |
def _prepend_name(self, prefix, dict_):
return dict(['.'.join([prefix, name]), msg]
for name, msg in dict_.iteritems()) | module function_definition identifier parameters identifier identifier identifier block return_statement call identifier generator_expression list call attribute string string_start string_content string_end identifier argument_list list identifier identifier identifier for_in_clause pattern_list identifier identifier ... | changes the keys of the dictionary prepending them with "name." |
def read_files(*filenames):
output = []
for filename in filenames:
f = codecs.open(filename, encoding='utf-8')
try:
output.append(f.read())
finally:
f.close()
return '\n\n'.join(output) | module function_definition identifier parameters list_splat_pattern identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier string strin... | Output the contents of one or more files to a single concatenated string. |
def endElement(self, name):
if self.current:
obj = self.current
else:
text = ''.join(self.chardata).strip()
obj = self._parse_node_data(text)
newcurrent, self.chardata = self.stack.pop()
self.current = self._element_to_node(newcurrent, name, obj) | module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier call attribute call attribute string string_start string... | End current xml element, parse and add to to parent node. |
def _populate_common_request(self, request):
url_record = self._item_session.url_record
if url_record.parent_url and not request.fields.get('Referer'):
self._add_referrer(request, url_record)
if self._fetch_rule.http_login:
request.username, request.password = self._fetch... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement boolean_operator attribute identifier identifier not_operator call attribute attribute identifier identifier identifier argument_list ... | Populate the Request with common fields. |
def variant(self):
variant = current_app.config['THEME_VARIANT']
if variant not in self.variants:
log.warning('Unkown theme variant: %s', variant)
return 'default'
else:
return variant | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute ident... | Get the current theme variant |
def merge_contextual(self, other):
for k in self.keys():
for item in self[k]:
for other_item in other.get(k, []):
if isinstance(other_item, six.text_type):
continue
for otherk in other_item.keys():
... | module function_definition identifier parameters identifier identifier block for_statement identifier call attribute identifier identifier argument_list block for_statement identifier subscript identifier identifier block for_statement identifier call attribute identifier identifier argument_list identifier list block ... | Merge in contextual info from a template Compound. |
def out(msg, error=False):
" Send message to shell "
pipe = stdout
if error:
pipe = stderr
msg = color_msg(msg, "warning")
pipe.write("%s\n" % msg) | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement string string_start string_content string_end expression_statement assignment identifier identifier if_statement identifier block expression_statement assignment identifier identifier expression_sta... | Send message to shell |
def getfunc(obj, name=''):
if name:
obj = getattr(obj, name)
return getattr(obj, '__func__', obj) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_end block if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier identifier return_statement call identifier argument_list identifier string stri... | Get the function corresponding to name from obj, not the method. |
def BackwardsReader(file, BLKSIZE = 4096):
buf = ""
file.seek(0, 2)
lastchar = file.read(1)
trailing_newline = (lastchar == "\n")
while 1:
newline_pos = buf.rfind("\n")
pos = file.tell()
if newline_pos != -1:
line = buf[newline_pos+1:]
buf = buf[:newli... | module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier string string_start string_end expression_statement call attribute identifier identifier argument_list integer integer expression_statement assignment identifier call attribu... | Read a file line by line, backwards |
def __check_logging_rules(configuration):
valid_log_levels = [
'debug',
'info',
'warning',
'error'
]
if configuration['logging']['log_level'].lower() not in valid_log_levels:
print('Log level must be one of {0}'.format(
', '.join(valid_log_levels)))
... | module function_definition identifier parameters identifier block expression_statement assignment 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 if_statement compariso... | Check that the logging values are proper |
def commit_pushdb(self, coordinates, postscript=None):
self.scm.commit('pants build committing publish data for push of {coordinates}'
'{postscript}'.format(coordinates=coordinates, postscript=postscript or ''),
verify=self.get_options().verify_commit) | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content ... | Commit changes to the pushdb with a message containing the provided coordinates. |
def todict(self):
dict_entry = []
for k,v in self.items():
if isinstance(v, ConfigTree):
dict_entry.append((k, v.todict()))
else:
dict_entry.append((k, v))
return dict(dict_entry) | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement call identifier argument_list identifier identifier block expression_statement call att... | Convert this node to a dictionary tree. |
def getConfiguration(self):
configuration = c_int()
mayRaiseUSBError(libusb1.libusb_get_configuration(
self.__handle, byref(configuration),
))
return configuration.value | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement call identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier call identifier argument_list identifier return... | Get the current configuration number for this device. |
def q_limited(self):
if (self.q >= self.q_max) or (self.q <= self.q_min):
return True
else:
return False | module function_definition identifier parameters identifier block if_statement boolean_operator parenthesized_expression comparison_operator attribute identifier identifier attribute identifier identifier parenthesized_expression comparison_operator attribute identifier identifier attribute identifier identifier block ... | Is the machine at it's limit of reactive power? |
def collapse(self, id_user):
c = CmtCOLLAPSED(id_bibrec=self.id_bibrec, id_cmtRECORDCOMMENT=self.id,
id_user=id_user)
db.session.add(c)
db.session.commit() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier expression_... | Collapse comment beloging to user. |
def relabel(self, change):
"Relabel images by moving from parent dir with old label `class_old` to parent dir with new label `class_new`."
class_new,class_old,file_path = change.new,change.old,change.owner.file_path
fp = Path(file_path)
parent = fp.parents[1]
self._csv_dict[fp] =... | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment pattern_list identifier identifier identifier expression_list attribute identifier identifier attribute identifier identifier attribute attribut... | Relabel images by moving from parent dir with old label `class_old` to parent dir with new label `class_new`. |
def build_intent(self, intent_name):
is_fallback = self.assist._intent_fallbacks[intent_name]
contexts = self.assist._required_contexts[intent_name]
events = self.assist._intent_events[intent_name]
new_intent = Intent(intent_name, fallback_intent=is_fallback, contexts=contexts, events=ev... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript attribute attribute identifier identifier identifier identifier expression_statement assignment identifier subscript attribute attribute identifier identifier identifier identifier expressio... | Builds an Intent object of the given name |
def _looks_like_functools_member(node, member):
if isinstance(node.func, astroid.Name):
return node.func.name == member
elif isinstance(node.func, astroid.Attribute):
return (
node.func.attrname == member
and isinstance(node.func.expr, astroid.Name)
and node.f... | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list attribute identifier identifier attribute identifier identifier block return_statement comparison_operator attribute attribute identifier identifier identifier identifier elif_clause call identifier a... | Check if the given Call node is a functools.partial call |
def finalize(self):
self.set_title(
'{} Manifold (fit in {:0.2f} seconds)'.format(
self._name, self.fit_time_.interval
)
)
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
if self._target_color_type == DISCRETE:
manual_le... | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier expression_... | Add title and modify axes to make the image ready for display. |
def as_string(self, chars, show_leaf=True, current_linkable=False, class_current="active_link"):
return self.__do_menu("as_string", show_leaf, current_linkable, class_current, chars) | module function_definition identifier parameters identifier identifier default_parameter identifier true default_parameter identifier false default_parameter identifier string string_start string_content string_end block return_statement call attribute identifier identifier argument_list string string_start string_cont... | It returns breadcrumb as string |
def InterpolateValue(self,
value,
type_info_obj=type_info.String(),
default_section=None,
context=None):
if isinstance(value, Text):
try:
value = StringInterpolator(
value,
self,
... | module function_definition identifier parameters identifier identifier default_parameter identifier call attribute identifier identifier argument_list default_parameter identifier none default_parameter identifier none block if_statement call identifier argument_list identifier identifier block try_statement block expr... | Interpolate the value and parse it with the appropriate type. |
def node2bracket(docgraph, node_id, child_str=''):
node_attrs = docgraph.node[node_id]
if istoken(docgraph, node_id):
pos_str = node_attrs.get(docgraph.ns+':pos', '')
token_str = node_attrs[docgraph.ns+':token']
return u"({pos}{space1}{token}{space2}{child})".format(
pos=pos_... | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_end block expression_statement assignment identifier subscript attribute identifier identifier identifier if_statement call identifier argument_list identifier identifier block expression_state... | convert a docgraph node into a PTB-style string. |
def parse_s2bs(s2bs):
s2b = {}
for s in s2bs:
for line in open(s):
line = line.strip().split('\t')
s, b = line[0], line[1]
s2b[s] = b
return s2b | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement identifier identifier block for_statement identifier call identifier argument_list identifier block expression_statement assignment identifier call attribute call attribute identifier id... | convert s2b files to dictionary |
def main(folder):
raw_datapath, outputpath, p_queue = get_parameters(folder)
create_preprocessed_dataset(raw_datapath, outputpath, p_queue)
utils.create_run_logfile(folder) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list identifier expression_statement call identifier argument_list identifier identifier identifier expression_statement call attribute identifier iden... | Main part of preprocess_dataset that glues things togeter. |
def clear(self):
node = self._first
while node is not None:
next_node = node._next
node._list = node._prev = node._next = None
node = next_node
self._size = 0 | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier while_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute iden... | Remove all nodes from the list. |
def apply(self):
self._old_config = {k: v for k, v in _config.items()}
self._apply() | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier dictionary_comprehension pair identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list expression_statement call attribute id... | Apply the current action to the current runtime configuration. |
def messageToFile(message):
outFile = StringIO()
messageGenerator = generator.Generator(outFile, False)
messageGenerator.flatten(message)
outFile.seek(0, 0)
return outFile | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier false expression_statement call attribute identifier identifier argument_lis... | Flattens a message into a file-like object. |
def dump_database(id):
tmp_dir = tempfile.mkdtemp()
current_dir = os.getcwd()
os.chdir(tmp_dir)
FNULL = open(os.devnull, "w")
heroku_app = HerokuApp(dallinger_uid=id, output=FNULL)
heroku_app.backup_capture()
heroku_app.backup_download()
for filename in os.listdir(tmp_dir):
if fi... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument... | Dump the database to a temporary directory. |
def process_row(cls, data, column_map):
row = {}
for key,value in data.iteritems():
if not value:
value = '-'
elif isinstance(value, list):
value = value[1]
elif isinstance(value, dict):
if 'type_name' in... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement not_operator identifier block expression_statement assignme... | Process the row data from Rekall |
def _add_hookimpl(self, hookimpl):
if hookimpl.hookwrapper:
methods = self._wrappers
else:
methods = self._nonwrappers
if hookimpl.trylast:
methods.insert(0, hookimpl)
elif hookimpl.tryfirst:
methods.append(hookimpl)
else:
... | module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier attribute identifier identifier if_statement attribute i... | Add an implementation to the callback chain. |
def runner(queue, parallel):
def run(fn_name, items):
logger.info("clusterk: %s" % fn_name)
assert "wrapper" in parallel, "Clusterk requires bcbio-nextgen-vm wrapper"
fn = getattr(__import__("{base}.clusterktasks".format(base=parallel["module"]),
fromlist=["cl... | module function_definition identifier parameters identifier identifier block function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier assert_statement comparison_... | Run individual jobs on an existing queue. |
def _ClientPathToString(client_path, prefix=""):
return os.path.join(prefix, client_path.client_id, client_path.vfs_path) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_end block return_statement call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier attribute identifier identifier | Returns a path-like String of client_path with optional prefix. |
def unique_slug_required(form, slug):
if hasattr(form, 'instance') and form.instance.id:
if Content.objects.exclude(page=form.instance).filter(
body=slug, type="slug").count():
raise forms.ValidationError(error_dict['another_page_error'])
elif Content.objects.filter(body=slug, ty... | module function_definition identifier parameters identifier identifier block if_statement boolean_operator call identifier argument_list identifier string string_start string_content string_end attribute attribute identifier identifier identifier block if_statement call attribute call attribute call attribute attribute... | Enforce a unique slug accross all pages and websistes. |
def delete(bad_entry):
entries = read()
kept_entries = [x for x in entries if x.rstrip() != bad_entry]
write(kept_entries) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause comparison_operator call attribute identifier identifier argum... | Removes an entry from rc file. |
def preprocessor(accepts, exports, flag=None):
def decorator(f):
preprocessors.append((accepts, exports, flag, f))
return f
return decorator | module function_definition identifier parameters identifier identifier default_parameter identifier none block function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list tuple identifier identifier identifier identifier return_statement identifier ... | Decorator to add a new preprocessor |
def _onMethodTimeout(self, serial, d):
del self._pendingCalls[serial]
d.errback(error.TimeOut('Method call timed out')) | module function_definition identifier parameters identifier identifier identifier block delete_statement subscript attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content stri... | Called when a remote method invocation timeout occurs |
def _site_users():
userlist = sudo("cat /etc/passwd | awk '/site/'").split('\n')
siteuserlist = [user.split(':')[0] for user in userlist if 'site_' in user]
return siteuserlist | module function_definition identifier parameters block expression_statement assignment identifier call attribute call identifier argument_list string string_start string_content string_end identifier argument_list string string_start string_content escape_sequence string_end expression_statement assignment identifier l... | Get a list of site_n users |
def reward(self):
raw_rewards, processed_rewards = 0, 0
for ts in self.time_steps:
if ts.raw_reward is not None:
raw_rewards += ts.raw_reward
if ts.processed_reward is not None:
processed_rewards += ts.processed_reward
return raw_rewards, processed_rewards | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier expression_list integer integer for_statement identifier attribute identifier identifier block if_statement comparison_operator attribute identifier identifier none block expression_state... | Returns a tuple of sum of raw and processed rewards. |
def find_parameter(self, name):
name = self.normalize_name(name)
arg = self.args.get(name)
return None if arg is None else arg.parameter | 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 attribute identifier identifier identifier argument_list identifier return_state... | Find parameter by name or normalized arg name. |
def get(self, roleId):
role = db.Role.find_one(Role.role_id == roleId)
if not role:
return self.make_response('No such role found', HTTP.NOT_FOUND)
return self.make_response({'role': role}) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list comparison_operator attribute identifier identifier identifier if_statement not_operator identifier block return_statement call ... | Get a specific role information |
def platform_versions(klass, account, **kwargs):
resource = klass.RESOURCE_OPTIONS + 'platform_versions'
request = Request(account.client, 'get', resource, params=kwargs)
return Cursor(None, request) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier binary_operator attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_li... | Returns a list of supported platform versions |
def dst(self, dt):
dst_start_date = self.first_sunday(dt.year, 3) + timedelta(days=7) \
+ timedelta(hours=2)
dst_end_date = self.first_sunday(dt.year, 11) + timedelta(hours=2)
if dst_start_date <= dt.replace(tzinfo=None) < dst_end_date:
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator binary_operator call attribute identifier identifier argument_list attribute identifier identifier integer call identifier argument_list keyword_argument identifier integer line_contin... | Calculate delta for daylight saving. |
def delMatch(self, rule_id):
rule = self.match_rules[rule_id]
d = self.callRemote(
'/org/freedesktop/DBus',
'RemoveMatch',
interface='org.freedesktop.DBus',
destination='org.freedesktop.DBus',
body=[rule],
signature='s',
)
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string ... | Removes a message matching rule previously registered with addMatch |
def convert_camel_case_string(name: str) -> str:
string = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", string).lower() | module function_definition identifier parameters typed_parameter identifier type identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier return_st... | Convert camel case string to snake case |
def namePush(ctxt, value):
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.namePush(ctxt__o, value)
return ret | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block expression_statement assignment identifier none else_clause block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call... | Pushes a new element name on top of the name stack |
def _format_tag_query(self, sampler, wmi_obj, tag_query):
try:
link_source_property = int(wmi_obj[tag_query[0]])
target_class = tag_query[1]
link_target_class_property = tag_query[2]
target_property = tag_query[3]
except IndexError:
self.log.er... | module function_definition identifier parameters identifier identifier identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list subscript identifier subscript identifier integer expression_statement assignment identifier subscript identifier integer expres... | Format `tag_query` or raise on incorrect parameters. |
def _get_values(profile=None):
profile = profile or {}
serializers = salt.loader.serializers(__opts__)
ret = {}
for fname in profile.get('files', []):
try:
with salt.utils.files.flopen(fname) as yamlfile:
contents = serializers.yaml.deserialize(yamlfile)
... | module function_definition identifier parameters default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier dictionary expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement as... | Retrieve all the referenced files, deserialize, then merge them together |
def _generate_read_callable(name, display_name, arguments, regex, doc, supported):
def f(self, *args, **kwargs):
url = self._generate_url(regex, args)
if 'params' in kwargs:
url += "?" + urllib.urlencode(kwargs['params'])
return self._get_data(url, accept=(kwargs.get('accept')))
... | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier ident... | Returns a callable which conjures the URL for the resource and GETs a response |
def reset(self):
if not self.chain_id:
return
saved, self.chain_id = self.chain_id, None
try:
self.call_no_reply(mitogen.core.Dispatcher.forget_chain, saved)
finally:
self.chain_id = saved | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block return_statement expression_statement assignment pattern_list identifier attribute identifier identifier expression_list attribute identifier identifier none try_statement block expression_s... | Instruct the target to forget any related exception. |
def make_auth_headers():
if not os.path.exists(".appveyor.token"):
raise RuntimeError(
"Please create a file named `.appveyor.token` in the current directory. "
"You can get the token from https://ci.appveyor.com/api-token"
)
with open(".appveyor.token") as f:
tok... | module function_definition identifier parameters block if_statement not_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end str... | Make the authentication headers needed to use the Appveyor API. |
def reset(self, name, suppress_logging=False):
self._close(name, suppress_logging)
self.get(name)
self.logger.info('Reset Flopsy Pool for {0}'.format(name)) | module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attri... | resets established connection by disconnecting and reconnecting |
def _add_ssl_info(self):
if self.scheme == u'https':
sock = self._get_ssl_sock()
if hasattr(sock, 'cipher'):
self.ssl_cert = sock.getpeercert()
else:
cert = sock.connection.get_peer_certificate()
self.ssl_cert = httputil.x509_to... | 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 call attribute identifier identifier argument_list if_statement call identifier argument_list ... | Add SSL cipher info. |
def _start(self):
self._enable_logpersist()
logcat_file_path = self._configs.output_file_path
if not logcat_file_path:
f_name = 'adblog,%s,%s.txt' % (self._ad.model,
self._ad._normalized_serial)
logcat_file_path = os.path.join(se... | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement not_operator identifier block expression_statement assignment identifier ... | The actual logic of starting logcat. |
def validate_query_params(self):
allowed_params = set(self.get_filters().keys())
allowed_params.update(self.get_always_allowed_arguments())
unallowed = set(self.request.query_params.keys()) - allowed_params
if unallowed:
msg = 'Unsupported parameter(s): {}. Please use a combi... | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call attribute call attribute identifier identifier argument_list identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute ide... | Ensure no unsupported query params were used. |
def new_connection(self):
if not self.prepared: self.prepare()
con = sqlite3.connect(self.path, isolation_level=self.isolation)
con.row_factory = self.factory
if self.text_fact: con.text_factory = self.text_fact
return con | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier ide... | Make a new connection. |
def _validate(self):
if not 0.0 <= self._min_percentile < self._max_percentile <= 100.0:
raise BadPercentileBounds(
min_percentile=self._min_percentile,
max_percentile=self._max_percentile,
upper_bound=100.0
)
return super(Percentil... | module function_definition identifier parameters identifier block if_statement not_operator comparison_operator float attribute identifier identifier attribute identifier identifier float block raise_statement call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument ide... | Ensure that our percentile bounds are well-formed. |
def show_address_scope(self, address_scope, **_params):
return self.get(self.address_scope_path % (address_scope),
params=_params) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list binary_operator attribute identifier identifier parenthesized_expression identifier keyword_argument identifier identifier | Fetches information of a certain address scope. |
def spawn_process(self, process=None):
if process is None:
return False
pid = fork()
if pid != 0:
process.pid = pid
self.PROCESSES[process.process_id] = process
connections.close_all()
return True
process.pid = getpid()
... | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block return_statement false expression_statement assignment identifier call identifier argument_list if_statement comparison_operator identifier integer block expression_... | spawn a new process |
def update_if_client(fctn):
@functools.wraps(fctn)
def _update_if_client(self, *args, **kwargs):
b = self._bundle
if b is None or not hasattr(b, 'is_client'):
return fctn(self, *args, **kwargs)
elif b.is_client and \
(b._last_client_update is None or
... | module function_definition identifier parameters identifier block decorated_definition decorator call attribute identifier identifier argument_list identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment iden... | Intercept and check updates from server if bundle is in client mode. |
def visit_Module(self, node):
self.generic_visit(node)
import_alias = ast.alias(name='itertools', asname=mangle('itertools'))
if self.use_itertools:
importIt = ast.Import(names=[import_alias])
node.body.insert(0, importIt)
return node | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content str... | Add itertools import for imap, izip or ifilter iterator. |
def get(self):
output = helm("get", self.release)
if output.returncode != 0:
print("Something went wrong!")
print(output.stderr)
else:
print(output.stdout) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end attribute identifier identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement cal... | Get specific information about this hub. |
def main():
version = 'Python Exist %s' % __version__
arguments = docopt(__doc__, version=version)
ExistCli(arguments) | module function_definition identifier parameters block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier expression_statement call ... | Parse the arguments and use them to create a ExistCli object |
def info_shell_scope(self):
Console.ok("{:>20} = {:}".format("ECHO", self.echo))
Console.ok("{:>20} = {:}".format("DEBUG", self.debug))
Console.ok("{:>20} = {:}".format("LOGLEVEL", self.loglevel))
Console.ok("{:>20} = {:}".format("SCOPE", self.active_scope))
Console.ok("{:>20} = ... | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list string string_start string_content string_end attribute identifier identifier expression_stateme... | prints some information about the shell scope |
def _inject_selenium(self, test):
from django.conf import settings
test_case = get_test_case_class(test)
test_case.selenium_plugin_started = True
sel = selenium(
getattr(settings, "SELENIUM_HOST", "localhost"),
int(getattr(settings, "SELENIUM_PORT", 4444)),
... | module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier true expression_... | Injects a selenium instance into the method. |
def to_rdmol(mol):
rwmol = Chem.RWMol(Chem.MolFromSmiles(''))
key_to_idx = {}
bond_type = {1: Chem.BondType.SINGLE,
2: Chem.BondType.DOUBLE,
3: Chem.BondType.TRIPLE}
conf = Chem.Conformer(rwmol.GetNumAtoms())
for k, a in mol.atoms_iter():
i = rwmol.AddAtom(C... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_end expression_statement assignment identifier dictionary expression_statement ass... | Convert molecule to RDMol |
def read(self, encoding=None):
encoding = encoding or ENCODING
try:
with codecs.open(self.path, encoding=encoding) as fi:
return fi.read()
except:
return None | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier identifier try_statement block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list attribute identifie... | Reads from the file and returns result as a string. |
def deep_force_unicode(value):
if isinstance(value, (list, tuple, set)):
value = type(value)(map(deep_force_unicode, value))
elif isinstance(value, dict):
value = type(value)(map(deep_force_unicode, value.items()))
elif isinstance(value, Promise):
value = force_text(value)
return... | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier tuple identifier identifier identifier block expression_statement assignment identifier call call identifier argument_list identifier argument_list call identifier argument_list identifier identifier ... | Recursively call force_text on value. |
def use_isolated_bank_view(self):
self._bank_view = ISOLATED
for session in self._get_provider_sessions():
try:
session.use_isolated_bank_view()
except AttributeError:
pass | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier identifier for_statement identifier call attribute identifier identifier argument_list block try_statement block expression_statement call attribute identifier identifier argument_list excep... | Pass through to provider ItemLookupSession.use_isolated_bank_view |
def generate_requirements_files(self, base_dir='.'):
print("Creating requirements files\n")
shared = self._get_shared_section()
requirements_dir = self._make_requirements_directory(base_dir)
for section in self.config.sections():
if section == 'metadata':
cont... | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement call identifier argument_list string string_start string_content escape_sequence string_end expression_statement assignment identifier call attribute identifi... | Generate set of requirements files for config |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.