code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def _filter_file(src, dest, subst):
substre = re.compile(r'\$(%s)' % '|'.join(subst.keys()))
def repl(m):
return subst[m.group(1)]
with open(src, "rt") as sf, open(dest, "wt") as df:
while True:
l = sf.readline()
if not l:
break
df.write(re... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argu... | Copy src to dest doing substitutions on the fly. |
def stop_host(self, config_file):
res = self.send_json_request('host/stop', data={'config': config_file})
if res.status_code != 200:
raise UnexpectedResponse(
'Attempted to stop a JSHost. Response: {res_code}: {res_text}'.format(
res_code=res.status_code,
... | 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 keyword_argument identifier dictionary pair string string_start string_content string_end identifier if... | Stops a managed host specified by `config_file`. |
def to_dict(self):
material = {'Data1': self.Data1,
'Data2': self.Data2,
'Data3': self.Data3,
'Data4': list(self.Data4)
}
return {'material':material,
'length': self.length,
'instanceHigh': se... | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_co... | MobID representation as dict |
def handle_bad_update(operation, ret):
print("Error " + operation)
sys.exit('Return code: ' + str(ret.status_code) + ' Error: ' + ret.text) | module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list binary_operator binary_operator binary_operator... | report error for bad update |
def handle_data(self, data):
if data:
inTag = self._inTag
if len(inTag) > 0:
if inTag[-1].tagName not in PRESERVE_CONTENTS_TAGS:
data = data.replace('\t', ' ').strip('\r\n')
if data.startswith(' '):
data = ' ... | module function_definition identifier parameters identifier identifier block if_statement identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block if_statement comparison_operator attribute subscri... | handle_data - Internal for parsing |
def _get_init_args(self):
args = {}
for rop in self.ro_properties:
if rop in self.properties:
args[rop] = self.properties[rop]
return args | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement identifier attribute identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment subscript identifier id... | Creates dict with properties marked as readonly |
def extract_log_level_from_environment(k, default):
return LOG_LEVELS.get(os.environ.get(k)) or int(os.environ.get(k, default)) | module function_definition identifier parameters identifier identifier block return_statement boolean_operator call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier call identifier argument_list call attribute attribute identifier identifie... | Gets the log level from the environment variable. |
def int_to_bytes(i, minlen=1, order='big'):
blen = max(minlen, PGPObject.int_byte_len(i), 1)
if six.PY2:
r = iter(_ * 8 for _ in (range(blen) if order == 'little' else range(blen - 1, -1, -1)))
return bytes(bytearray((i >> c) & 0xff for c in r))
return i.to_bytes(blen, or... | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier call attribute identifier identifier argument_list identif... | convert integer to bytes |
def tospark(self, engine=None):
from thunder.series.readers import fromarray
if self.mode == 'spark':
logging.getLogger('thunder').warn('images already in local mode')
pass
if engine is None:
raise ValueError('Must provide SparkContext')
return fromarr... | module function_definition identifier parameters identifier default_parameter identifier none block import_from_statement dotted_name identifier identifier identifier dotted_name identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_st... | Convert to spark mode. |
def _update(self, dct):
LOG.info('%r._update(%r, %r)', self, self.job_id, dct)
dct.setdefault('ansible_job_id', self.job_id)
dct.setdefault('data', '')
fp = open(self.path + '.tmp', 'w')
try:
fp.write(json.dumps(dct))
finally:
fp.close()
os... | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list... | Update an async job status file. |
def del_key(self, key, key_to_delete):
"Delete the `key_to_delete` for the record found with `key`."
v = self.get(key)
if key_to_delete in v:
del v[key_to_delete]
self.set(key, v) | module function_definition identifier parameters identifier identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier identifier block... | Delete the `key_to_delete` for the record found with `key`. |
def _ConvertFloat(value):
if value == 'nan':
raise ParseError('Couldn\'t parse float "nan", use "NaN" instead.')
try:
return float(value)
except ValueError:
if value == _NEG_INFINITY:
return float('-inf')
elif value == _INFINITY:
return float('inf')
elif value == _NAN:
return... | module function_definition identifier parameters identifier block if_statement comparison_operator identifier string string_start string_content string_end block raise_statement call identifier argument_list string string_start string_content escape_sequence string_end try_statement block return_statement call identifi... | Convert an floating point number. |
def input_entity(self):
if not self._input_entity:
try:
self._input_entity = self._client._entity_cache[self._peer]
except KeyError:
pass
return self._input_entity | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block try_statement block expression_statement assignment attribute identifier identifier subscript attribute attribute identifier identifier identifier attribute identifier identifier except_clau... | Input version of the entity. |
def infoObject(object, cat, format, *args):
doLog(INFO, object, cat, format, args) | module function_definition identifier parameters identifier identifier identifier list_splat_pattern identifier block expression_statement call identifier argument_list identifier identifier identifier identifier identifier | Log an informational message in the given category. |
def assure_migrations_table_setup(db):
from mig.models import MigrationData
if not MigrationData.__table__.exists(db.bind):
MigrationData.metadata.create_all(
db.bind, tables=[MigrationData.__table__]) | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier dotted_name identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block expression_statement call attribute att... | Make sure the migrations table is set up in the database. |
def breadcrumb_raw_safe(context, label, viewname, *args, **kwargs):
append_breadcrumb(context, label, viewname, args, kwargs)
return '' | module function_definition identifier parameters identifier identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call identifier argument_list identifier identifier identifier identifier identifier return_statement string string_start string_end | Same as breadcrumb but label is not escaped and translated. |
def new_as_dict(self, raw=True, vars=None):
result = {}
for section in self.sections():
if section not in result:
result[section] = {}
for option in self.options(section):
value = self.get(section, option, raw=raw, vars=vars)
try:
value = cherr... | module function_definition identifier parameters identifier default_parameter identifier true default_parameter identifier none block expression_statement assignment identifier dictionary for_statement identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier identi... | Convert an INI file to a dictionary |
def _generate_cpu_stats():
cpu_name = urwid.Text("CPU Name N/A", align="center")
try:
cpu_name = urwid.Text(get_processor_name().strip(), align="center")
except OSError:
logging.info("CPU name not available")
return [urwid.Text(('bold text', "CPU Detected"),
... | module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end try_statement block expression_statement assignment... | Read and display processor name |
def compare_view(self, request, object_id, version_id, extra_context=None):
opts = self.model._meta
object_id = unquote(object_id)
current = Version.objects.get_for_object_reference(self.model, object_id)[0]
revision = Version.objects.get_for_object_reference(self.model, object_id).filte... | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier express... | Actually compare two versions. |
def update(self, ptime):
delta = self.delta + ptime
total_duration = self.delay + self.duration
if delta > total_duration:
delta = total_duration
if delta < self.delay:
pass
elif delta == total_duration:
for key, tweenable in self.tweenables:
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator attribute identifier identifier identifier expression_statement assignment identifier binary_operator attribute identifier identifier attribute identifier identifier if_statement compa... | Update tween with the time since the last frame |
def tfidf_weight(X):
X = coo_matrix(X)
N = float(X.shape[0])
idf = log(N) - log1p(bincount(X.col))
X.data = sqrt(X.data) * idf[X.col]
return X | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list subscript attribute identifier identifier integer expression_statement assignment identifier bina... | Weights a Sparse Matrix by TF-IDF Weighted |
def _split_match_steps_into_match_traversals(match_steps):
output = []
current_list = None
for step in match_steps:
if isinstance(step.root_block, QueryRoot):
if current_list is not None:
output.append(current_list)
current_list = [step]
else:
... | module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier none for_statement identifier identifier block if_statement call identifier argument_list attribute identifier identifier identifier block if_statement comparison_... | Split a list of MatchSteps into multiple lists, each denoting a single MATCH traversal. |
def full_address(self):
addr = ""
if self.house_number:
addr = addr + self.house_number
if self.street_prefix:
addr = addr + " " + self.street_prefix
if self.street:
addr = addr + " " + self.street
if self.street_suffix:
addr = addr... | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_end if_statement attribute identifier identifier block expression_statement assignment identifier binary_operator identifier attribute identifier identifier if_statement attribute iden... | Print the address in a human readable format |
def remove_boards_gui(hwpack=''):
if not hwpack:
if len(hwpack_names()) > 1:
hwpack = psidialogs.choice(hwpack_names(),
'select hardware package to select board from!',
title='select')
else:
hwpack ... | module function_definition identifier parameters default_parameter identifier string string_start string_end block if_statement not_operator identifier block if_statement comparison_operator call identifier argument_list call identifier argument_list integer block expression_statement assignment identifier call attribu... | remove boards by GUI. |
def transfer_user(self, username, transfer_address, owner_privkey):
url = self.base_url + "/users/" + username + "/update"
owner_pubkey = get_pubkey_from_privkey(owner_privkey)
payload = {
'transfer_address': transfer_address,
'owner_pubkey': owner_pubkey
}
... | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier binary_operator binary_operator binary_operator attribute identifier identifier string string_start string_content string_end identifier string string_start string_content string... | Transfer name on blockchain |
def _get_extended_palette_entry(self, name, index, is_hex=False):
values = None
is_fbterm = (env.TERM == 'fbterm')
if 'extended' in self._palette_support:
if is_hex:
index = str(find_nearest_color_hexstr(index,
met... | module function_definition identifier parameters identifier identifier identifier default_parameter identifier false block expression_statement assignment identifier none expression_statement assignment identifier parenthesized_expression comparison_operator attribute identifier identifier string string_start string_co... | Compute extended entry, once on the fly. |
def add_cron(self, name, minute, hour, mday, month, wday, who, command, env=None):
raise NotImplementedError | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier identifier default_parameter identifier none block raise_statement identifier | Add an entry to the system crontab. |
def bind_path(self, name, folder):
if not len(name) or name[0] != '/' or name[-1] != '/':
raise ValueError(
"name must start and end with '/': {0}".format(name))
self._folder_masks.insert(0, (name, folder)) | module function_definition identifier parameters identifier identifier identifier block if_statement boolean_operator boolean_operator not_operator call identifier argument_list identifier comparison_operator subscript identifier integer string string_start string_content string_end comparison_operator subscript identi... | Adds a mask that maps to a given folder relative to `base_path`. |
def getHostsFromList(hostlist):
if any(re.search('[\[\]]', x) for x in hostlist):
return parseSLURM(str(hostlist))
hostlist = groupTogether(hostlist)
retVal = []
for key, group in groupby(hostlist):
retVal.append((key, len(list(group))))
return retVal | module function_definition identifier parameters identifier block if_statement call identifier generator_expression call attribute identifier identifier argument_list string string_start string_content string_end identifier for_in_clause identifier identifier block return_statement call identifier argument_list call id... | Return the hosts from the command line |
def callback(self, output, inputs=None, state=None, events=None):
'Form a callback function by wrapping, in the same way as the underlying Dash application would'
callback_set = {'output':output,
'inputs':inputs and inputs or dict(),
'state':state and stat... | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_s... | Form a callback function by wrapping, in the same way as the underlying Dash application would |
def _compute_mean(self, C, mag, ztor, rrup):
gc0 = 0.2418
ci = 0.3846
gch = 0.00607
g4 = 1.7818
ge = 0.554
gm = 1.414
mean = (
gc0 + ci + ztor * gch + C['gc1'] +
gm * mag + C['gc2'] * (10 - mag) ** 3 +
C['gc3'] * np.log(rrup + g... | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier float expression_statement assignment identifier float expression_statement assignment identifier float expression_statement assignment identifier float expression_sta... | Compute mean value as in ``subroutine getGeom`` in ``hazgridXnga2.f`` |
def rename(path):
new_path = prompt(path)
if path != new_path:
try:
from shutil import move
except ImportError:
from os import rename as move
move(path, new_path)
return new_path | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier identifier block try_statement block import_from_statement dotted_name identifier dotted_name identifier except_clause identif... | Rename a file if necessary. |
def split(self, availWidth, availHeight):
logger.debug("*** split (%f, %f)", availWidth, availHeight)
splitted = []
if self.splitIndex:
text1 = self.text[:self.splitIndex]
text2 = self.text[self.splitIndex:]
p1 = Paragraph(Text(text1), self.style, debug=self.d... | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier expression_statement assignment identifier list if_statement attribute identifier identifier... | Split ourselves in two paragraphs. |
def _init_proc(self):
if not self.proc:
self.proc = [
mp.Process(target=self._proc_loop, args=(i, self.alive, self.queue, self.fn))
for i in range(self.num_proc)
]
self.alive.value = True
for p in self.proc:
p.start(... | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier list_comprehension call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identif... | Start processes if not already started |
def merge(self, other):
if not isinstance(other, one):
other = one(other)
new = concatenate((self.coordinates, other.coordinates))
unique = set([tuple(x) for x in new.tolist()])
final = asarray([list(x) for x in unique])
return one(final) | module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list tu... | Combine this region with other. |
def toggle_play_pause(self):
if (self._state == STATE_PLAYING and
self._input_func in self._netaudio_func_list):
return self._pause()
elif self._input_func in self._netaudio_func_list:
return self._play() | module function_definition identifier parameters identifier block if_statement parenthesized_expression boolean_operator comparison_operator attribute identifier identifier identifier comparison_operator attribute identifier identifier attribute identifier identifier block return_statement call attribute identifier ide... | Toggle play pause media player. |
def nth(lst, n):
expect_type(n, (String, Number), unit=None)
if isinstance(n, String):
if n.value.lower() == 'first':
i = 0
elif n.value.lower() == 'last':
i = -1
else:
raise ValueError("Invalid index %r" % (n,))
else:
i = n.to_python_index... | module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list identifier tuple identifier identifier keyword_argument identifier none if_statement call identifier argument_list identifier identifier block if_statement comparison_operator call attribute a... | Return the nth item in the list. |
def write(self, data):
for chunk in chunks(data, 512):
self.wait_to_write()
self.comport.write(chunk)
self.comport.flush() | module function_definition identifier parameters identifier identifier block for_statement identifier call identifier argument_list identifier integer block expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_lis... | Write data to serial port. |
def read_model_yaml(self, modelkey):
model_yaml = self._name_factory.model_yaml(modelkey=modelkey,
fullpath=True)
model = yaml.safe_load(open(model_yaml))
return model | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier true expression_statement assignment identifier call attribut... | Read the yaml file for the diffuse components |
def sniff_field_spelling(mlog, source):
position_field_type_default = position_field_types[0]
msg = mlog.recv_match(source)
mlog._rewind()
position_field_selection = [spelling for spelling in position_field_types if hasattr(msg, spelling[0])]
return position_field_selection[0] if position_field_sele... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument... | attempt to detect whether APM or PX4 attributes names are in use |
def install_from_pypi(context):
tmp_dir = venv.create_venv()
install_cmd = '%s/bin/pip install %s' % (tmp_dir, context.module_name)
package_index = 'pypi'
if context.pypi:
install_cmd += '-i %s' % context.pypi
package_index = context.pypi
try:
result = shell.dry_run(install_c... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier attribute identifier identifier expres... | Attempts to install your package from pypi. |
def toggle_quick_open_command_line_sensitivity(self, chk):
self.get_widget('quick_open_command_line').set_sensitive(chk.get_active())
self.get_widget('quick_open_in_current_terminal').set_sensitive(chk.get_active()) | module function_definition identifier parameters identifier identifier block expression_statement call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list expression_statement call attribut... | When the user unchecks 'enable quick open', the command line should be disabled |
def activation_done(self, *args, **kwargs):
if self._save:
self.save_task()
else:
super().activation_done(*args, **kwargs) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list else_clause block expression_statement call attribute call identi... | Complete the ``activation`` or save only, depending on form submit. |
def filter_out(queryset, setting_name):
kwargs = helpers.get_settings().get(setting_name, {}).get('FILTER_OUT', {})
queryset = queryset.exclude(**kwargs)
return queryset | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call attribute call attribute identifier identifier argument_list identifier argument_list identifier dictionary identifier argument_list string string_start string_content string_end d... | Remove unwanted results from queryset |
def to_dataframe(self):
def row_from_variant(variant):
return OrderedDict([
("chr", variant.contig),
("start", variant.original_start),
("ref", variant.original_ref),
("alt", variant.original_alt),
("gene_name", ";".join... | module function_definition identifier parameters identifier block function_definition identifier parameters identifier block return_statement call identifier argument_list list tuple string string_start string_content string_end attribute identifier identifier tuple string string_start string_content string_end attribu... | Build a DataFrame from this variant collection |
def react(self, emojiname):
self._client.react_to_message(
emojiname=emojiname,
channel=self._body['channel'],
timestamp=self._body['ts']) | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier subscript attribute identifier identifier string string_start string_content string... | React to a message using the web api |
def check_rates(self, rates, base):
if "rates" not in rates:
raise RuntimeError("%s: 'rates' not found in results" % self.name)
if "base" not in rates or rates["base"] != base or base not in rates["rates"]:
self.log(logging.WARNING, "%s: 'base' not found in results", self.name)
... | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator string string_start string_content string_end identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identif... | Local helper function for validating rates response |
def _num_samples(x):
if hasattr(x, 'fit'):
raise TypeError('Expected sequence or array-like, got '
'estimator %s' % x)
if not hasattr(x, '__len__') and not hasattr(x, 'shape'):
if hasattr(x, '__array__'):
x = np.asarray(x)
else:
raise TypeE... | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier string string_start string_content string_end block raise_statement call identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start ... | Return number of samples in array-like x. |
def array_items(self, number_type, *, number_suffix=''):
for token in self.collect_tokens_until('CLOSE_BRACKET'):
is_number = token.type == 'NUMBER'
value = token.value.lower()
if not (is_number and value.endswith(number_suffix)):
raise self.error(f'Invalid {n... | module function_definition identifier parameters identifier identifier keyword_separator default_parameter identifier string string_start string_end block for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment ident... | Parse and yield array items from the token stream. |
def _stat_name(feat_name, stat_mode):
if feat_name[-1] == 's':
feat_name = feat_name[:-1]
if feat_name == 'soma_radii':
feat_name = 'soma_radius'
if stat_mode == 'raw':
return feat_name
return '%s_%s' % (stat_mode, feat_name) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator subscript identifier unary_operator integer string string_start string_content string_end block expression_statement assignment identifier subscript identifier slice unary_operator integer if_statement comparis... | Set stat name based on feature name and stat mode |
def all_edges(self, node):
return set(self.inc_edges(node) + self.out_edges(node)) | module function_definition identifier parameters identifier identifier block return_statement call identifier argument_list binary_operator call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier | Returns a list of incoming and outging edges. |
def current_app(self):
current_focus = self.adb_shell(CURRENT_APP_CMD)
if current_focus is None:
return None
current_focus = current_focus.replace("\r", "")
matches = WINDOW_REGEX.search(current_focus)
if matches:
(pkg, activity) = matches.group("package",... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block return_statement none expression_statement assignment identifier call attribute identifier ide... | Return the current app. |
def format_choices(self):
ce = enumerate(self.choices)
f = lambda i, c: '%s (%d)' % (c, i+1)
toks = [f(i,c) for i, c in ce] + ['Help (?)']
return ' '.join(toks) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier lambda lambda_parameters identifier identifier binary_operator string string_start string_content string_e... | Return the choices in string form. |
def decode(self, data, erase_pos=None, only_erasures=False):
if isinstance(data, str):
data = bytearray(data, "latin-1")
dec = bytearray()
for i in xrange(0, len(data), self.nsize):
chunk = data[i:i+self.nsize]
e_pos = []
if erase_pos:
... | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier false block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start... | Repair a message, whatever its size is, by using chunking |
def ssh(ctx, cluster_id, key_file):
session = create_session(ctx.obj['AWS_PROFILE_NAME'])
client = session.client('emr')
result = client.describe_cluster(ClusterId=cluster_id)
target_dns = result['Cluster']['MasterPublicDnsName']
ssh_options = '-o StrictHostKeyChecking=no -o ServerAliveInterval=10'
... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier id... | SSH login to EMR master node |
def secure(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if not request.is_secure():
redirect = _redirect(request, True)
if redirect:
return redirect
return view_func(request, *args, **kwarg... | module function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier keyword_argument identifier call identifier argument_list identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern ident... | Handles SSL redirect on the view level. |
def setting(self, setting_name, default=None):
keys = setting_name.split(".")
config = self._content
for key in keys:
if key not in config:
return default
config = config[key]
return config | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier attribute identifier ident... | Retrieve a setting value. |
def waitForInput(self):
self._waitingForInput = False
try:
if self.isDestroyed() or self.isReadOnly():
return
except RuntimeError:
return
self.moveCursor(QTextCursor.End)
if self.textCursor().block().text() == '>>> ':
r... | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier false try_statement block if_statement boolean_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list block return_statement except_cl... | Inserts a new input command into the console editor. |
def cli(env, volume_id, replicant_id):
file_storage_manager = SoftLayer.FileStorageManager(env.client)
success = file_storage_manager.failback_from_replicant(
volume_id,
replicant_id
)
if success:
click.echo("Failback from replicant is now in progress.")
else:
click.e... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier i... | Failback a file volume from the given replicant volume. |
def airport_codes():
html = requests.get(URL).text
data_block = _find_data_block(html)
return _airport_codes_from_data_block(data_block) | module function_definition identifier parameters block expression_statement assignment identifier attribute call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier return_statement call identifier argument_list identifi... | Returns the set of airport codes that is available to be requested. |
def _get_user_info(self, cmd, section, required=True,
accept_just_who=False):
line = self.next_line()
if line.startswith(section + b' '):
return self._who_when(line[len(section + b' '):], cmd, section,
accept_just_who=accept_just_who)
elif required:
... | module function_definition identifier parameters identifier identifier identifier default_parameter identifier true default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement call attribute identifier identifier argument_list binar... | Parse a user section. |
def centroid(self):
left, bottom, right, top = self.lbrt()
return (right + left) / 2.0, (top + bottom) / 2.0 | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier identifier call attribute identifier identifier argument_list return_statement expression_list binary_operator parenthesized_expression binary_operator identifier identifier fl... | Return the centroid of the rectangle. |
def addReadGroup(self, readGroup):
id_ = readGroup.getId()
self._readGroupIdMap[id_] = readGroup
self._readGroupIds.append(id_) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript attribute identifier identifier identifier identifier expression_statement call attribute attribute identif... | Adds the specified ReadGroup to this ReadGroupSet. |
def result_cached(task_id, wait=0, broker=None):
if not broker:
broker = get_broker()
start = time()
while True:
r = broker.cache.get('{}:{}'.format(broker.list_key, task_id))
if r:
return SignedPackage.loads(r)['result']
if (time() - start) * 1000 >= wait >= 0:
... | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier none block if_statement not_operator identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument... | Return the result from the cache backend |
def hoist_event(self, e):
if e.response_type == 0:
return self._process_error(ffi.cast("xcb_generic_error_t *", e))
event = self._event_offsets[e.response_type & 0x7f]
buf = CffiUnpacker(e)
return event(buf) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier integer block return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end... | Hoist an xcb_generic_event_t to the right xcffib structure. |
def prep_ploidy(work_dir, sample, bam_file, cromwell_dir, sv_glob):
purecn_file = _get_cromwell_file(cromwell_dir, sv_glob, dict(sample=sample, method="purecn", ext="purecn.csv"))
work_dir = utils.safe_makedir(os.path.join(work_dir, sample, "inputs"))
out_file = os.path.join(work_dir, "%s-solutions.txt" % s... | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier string string_star... | Create LOHHLA compatible input ploidy file from PureCN output. |
def redirect_to_terms_accept(current_path='/', slug='default'):
redirect_url_parts = list(urlparse(ACCEPT_TERMS_PATH))
if slug != 'default':
redirect_url_parts[2] += slug
querystring = QueryDict(redirect_url_parts[4], mutable=True)
querystring[TERMS_RETURNTO_PARAM] = current_path
redirect_ur... | module function_definition identifier parameters default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier i... | Redirect the user to the terms and conditions accept page. |
def replace_u_start_day(day):
day = day.lstrip('-')
if day == 'uu' or day == '0u':
return '01'
if day == 'u0':
return '10'
return day.replace('u', '0') | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement boolean_operator comparison_operator identifier string string_start string_content string_end compari... | Find the earliest legitimate day. |
def unsubscribe(self, client):
if client in self.clients:
self.clients.remove(client)
log("Unsubscribed client {} from channel {}".format(client, self.name)) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call identifier argument_list call a... | Unsubscribe a client from the channel. |
def indented_show(text, howmany=1):
print(StrTemplate.pad_indent(text=text, howmany=howmany)) | module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier | Print a formatted indented text. |
def extract_aiml(path='aiml-en-us-foundation-alice.v1-9'):
path = find_data_path(path) or path
if os.path.isdir(path):
paths = os.listdir(path)
paths = [os.path.join(path, p) for p in paths]
else:
zf = zipfile.ZipFile(path)
paths = []
for name in zf.namelist():
... | module function_definition identifier parameters default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier boolean_operator call identifier argument_list identifier identifier if_statement call attribute attribute identifier identifier identifier argumen... | Extract an aiml.zip file if it hasn't been already and return a list of aiml file paths |
def setup_argparse(self, argument_parser):
import glob
import logging
import argparse
def get_fonts(pattern):
fonts_to_check = []
for fullpath in glob.glob(pattern):
fullpath_absolute = os.path.abspath(fullpath)
if fullpath_absolute.lower().endswith(".ufo") and os.path.isdir(... | module function_definition identifier parameters identifier identifier block import_statement dotted_name identifier import_statement dotted_name identifier import_statement dotted_name identifier function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement id... | Set up custom arguments needed for this profile. |
def update_line(self, resource_id, data):
return OrderLines(self.client).on(self).update(resource_id, data) | module function_definition identifier parameters identifier identifier identifier block return_statement call attribute call attribute call identifier argument_list attribute identifier identifier identifier argument_list identifier identifier argument_list identifier identifier | Update a line for an order. |
def xmlrpc_reschedule(self):
if not len(self.scheduled_tasks) == 0:
self.reschedule = list(self.scheduled_tasks.items())
self.scheduled_tasks = {}
return True | module function_definition identifier parameters identifier block if_statement not_operator comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement assignment attribute identifier identifier call identifier argument_list call attribute attribute identifier id... | Reschedule all running tasks. |
def visit_reference(self, node: docutils.nodes.reference) -> None:
path = pathlib.Path(node.attributes['refuri'])
try:
if path.is_absolute():
return
resolved_path = path.resolve()
except FileNotFoundError:
return
try:
resolv... | module function_definition identifier parameters identifier typed_parameter identifier type attribute attribute identifier identifier identifier type none block expression_statement assignment identifier call attribute identifier identifier argument_list subscript attribute identifier identifier string string_start str... | Called for "reference" nodes. |
def login(method):
def wrapper(*args, **kwargs):
crawler = args[0].crawler
try:
if os.path.isfile(cookie_path):
with open(cookie_path, 'r') as cookie_file:
cookie = cookie_file.read()
expire_time = re.compile(r'\d{4}-\d{2}-\d{2}').finda... | module function_definition identifier parameters identifier block function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier attribute subscript identifier integer identifier try_statement block if_statement call attribute... | Require user to login. |
def OnCellFrozen(self, event):
with undo.group(_("Frozen")):
self.grid.actions.change_frozen_attr()
self.grid.ForceRefresh()
self.grid.update_attribute_toolbar()
event.Skip() | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item call attribute identifier identifier argument_list call identifier argument_list string string_start string_content string_end block expression_statement call attribute attribute attribute identifier identi... | Cell frozen event handler |
def kill_after(seconds, timeout=2):
pid = os.getpid()
kill = os.kill
run_after_async(seconds, kill, pid, signal.SIGTERM)
run_after_async(seconds + timeout, kill, pid, 9) | module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier attribute identifier identifier expression_statement call identifier argument_li... | Kill self after seconds |
def do_files_exist(filenames):
preexisting = [tf.io.gfile.exists(f) for f in filenames]
return any(preexisting) | module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension call attribute attribute attribute identifier identifier identifier identifier argument_list identifier for_in_clause identifier identifier return_statement call identifier argument_list ident... | Whether any of the filenames exist. |
def _init_externals():
if __version__ == 'git':
sys.path.insert(0, osp.join(osp.dirname(__file__), 'ext', 'gitdb'))
try:
import gitdb
except ImportError:
raise ImportError("'gitdb' could not be found in your PYTHONPATH") | module function_definition identifier parameters block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list integer call attribute identifier identifier argument_list call attribute id... | Initialize external projects by putting them into the path |
def view_current_app_behavior(self) -> str:
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'dumpsys', 'window', 'windows')
return re.findall(r'mCurrentFocus=.+(com[a-zA-Z0-9\.]+/.[a-zA-Z0-9\.]+)', output)[0] | module function_definition identifier parameters identifier type identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier string string_start string_content string_... | View application behavior in the current window. |
def clone(cls, name, vhost, directory, origin):
paas_info = cls.info(name)
if 'php' in paas_info['type'] and not vhost:
cls.error('PHP instances require indicating the VHOST to clone '
'with --vhost <vhost>')
paas_access = '%s@%s' % (paas_info['user'], paas_info... | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement boolean_operator comparison_operator string string_start string_content string_end subscript... | Clone a PaaS instance's vhost into a local git repository. |
def actors(context):
fritz = context.obj
fritz.login()
for actor in fritz.get_actors():
click.echo("{} ({} {}; AIN {} )".format(
actor.name,
actor.manufacturer,
actor.productname,
actor.actor_id,
))
if actor.has_temperature:
... | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list for_statement identifier call attribute identifier identifier argument_list block expression_statement call... | Display a list of actors |
def ActiveDates(self):
(earliest, latest) = self.GetDateRange()
if earliest is None:
return []
dates = []
date_it = util.DateStringToDateObject(earliest)
date_end = util.DateStringToDateObject(latest)
delta = datetime.timedelta(days=1)
while date_it <= date_end:
date_it_string = ... | module function_definition identifier parameters identifier block expression_statement assignment tuple_pattern identifier identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier none block return_statement list expression_statement assignment identifier list expression... | Return dates this service period is active as a list of "YYYYMMDD". |
def clear_globals(self):
base_keys = ['cStringIO', 'IntType', 'KeyValueStore', 'undoable',
'is_generator_like', 'is_string_like', 'bz2', 'base64',
'__package__', 're', 'config', '__doc__', 'SliceType',
'CellAttributes', 'product', 'ast', '__builtins... | 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 string string_start st... | Clears all newly assigned globals |
def minimumCanEqual(self):
if self.minimum is None:
raise SchemaError("minimumCanEqual requires presence of minimum")
value = self._schema.get("minimumCanEqual", True)
if value is not True and value is not False:
raise SchemaError(
"minimumCanEqual value {... | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identif... | Flag indicating if maximum value is inclusive or exclusive. |
def visit_ExceptHandler(self, node):
currs = (node,)
raises = ()
for n in node.body:
self.result.add_node(n)
for curr in currs:
self.result.add_edge(curr, n)
currs, nraises = self.visit(n)
raises += nraises
return currs, rai... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier tuple identifier expression_statement assignment identifier tuple for_statement identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier ide... | OUT = body's, RAISES = body's |
def _create_justification_button(self):
iconnames = ["JustifyLeft", "JustifyCenter", "JustifyRight"]
bmplist = [icons[iconname] for iconname in iconnames]
self.justify_tb = _widgets.BitmapToggleButton(self, bmplist)
self.justify_tb.SetToolTipString(_(u"Justification"))
self.Bind(... | 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 expression_statement assignment identifier list_comprehension subscr... | Creates horizontal justification button |
def mount(self, path, mount):
self._mountpoints[self._join_chunks(self._normalize_path(path))] = mount | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment subscript attribute identifier identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier | Add a mountpoint to the filesystem. |
def check_updates():
count, packages = fetch()
message = "No news is good news !"
if count > 0:
message = ("{0} software updates are available\n".format(count))
return [message, count, packages] | module function_definition identifier parameters block expression_statement assignment pattern_list identifier identifier call identifier argument_list expression_statement assignment identifier string string_start string_content string_end if_statement comparison_operator identifier integer block expression_statement ... | Check and display upgraded packages |
def compare(self, vertex0, vertex1, subject_graph):
return (
self.pattern_graph.vertex_fingerprints[vertex0] ==
subject_graph.vertex_fingerprints[vertex1]
).all() | module function_definition identifier parameters identifier identifier identifier identifier block return_statement call attribute parenthesized_expression comparison_operator subscript attribute attribute identifier identifier identifier identifier subscript attribute identifier identifier identifier identifier argume... | Returns true when the two vertices are of the same kind |
def zip_all(directory):
zips = []
for cwd, dirs, files in os.walk(directory):
if 'ssmLT.xml' in files:
zips.append(zip_source_model(os.path.join(cwd, 'ssmLT.xml')))
for f in files:
if f.endswith('.xml') and 'exposure' in f.lower():
zips.append(zip_exposure... | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier identifier call attribute identifier identifier argument_list identifier block if_statement comparison_operator string string_start string_content string_end... | Zip source models and exposures recursively |
def load_spelling(spell_file=SPELLING_FILE):
with open(spell_file) as f:
tokens = f.read().split('\n')
size = len(tokens)
term_freq = {token: size - i for i, token in enumerate(tokens)}
return term_freq | module function_definition identifier parameters default_parameter identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argume... | Load the term_freq from spell_file |
def Shutdown(self):
logger.debug("Nodeleader shutting down")
self.stop_peer_check_loop()
self.peer_check_loop_deferred = None
self.stop_check_bcr_loop()
self.check_bcr_loop_deferred = None
self.stop_memcheck_loop()
self.memcheck_loop_deferred = None
self.s... | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier ... | Disconnect all connected peers. |
def upgrade(self):
warn('Upgrading ' + self.filename)
if self.backup_config(self.filename):
return self.write_default_config(self.filename)
return False | module function_definition identifier parameters identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier if_statement call attribute identifier identifier argument_list attribute identifier identifier block return_... | Upgrade the config file. |
def debug(self):
url = '{}/debug/status'.format(self.url)
data = self._get(url)
return data.json() | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list... | Retrieve the debug information from the charmstore. |
def _thread_worker(self):
while self._running:
packet = self._queue.get(True)
if isinstance(packet, dict) and QS_CMD in packet:
try:
self._callback_listen(packet)
except Exception as err:
_LOGGER.error("Exception in ... | module function_definition identifier parameters identifier block while_statement attribute identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list true if_statement boolean_operator call identifier argument_list identifier identifie... | Process callbacks from the queue populated by &listen. |
def _x_get_physical_path(self):
path = self.context.getPath()
portal_path = api.get_path(api.get_portal())
if portal_path not in path:
return "{}/{}".format(portal_path, path)
return path | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument... | Generate the physical path |
def callback(self, event):
self.init_width()
if len(self.initial) > 0:
for cell in self.initial:
self.color_square(cell[0], cell[1], True)
self.initial = []
self.begin_drag = event
self.color_square(event.x, event.y) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block for_statement identifier attribute identifier identifier block... | Selects cells on click. |
def store(data, arr, start=0, stop=None, offset=0, blen=None):
blen = _util.get_blen_array(data, blen)
if stop is None:
stop = len(data)
else:
stop = min(stop, len(data))
length = stop - start
if length < 0:
raise ValueError('invalid stop/start')
for bi in range(start, st... | module function_definition identifier parameters identifier identifier default_parameter identifier integer default_parameter identifier none default_parameter identifier integer default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identif... | Copy `data` block-wise into `arr`. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.