code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def addPSF(self, psf, date=None, info='', light_spectrum='visible'):
self._registerLight(light_spectrum)
date = _toDate(date)
f = self.coeffs['psf']
if light_spectrum not in f:
f[light_spectrum] = []
f[light_spectrum].insert(_insertDateIndex(date, f[light_spectrum]),
[date, info, psf]) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier string string_start string_end default_parameter identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end if_statement comparison_operator identifier identifier block expression_statement assignment subscript identifier identifier list expression_statement call attribute subscript identifier identifier identifier argument_list call identifier argument_list identifier subscript identifier identifier list identifier identifier identifier | add a new point spread function |
def send_mail(self, subject, to, template, **template_ctx):
if not self.mail:
from warnings import warn
warn('Attempting to send mail without the mail bundle installed! '
'Please install it, or fix your configuration.')
return
self.mail.send(subject, to, template, **dict(
**self.security.run_ctx_processor('mail'),
**template_ctx)) | module function_definition identifier parameters identifier identifier identifier identifier dictionary_splat_pattern identifier block if_statement not_operator attribute identifier identifier block import_from_statement dotted_name identifier dotted_name identifier expression_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end return_statement expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier identifier dictionary_splat call identifier argument_list dictionary_splat call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end dictionary_splat identifier | Utility method to send mail with the `mail` template context. |
def readCache(self, filename):
with open(filename, 'rb') as f:
self.modules = pickle.load(f) | 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 attribute identifier identifier call attribute identifier identifier argument_list identifier | Load the graph from a cache file. |
def check_runner(self):
if os.getcwd() not in sys.path:
sys.path.append(os.getcwd())
if self.runner is None:
self.runner = Runner(self.comp, exit=self.exit_runner, store=self.mypy) | module function_definition identifier parameters identifier block if_statement comparison_operator call attribute identifier identifier argument_list attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier | Make sure there is a runner. |
def _find_usage_gateways(self):
gws = self.conn.describe_internet_gateways()
self.limits['Internet gateways']._add_current_usage(
len(gws['InternetGateways']),
aws_type='AWS::EC2::InternetGateway',
) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list call identifier argument_list subscript identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end | find usage for Internet Gateways |
def _buildFileUrl(self, xml_req):
return '%(protocol)s://%(host)s:%(port)s%(xml_req)s'%{
'protocol': self._protocol,
'host': self._host,
'port': self._port,
'xml_req': xml_req,
} | module function_definition identifier parameters identifier identifier block return_statement binary_operator string string_start string_content string_end dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end identifier | Builds url for fetching the files from FM. |
def remove_excluded(self):
sources = list(self.sources.values())
for src in sources:
if src.excluded:
del self.sources[src.name]
src.imports = [m for m in src.imports if not self._exclude(m)]
src.imported_by = [m for m in src.imported_by if not self._exclude(m)] | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list for_statement identifier identifier block if_statement attribute identifier identifier block delete_statement subscript attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause not_operator call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause not_operator call attribute identifier identifier argument_list identifier | Remove all sources marked as excluded. |
def scale_to_vol(self, vol):
f = np.exp((np.log(vol) - np.log(self.vol)) / self.n)
self.expand *= f
self.cov *= f**2
self.am *= f**-2
self.axlens *= f
self.axes *= f
self.vol = vol | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator parenthesized_expression binary_operator call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement augmented_assignment attribute identifier identifier identifier expression_statement augmented_assignment attribute identifier identifier binary_operator identifier integer expression_statement augmented_assignment attribute identifier identifier binary_operator identifier unary_operator integer expression_statement augmented_assignment attribute identifier identifier identifier expression_statement augmented_assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier | Scale ellipoid to a target volume. |
def _init_equiv(self):
gocolored_all = set(self.go2color)
go2obj_usr = self.gosubdag.go2obj
go2color_add = {}
for gocolored_cur, color in self.go2color.items():
if gocolored_cur in go2obj_usr:
goobj = go2obj_usr[gocolored_cur]
goids_equiv = goobj.alt_ids.union([goobj.id])
for goid_add in goids_equiv.difference(gocolored_all):
if goid_add in go2color_add:
print('**TBD: TWO DIFFERENT COLORS FOR EQUIV GO ID')
go2color_add[goid_add] = color
for goid, color in go2color_add.items():
self.go2color[goid] = color | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement comparison_operator identifier identifier block expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list list attribute identifier identifier for_statement identifier call attribute identifier identifier argument_list identifier block if_statement comparison_operator identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier identifier identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment subscript attribute identifier identifier identifier identifier | Add equivalent GO IDs to go2color, if necessary. |
def seed_aws_data(ctx, data):
swag = create_swag_from_ctx(ctx)
for k, v in json.loads(data.read()).items():
for account in v['accounts']:
data = {
'description': 'This is an AWS owned account used for {}'.format(k),
'id': account['account_id'],
'contacts': [],
'owner': 'aws',
'provider': 'aws',
'sensitive': False,
'email': 'support@amazon.com',
'name': k + '-' + account['region']
}
click.echo(click.style(
'Seeded Account. AccountName: {}'.format(data['name']), fg='green')
)
swag.create(data, dry_run=ctx.dry_run) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier for_statement pattern_list identifier identifier call attribute call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier argument_list block for_statement identifier subscript identifier string string_start string_content string_end block expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end list pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end false pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end binary_operator binary_operator identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list subscript identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier | Seeds SWAG from a list of known AWS accounts. |
def with_ctx(func=None):
if not func:
return functools.partial(with_ctx)
@functools.wraps(func)
def func_with_context(_obj, *args, **kwargs):
if 'ctx' not in kwargs or kwargs['ctx'] is None:
with _obj.ctx() as new_ctx:
kwargs['ctx'] = new_ctx
return func(_obj, *args, **kwargs)
else:
return func(_obj, *args, **kwargs)
return func_with_context | module function_definition identifier parameters default_parameter identifier none block if_statement not_operator identifier block return_statement call attribute identifier identifier argument_list identifier decorated_definition decorator call attribute identifier identifier argument_list identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator subscript identifier string string_start string_content string_end none block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list as_pattern_target identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier return_statement call identifier argument_list identifier list_splat identifier dictionary_splat identifier else_clause block return_statement call identifier argument_list identifier list_splat identifier dictionary_splat identifier return_statement identifier | Auto create a new context if not available |
def truncate(value: Decimal, n_digits: int) -> Decimal:
return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits) | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block return_statement binary_operator call identifier argument_list call attribute identifier identifier argument_list binary_operator identifier parenthesized_expression binary_operator integer identifier parenthesized_expression binary_operator integer identifier | Truncates a value to a number of decimals places |
def _machinectl(cmd,
output_loglevel='debug',
ignore_retcode=False,
use_vt=False):
prefix = 'machinectl --no-legend --no-pager'
return __salt__['cmd.run_all']('{0} {1}'.format(prefix, cmd),
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier false default_parameter identifier false block expression_statement assignment identifier string string_start string_content string_end return_statement call subscript identifier string string_start string_content string_end argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Helper function to run machinectl |
def register(linter):
linter.register_checker(ResourceLeakageChecker(linter))
linter.register_checker(BlacklistedImportsChecker(linter))
linter.register_checker(MovedTestCaseClassChecker(linter))
linter.register_checker(BlacklistedLoaderModulesUsageChecker(linter))
linter.register_checker(BlacklistedFunctionsChecker(linter)) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier | Required method to auto register this checker |
def check_event_coverage(patterns, event_list):
proportions = []
for pattern_list in patterns:
proportion = 0
for pattern in pattern_list:
for node in pattern.nodes():
if node in event_list:
proportion += 1.0 / len(pattern_list)
break
proportions.append(proportion)
return proportions | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier integer for_statement identifier identifier block for_statement identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier identifier block expression_statement augmented_assignment identifier binary_operator float call identifier argument_list identifier break_statement expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Calculate the ratio of patterns that were extracted. |
def utcnow(cls):
obj = datetime.datetime.utcnow()
obj = cls(obj, tzinfo=pytz.utc)
return obj | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier attribute identifier identifier return_statement identifier | Return a new datetime representing UTC day and time. |
def _doc_method(klass, func):
argspec = inspect.getfullargspec(func)
if argspec.args and argspec.args[0] == 'self':
del argspec.args[0]
args = inspect.formatargspec(*argspec)
header = "{klass}.{name}{args}".format(klass=klass.__name__,
name=_name(func),
args=args,
)
docstring = _doc(func)
return _concat(header, docstring) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement boolean_operator attribute identifier identifier comparison_operator subscript attribute identifier identifier integer string string_start string_content string_end block delete_statement subscript attribute identifier identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list list_splat identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier call identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list identifier return_statement call identifier argument_list identifier identifier | Generate the docstring of a method. |
def check_dependee_build(self, depender, dependee, dependee_id):
shutit_global.shutit_global_object.yield_to_draw()
cfg = self.cfg
if not (cfg[dependee.module_id]['shutit.core.module.build'] or
self.is_to_be_built_or_is_installed(dependee)):
return 'depender module id:\n\n[' + depender.module_id + ']\n\nis configured: "build:yes" or is already built but dependee module_id:\n\n[' + dependee_id + ']\n\n is not configured: "build:yes"'
return '' | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier attribute identifier identifier if_statement not_operator parenthesized_expression boolean_operator subscript subscript identifier attribute identifier identifier string string_start string_content string_end call attribute identifier identifier argument_list identifier block return_statement binary_operator binary_operator binary_operator binary_operator string string_start string_content escape_sequence escape_sequence string_end attribute identifier identifier string string_start string_content escape_sequence escape_sequence escape_sequence escape_sequence string_end identifier string string_start string_content escape_sequence escape_sequence string_end return_statement string string_start string_end | Checks whether a depended on module is configured to be built. |
def name(self) -> str:
if self.direction == DIRECTION_IN:
return self.raw.get('Input.Name', '')
return self.raw.get('Output.Name', '') | module function_definition identifier parameters identifier type identifier block if_statement comparison_operator attribute identifier identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_end return_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_end | Return name relevant to direction. |
def pythonise(id, encoding='ascii'):
replace = {'-': '_', ':': '_', '/': '_'}
func = lambda id, pair: id.replace(pair[0], pair[1])
id = reduce(func, replace.iteritems(), id)
id = '_%s' % id if id[0] in string.digits else id
return id.encode(encoding) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier lambda lambda_parameters identifier identifier call attribute identifier identifier argument_list subscript identifier integer subscript identifier integer expression_statement assignment identifier call identifier argument_list identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier conditional_expression binary_operator string string_start string_content string_end identifier comparison_operator subscript identifier integer attribute identifier identifier identifier return_statement call attribute identifier identifier argument_list identifier | Return a Python-friendly id |
def load_stream(cls, st):
y = yaml.load(st)
return [ Automaton(k, v) for k, v in y.iteritems() ] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement list_comprehension call identifier argument_list identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list | Load Automatons from a stream |
def tags(cls, filename, namespace=None):
return cls._raster_opener(filename).tags(ns=namespace) | module function_definition identifier parameters identifier identifier default_parameter identifier none block return_statement call attribute call attribute identifier identifier argument_list identifier identifier argument_list keyword_argument identifier identifier | Extract tags from file. |
def log_decl_method(func):
from functools import wraps
@wraps(func)
def with_logging(*args, **kwargs):
self = args[0]
decl = args[2]
log(DEBUG, u" {}: {} {}".format(
self.state['current_step'], decl.name,
serialize(decl.value).strip()).encode('utf-8'))
return func(*args, **kwargs)
return with_logging | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier dotted_name identifier decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier subscript identifier integer expression_statement call identifier argument_list identifier call attribute call attribute string string_start string_content string_end identifier argument_list subscript attribute identifier identifier string string_start string_content string_end attribute identifier identifier call attribute call identifier argument_list attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end return_statement call identifier argument_list list_splat identifier dictionary_splat identifier return_statement identifier | Decorate do_declartion methods for debug logging. |
def _save_pickle(self, filename):
with open(filename, 'wb') as file_handle:
pickle.dump(self._sensors, file_handle, pickle.HIGHEST_PROTOCOL)
file_handle.flush()
os.fsync(file_handle.fileno()) | 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 call attribute identifier identifier argument_list attribute identifier identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list | Save sensors to pickle file. |
def run(self, cmd):
print datetime.datetime.now()
output = subprocess.Popen(cmd, shell=True)
output = output.communicate()[0]
print output | module function_definition identifier parameters identifier identifier block print_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true expression_statement assignment identifier subscript call attribute identifier identifier argument_list integer print_statement identifier | Runs the appropriate command |
def unsign(self, token):
if self.max_age is None:
data = self.signer.unsign(token)
else:
data = self.signer.unsign(token, max_age=self.max_age)
return signing.b64_decode(data.encode()) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier else_clause block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list | Extract the data from a signed ``token``. |
def _legacy_api_registration_check(self):
logger.debug('Checking registration status...')
machine_id = generate_machine_id()
try:
url = self.api_url + '/v1/systems/' + machine_id
net_logger.info("GET %s", url)
res = self.session.get(url, timeout=self.config.http_timeout)
except requests.ConnectionError:
logger.error('Connection timed out. Running connection test...')
self.test_connection()
return False
try:
unreg_status = json.loads(res.content).get('unregistered_at', 'undefined')
self.config.account_number = json.loads(res.content).get('account_number', 'undefined')
except ValueError:
return False
if unreg_status == 'undefined':
return None
elif unreg_status is None:
return True
else:
return unreg_status | 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 identifier call identifier argument_list try_statement block expression_statement assignment identifier binary_operator binary_operator attribute identifier identifier string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier attribute attribute identifier identifier identifier except_clause attribute identifier 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 return_statement false try_statement block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute attribute identifier identifier identifier call attribute call attribute identifier identifier argument_list attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end except_clause identifier block return_statement false if_statement comparison_operator identifier string string_start string_content string_end block return_statement none elif_clause comparison_operator identifier none block return_statement true else_clause block return_statement identifier | Check registration status through API |
def request(self, action, data={}, headers={}, method='GET'):
headers = {
"Authorization": "Bearer " + self.token,
"Content-Type": "application/json",
"X-Version": "1",
"Accept": "application/json"
}
return Transport.request(self, action, data, headers, method) | module function_definition identifier parameters identifier identifier default_parameter identifier dictionary default_parameter identifier dictionary default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier dictionary pair string string_start string_content string_end binary_operator string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end return_statement call attribute identifier identifier argument_list identifier identifier identifier identifier identifier | Append the REST headers to every request |
def delete(self, key):
self._get_table()
self.table.delete_item(key=key)
log.debug("Deleted item at key '%s'" % (key)) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression identifier | If this key exists, delete it |
def _detect_buffer_encoding(self, f):
encoding = None
with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as m:
encoding = self._analyze_file(m)
return encoding | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier none with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list integer keyword_argument identifier attribute identifier identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier | Guess by checking BOM, and checking `_special_encode_check`, and using memory map. |
def build_media(self):
logger.debug("Building media directory")
if self.verbosity > 1:
self.stdout.write("Building media directory")
if os.path.exists(self.media_root) and settings.MEDIA_URL:
target_dir = path.join(self.fs_name, self.build_dir, settings.MEDIA_URL.lstrip('/'))
logger.debug("Copying {}{} to {}{}".format("osfs://", self.media_root, self.fs_name, target_dir))
copy.copy_dir("osfs:///", smart_text(self.media_root), self.fs, smart_text(target_dir)) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator attribute identifier identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement boolean_operator call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list string string_start string_content string_end attribute identifier identifier attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list attribute identifier identifier attribute identifier identifier call identifier argument_list identifier | Build the media files. |
def copy_experiment(experiment):
try:
publisher.publish_experiment_job_log(
log_lines='Copying outputs from experiment `{}` into experiment `{}`'.format(
experiment.original_experiment.unique_name, experiment.unique_name
),
experiment_uuid=experiment.uuid.hex,
experiment_name=experiment.unique_name,
job_uuid='all',
)
stores.copy_experiment_outputs(
persistence_outputs_from=experiment.original_experiment.persistence_outputs,
persistence_outputs_to=experiment.persistence_outputs,
experiment_name_from=experiment.original_experiment.unique_name,
experiment_name_to=experiment.unique_name)
except OSError:
publisher.publish_experiment_job_log(
log_lines='Could not copy the outputs of experiment `{}` into experiment `{}`'.format(
experiment.original_experiment.unique_name, experiment.unique_name
),
experiment_uuid=experiment.uuid.hex,
experiment_name=experiment.unique_name,
job_uuid='all',
)
_logger.warning(
'Could not copy the outputs of experiment `%s` into experiment `%s`',
experiment.original_experiment.unique_name, experiment.unique_name) | module function_definition identifier parameters identifier block try_statement block expression_statement call attribute identifier identifier argument_list keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier attribute identifier identifier keyword_argument identifier attribute attribute identifier identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list keyword_argument identifier attribute attribute identifier identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute attribute identifier identifier identifier keyword_argument identifier attribute identifier identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier attribute identifier identifier keyword_argument identifier attribute attribute identifier identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute attribute identifier identifier identifier attribute identifier identifier | If experiment is a restart, we should resume from last check point |
def loads(cls, data):
rep = cbor.loads(data)
if not isinstance(rep, Sequence):
raise SerializationError('expected a CBOR list')
if len(rep) != 2:
raise SerializationError('expected a CBOR list of 2 items')
metadata = rep[0]
if 'v' not in metadata:
raise SerializationError('no version in CBOR metadata')
if metadata['v'] != 'fc01':
raise SerializationError('invalid CBOR version {!r} '
'(expected "fc01")'
.format(metadata['v']))
read_only = metadata.get('ro', False)
contents = rep[1]
return cls.from_dict(contents, read_only=read_only) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript identifier integer if_statement comparison_operator string string_start string_content string_end identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end false expression_statement assignment identifier subscript identifier integer return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier | Create a feature collection from a CBOR byte string. |
def _thumbnail_local(self, original_filename, thumb_filename,
thumb_size, thumb_url, crop=None, bg=None,
quality=85):
self._get_path(thumb_filename)
thumb_url_full = url_for('static', filename=thumb_url)
if os.path.exists(thumb_filename):
return thumb_url_full
try:
image = Image.open(original_filename)
except IOError:
return ''
img = self._thumbnail_resize(image, thumb_size, crop=crop, bg=bg)
img.save(thumb_filename, image.format, quality=quality)
return thumb_url_full | module function_definition identifier parameters identifier identifier identifier identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier integer block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block return_statement identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause identifier block return_statement string string_start string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier keyword_argument identifier identifier return_statement identifier | Finds or creates a thumbnail for the specified image on the local filesystem. |
def create_tool(self, task):
gp_tool = dict(taskName=task.name,
taskDisplayName=task.display_name,
taskDescription=task.description,
canRunInBackground=True,
taskUri=task.uri)
gp_tool['execute'] = self._execute_template.substitute(gp_tool)
gp_tool['parameterInfo'] = param_builder.create_param_info(task.parameters,
self.parameter_map)
gp_tool['updateParameter'] = param_builder.create_update_parameter(task.parameters,
self.parameter_map)
gp_tool['preExecute'] = param_builder.create_pre_execute(task.parameters,
self.parameter_map)
gp_tool['postExecute'] = param_builder.create_post_execute(task.parameters,
self.parameter_map)
return self._tool_template.substitute(gp_tool) | 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 attribute identifier identifier keyword_argument identifier true keyword_argument identifier attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier return_statement call attribute attribute identifier identifier identifier argument_list identifier | Creates a new GPTool for the toolbox. |
def before(f, chain=False):
def decorator(g):
@wraps(g)
def h(*args, **kargs):
if chain:
return g(f(*args, **kargs))
else:
f(*args, **kargs)
return g(*args, **kargs)
return h
return decorator | module function_definition identifier parameters identifier default_parameter identifier false block function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement identifier block return_statement call identifier argument_list call identifier argument_list list_splat identifier dictionary_splat identifier else_clause block expression_statement call identifier argument_list list_splat identifier dictionary_splat identifier return_statement call identifier argument_list list_splat identifier dictionary_splat identifier return_statement identifier return_statement identifier | Runs f before the decorated function. |
def finish_hanging(self):
if self.groups.starting_signature:
if self.groups.starting_group:
self.add_tokens_for_group(with_pass=True)
elif self.groups.starting_single:
self.add_tokens_for_single(ignore=True) | module function_definition identifier parameters identifier block if_statement attribute attribute identifier identifier identifier block if_statement attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list keyword_argument identifier true elif_clause attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list keyword_argument identifier true | Add tokens for hanging singature if any |
def coerce(value):
if isinstance(value, StringCell):
return value
elif isinstance(value, (str, unicode)):
return StringCell(value)
else:
raise CoercionFailure("Cannot coerce %s to StringCell" % (value)) | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block return_statement identifier elif_clause call identifier argument_list identifier tuple identifier identifier block return_statement call identifier argument_list identifier else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression identifier | Turns value into a string |
def build_specfile_filesection(spec, files):
str = '%files\n'
if 'X_RPM_DEFATTR' not in spec:
spec['X_RPM_DEFATTR'] = '(-,root,root)'
str = str + '%%defattr %s\n' % spec['X_RPM_DEFATTR']
supported_tags = {
'PACKAGING_CONFIG' : '%%config %s',
'PACKAGING_CONFIG_NOREPLACE' : '%%config(noreplace) %s',
'PACKAGING_DOC' : '%%doc %s',
'PACKAGING_UNIX_ATTR' : '%%attr %s',
'PACKAGING_LANG_' : '%%lang(%s) %s',
'PACKAGING_X_RPM_VERIFY' : '%%verify %s',
'PACKAGING_X_RPM_DIR' : '%%dir %s',
'PACKAGING_X_RPM_DOCDIR' : '%%docdir %s',
'PACKAGING_X_RPM_GHOST' : '%%ghost %s', }
for file in files:
tags = {}
for k in list(supported_tags.keys()):
try:
v = file.GetTag(k)
if v:
tags[k] = v
except AttributeError:
pass
str = str + SimpleTagCompiler(supported_tags, mandatory=0).compile( tags )
str = str + ' '
str = str + file.GetTag('PACKAGING_INSTALL_LOCATION')
str = str + '\n\n'
return str | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier string string_start string_content escape_sequence string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier binary_operator identifier binary_operator string string_start string_content escape_sequence string_end subscript identifier string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end for_statement identifier identifier block expression_statement assignment identifier dictionary for_statement identifier call identifier argument_list call attribute identifier identifier argument_list block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement assignment subscript identifier identifier identifier except_clause identifier block pass_statement expression_statement assignment identifier binary_operator identifier call attribute call identifier argument_list identifier keyword_argument identifier integer identifier argument_list identifier expression_statement assignment identifier binary_operator identifier string string_start string_content string_end expression_statement assignment identifier binary_operator identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier binary_operator identifier string string_start string_content escape_sequence escape_sequence string_end return_statement identifier | builds the %file section of the specfile |
def wrap_io_os_err(e):
msg = ''
if e.strerror:
msg = e.strerror
if e.message:
msg = ' '.join([e.message, msg])
if e.filename:
msg = ': '.join([msg, e.filename])
return msg | 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 attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list attribute identifier identifier identifier if_statement attribute identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list identifier attribute identifier identifier return_statement identifier | Formats IO and OS error messages for wrapping in FSQExceptions |
def orcid_uri_to_orcid(value):
"Strip the uri schema from the start of ORCID URL strings"
if value is None:
return value
replace_values = ['http://orcid.org/', 'https://orcid.org/']
for replace_value in replace_values:
value = value.replace(replace_value, '')
return value | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement comparison_operator identifier none block return_statement identifier expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_end return_statement identifier | Strip the uri schema from the start of ORCID URL strings |
def _make_write_func(file_obj):
if file_obj is None:
return ffi.NULL
@ffi.callback("cairo_write_func_t", error=constants.STATUS_WRITE_ERROR)
def write_func(_closure, data, length):
file_obj.write(ffi.buffer(data, length))
return constants.STATUS_SUCCESS
return write_func | module function_definition identifier parameters identifier block if_statement comparison_operator identifier none block return_statement attribute identifier identifier decorated_definition decorator call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier return_statement attribute identifier identifier return_statement identifier | Return a CFFI callback that writes to a file-like object. |
def rename_annotations(self, sentence):
annotations = []
for token in sentence:
data = {CLAUSE_IDX: token[CLAUSE_IDX]}
if CLAUSE_ANNOT in token:
if 'KINDEL_PIIR' in token[CLAUSE_ANNOT]:
data[CLAUSE_ANNOTATION] = CLAUSE_BOUNDARY
elif 'KIILU_ALGUS' in token[CLAUSE_ANNOT]:
data[CLAUSE_ANNOTATION] = EMBEDDED_CLAUSE_START
elif 'KIILU_LOPP' in token[CLAUSE_ANNOT]:
data[CLAUSE_ANNOTATION] = EMBEDDED_CLAUSE_END
annotations.append(data)
return annotations | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier dictionary pair identifier subscript identifier identifier if_statement comparison_operator identifier identifier block if_statement comparison_operator string string_start string_content string_end subscript identifier identifier block expression_statement assignment subscript identifier identifier identifier elif_clause comparison_operator string string_start string_content string_end subscript identifier identifier block expression_statement assignment subscript identifier identifier identifier elif_clause comparison_operator string string_start string_content string_end subscript identifier identifier block expression_statement assignment subscript identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Function that renames and restructures clause information. |
def deleteAnnot(self, fannot):
CheckParent(self)
val = _fitz.Page_deleteAnnot(self, fannot)
if val:
val.thisown = True
val.parent = weakref.proxy(self)
val.parent._annot_refs[id(val)] = val
fannot._erase()
return val | module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement identifier block expression_statement assignment attribute identifier identifier true expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript attribute attribute identifier identifier identifier call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list return_statement identifier | Delete annot if PDF and return next one |
def fit_transform_poof(self, X, y=None, outpath=None, **kwargs):
self.fit_transform(X, y, **kwargs)
self.poof(outpath, **kwargs) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list identifier identifier dictionary_splat identifier expression_statement call attribute identifier identifier argument_list identifier dictionary_splat identifier | Fit the model and transforms and then call poof. |
def keep_sources(self, keep):
if self.unmixing_ is None or self.mixing_ is None:
raise RuntimeError("No sources available (run do_mvarica first)")
n_sources = self.mixing_.shape[0]
self.remove_sources(np.setdiff1d(np.arange(n_sources), np.array(keep)))
return self | module function_definition identifier parameters identifier identifier block if_statement boolean_operator comparison_operator attribute identifier identifier none comparison_operator attribute identifier identifier none block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript attribute attribute identifier identifier identifier integer expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier return_statement identifier | Keep only the specified sources in the decomposition. |
def reset_headers(self):
rows = self.rowCount()
cols = self.columnCount()
for r in range(rows):
self.setVerticalHeaderItem(r, QTableWidgetItem(str(r)))
for c in range(cols):
self.setHorizontalHeaderItem(c, QTableWidgetItem(str(c)))
self.setColumnWidth(c, 40) | 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 for_statement identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier call identifier argument_list call identifier argument_list identifier for_statement identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier call identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier integer | Update the column and row numbering in the headers. |
def always_fail(cls, request) -> [
(200, 'Ok', String),
(406, 'Not Acceptable', Void)]:
task_id = uuid4().hex.upper()[:5]
log.info('Starting always FAILING task {}'.format(task_id))
for i in range(randint(0, MAX_LOOP_DURATION)):
yield
Respond(406)
Respond(200, 'Foobar') | module function_definition identifier parameters identifier identifier type list tuple integer string string_start string_content string_end identifier tuple integer string string_start string_content string_end identifier block expression_statement assignment identifier subscript call attribute attribute call identifier argument_list identifier identifier argument_list slice integer expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier for_statement identifier call identifier argument_list call identifier argument_list integer identifier block expression_statement yield expression_statement call identifier argument_list integer expression_statement call identifier argument_list integer string string_start string_content string_end | Perform an always failing task. |
def nchunks_initialized(self):
prog = re.compile(r'\.'.join([r'\d+'] * min(1, self.ndim)))
return sum(1 for k in listdir(self.chunk_store, self._path) if prog.match(k)) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list binary_operator list string string_start string_content string_end call identifier argument_list integer attribute identifier identifier return_statement call identifier generator_expression integer for_in_clause identifier call identifier argument_list attribute identifier identifier attribute identifier identifier if_clause call attribute identifier identifier argument_list identifier | The number of chunks that have been initialized with some data. |
def blackbox(blackbox):
if tuple(sorted(blackbox.output_indices)) != blackbox.output_indices:
raise ValueError('Output indices {} must be ordered'.format(
blackbox.output_indices))
partition(blackbox.partition)
for part in blackbox.partition:
if not set(part) & set(blackbox.output_indices):
raise ValueError(
'Every blackbox must have an output - {} does not'.format(
part)) | module function_definition identifier parameters identifier block if_statement comparison_operator call identifier argument_list call identifier argument_list attribute identifier identifier attribute identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement call identifier argument_list attribute identifier identifier for_statement identifier attribute identifier identifier block if_statement not_operator binary_operator call identifier argument_list identifier call identifier argument_list attribute identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier | Validate a macro blackboxing. |
def format_csv(self, delim=',', qu='"'):
res = qu + self.name + qu + delim
if self.data:
for d in self.data:
res += qu + str(d) + qu + delim
return res + '\n' | module function_definition identifier parameters identifier 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 binary_operator binary_operator binary_operator identifier attribute identifier identifier identifier identifier if_statement attribute identifier identifier block for_statement identifier attribute identifier identifier block expression_statement augmented_assignment identifier binary_operator binary_operator binary_operator identifier call identifier argument_list identifier identifier identifier return_statement binary_operator identifier string string_start string_content escape_sequence string_end | Prepares the data in CSV format |
def apply(self, reboot=False):
self.root.use_virtual_addresses = True
self.root.manage.manage = True
self.root.mode = 'new'
self.root.init_boot = reboot
self.client.set_profile(self.root.get_json()) | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment attribute attribute identifier identifier identifier true expression_statement assignment attribute attribute attribute identifier identifier identifier identifier true expression_statement assignment attribute attribute identifier identifier identifier string string_start string_content string_end expression_statement assignment attribute attribute identifier identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list | Apply the configuration to iRMC. |
def _secrets_table_name(environment=None, stage=None):
if environment is None:
environment = os.environ.get("HUMILIS_ENVIRONMENT")
if stage is None:
stage = os.environ.get("HUMILIS_STAGE")
if environment:
if stage:
return "{environment}-{stage}-secrets".format(**locals())
else:
return "{environment}-secrets".format(**locals()) | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement identifier block if_statement identifier block return_statement call attribute string string_start string_content string_end identifier argument_list dictionary_splat call identifier argument_list else_clause block return_statement call attribute string string_start string_content string_end identifier argument_list dictionary_splat call identifier argument_list | Name of the secrets table associated to a humilis deployment. |
def focusOutEvent(self, ev):
Kittens.widgets.ClickableTreeWidget.focusOutEvent(self, ev)
wid = QApplication.focusWidget()
while wid:
if wid is self:
return
wid = wid.parent()
self._startOrStopEditing() | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list while_statement identifier block if_statement comparison_operator identifier identifier block return_statement expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Redefine focusOut events to stop editing |
def run (self):
try:
self.run_checked()
except KeyboardInterrupt:
thread.interrupt_main()
except Exception:
self.internal_error() | module function_definition identifier parameters identifier block try_statement block expression_statement call attribute identifier identifier argument_list except_clause identifier block expression_statement call attribute identifier identifier argument_list except_clause identifier block expression_statement call attribute identifier identifier argument_list | Handle keyboard interrupt and other errors. |
def forward(self, x: torch.Tensor, sublayer: Callable[[torch.Tensor], torch.Tensor]) -> torch.Tensor:
return x + self.dropout(sublayer(self.norm(x))) | module function_definition identifier parameters identifier typed_parameter identifier type attribute identifier identifier typed_parameter identifier type generic_type identifier type_parameter type list attribute identifier identifier type attribute identifier identifier type attribute identifier identifier block return_statement binary_operator identifier call attribute identifier identifier argument_list call identifier argument_list call attribute identifier identifier argument_list identifier | Apply residual connection to any sublayer with the same size. |
def cleanup(self, sched, coro):
try:
sched.sigwait[self.name].remove((self, coro))
except ValueError:
pass
return True | module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement call attribute subscript attribute identifier identifier attribute identifier identifier identifier argument_list tuple identifier identifier except_clause identifier block pass_statement return_statement true | Remove this coro from the waiting for signal queue. |
def pre_flight_headers(self, request, methods):
methods = ', '.join(m.value for m in methods)
headers = {
'Allow': methods,
'Cache-Control': 'no-cache, no-store'
}
allow_origin = self.allow_origin(request)
if allow_origin:
headers = dict_filter(headers, {
'Access-Control-Allow-Origin': allow_origin,
'Access-Control-Allow-Methods': methods,
'Access-Control-Allow-Credentials': {True: 'true', False: 'false'}.get(self.allow_credentials),
'Access-Control-Allow-Headers': ', '.join(self.allow_headers) if self.allow_headers else None,
'Access-Control-Expose-Headers': ', '.join(self.expose_headers) if self.expose_headers else None,
'Access-Control-Max-Age': str(self.max_age) if self.max_age else None,
})
return headers | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier generator_expression attribute identifier identifier for_in_clause identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end call attribute dictionary pair true string string_start string_content string_end pair false string string_start string_content string_end identifier argument_list attribute identifier identifier pair string string_start string_content string_end conditional_expression call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier none pair string string_start string_content string_end conditional_expression call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier none pair string string_start string_content string_end conditional_expression call identifier argument_list attribute identifier identifier attribute identifier identifier none return_statement identifier | Generate pre-flight headers. |
def valid_max_age(number):
"Validate a cookie Max-Age"
if isinstance(number, basestring):
try:
number = long(number)
except (ValueError, TypeError):
return False
if number >= 0 and number % 1 == 0:
return True
return False | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement call identifier argument_list identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier except_clause tuple identifier identifier block return_statement false if_statement boolean_operator comparison_operator identifier integer comparison_operator binary_operator identifier integer integer block return_statement true return_statement false | Validate a cookie Max-Age |
def reboot(env, identifier, hard):
hardware_server = env.client['Hardware_Server']
mgr = SoftLayer.HardwareManager(env.client)
hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')
if not (env.skip_confirmations or
formatting.confirm('This will power off the server with id %s. '
'Continue?' % hw_id)):
raise exceptions.CLIAbort('Aborted.')
if hard is True:
hardware_server.rebootHard(id=hw_id)
elif hard is False:
hardware_server.rebootSoft(id=hw_id)
else:
hardware_server.rebootDefault(id=hw_id) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier string string_start string_content string_end if_statement not_operator parenthesized_expression boolean_operator attribute identifier identifier call attribute identifier identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end identifier block raise_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier true block expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier elif_clause comparison_operator identifier false block expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier | Reboot an active server. |
def machine(self):
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.FLAVOUR) | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end return_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier | Return the flavour attribute of the BFD file being processed. |
def parse_affine(self, hdat, dataobj=None):
if 'affine' in hdat: return to_affine(hdat['affine'])
else: return to_affine(self.default_affine()) | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator string string_start string_content string_end identifier block return_statement call identifier argument_list subscript identifier string string_start string_content string_end else_clause block return_statement call identifier argument_list call attribute identifier identifier argument_list | Parses the affine out of the given header data and yields it. |
def setup_tree(ctx, verbose=None, root=None, tree_dir=None, modules_dir=None):
print('Setting up the tree')
ctx.run('python bin/setup_tree.py -t {0} -r {1} -m {2}'.format(tree_dir, root, modules_dir)) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier identifier | Sets up the SDSS tree enviroment |
def _update_axes_color(self, color):
prop_x = self.axes_actor.GetXAxisCaptionActor2D().GetCaptionTextProperty()
prop_y = self.axes_actor.GetYAxisCaptionActor2D().GetCaptionTextProperty()
prop_z = self.axes_actor.GetZAxisCaptionActor2D().GetCaptionTextProperty()
if color is None:
color = rcParams['font']['color']
color = parse_color(color)
for prop in [prop_x, prop_y, prop_z]:
prop.SetColor(color[0], color[1], color[2])
prop.SetShadow(False)
return | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list if_statement comparison_operator identifier none block expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier for_statement identifier list identifier identifier identifier block expression_statement call attribute identifier identifier argument_list subscript identifier integer subscript identifier integer subscript identifier integer expression_statement call attribute identifier identifier argument_list false return_statement | Internal helper to set the axes label color |
def check_path_matches_patterns(path, patterns):
path = os.path.abspath(path)
for patt in patterns:
if isinstance(patt, six.string_types):
if path == patt:
return True
elif patt.search(path):
return True
return False | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier for_statement identifier identifier block if_statement call identifier argument_list identifier attribute identifier identifier block if_statement comparison_operator identifier identifier block return_statement true elif_clause call attribute identifier identifier argument_list identifier block return_statement true return_statement false | Check if the path matches at least one of the provided patterns. |
def from_acl_response(acl_response):
if 'read' in acl_response:
read_acl = AclType.from_acl_response(acl_response['read'])
return Acl(read_acl)
else:
raise ValueError('Response does not contain read ACL') | module function_definition identifier parameters identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end return_statement call identifier argument_list identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end | Takes JSON response from API and converts to ACL object |
def write_file(writer, filename):
for line in txt_line_iterator(filename):
writer.write(line)
writer.write("\n") | module function_definition identifier parameters identifier identifier block for_statement identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end | Write all of lines from file using the writer. |
def add_autoscaling(subparsers):
autoscaling_parser = subparsers.add_parser(
'autoscaling',
help=runner.create_scaling_policy.__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
autoscaling_parser.set_defaults(func=runner.create_scaling_policy) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier attribute attribute identifier identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier | Auto Scaling Group Policy subcommands. |
def _save_percolator(self):
index = Content.search_objects.mapping.index
query_filter = self.get_content(published=False).to_dict()
q = {}
if "query" in query_filter:
q = {"query": query_filter.get("query", {})}
else:
return
q["sponsored"] = bool(self.tunic_campaign_id)
q["start_date"] = self.start_date
q["end_date"] = self.end_date if self.end_date else datetime.max.replace(tzinfo=pytz.UTC)
if q["start_date"]:
q['start_date_epoch'] = datetime_to_epoch_seconds(q["start_date"])
if q["end_date"]:
q['end_date_epoch'] = datetime_to_epoch_seconds(q["end_date"])
if self.query:
q['included_ids'] = self.query.get('included_ids', [])
es.index(
index=index,
doc_type=".percolator",
body=q,
id=self.es_id
) | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list keyword_argument identifier false identifier argument_list expression_statement assignment identifier dictionary if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end dictionary else_clause block return_statement expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end conditional_expression attribute identifier identifier attribute identifier identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier if_statement subscript identifier string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list subscript identifier string string_start string_content string_end if_statement subscript identifier string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list subscript identifier string string_start string_content string_end if_statement attribute identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end list expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier | Saves the query field as an elasticsearch percolator |
def print_param_values(self_):
self = self_.self
for name,val in self.param.get_param_values():
print('%s.%s = %s' % (self.name,name,val)) | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier identifier identifier | Print the values of all this object's Parameters. |
def getheader(self, field, default=''):
if self.headers:
for header in self.headers:
if field.lower() == header.lower():
return self.headers[header]
return default | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_end block if_statement attribute identifier identifier block for_statement identifier attribute identifier identifier block if_statement comparison_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list block return_statement subscript attribute identifier identifier identifier return_statement identifier | Returns the HTTP response header field, case insensitively |
def toggleDrawingSensitive(self, drawing=True):
self.actions.editMode.setEnabled(not drawing)
if not drawing and self.beginner():
print('Cancel creation.')
self.canvas.setEditing(True)
self.canvas.restoreCursor()
self.actions.create.setEnabled(True) | module function_definition identifier parameters identifier default_parameter identifier true block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list not_operator identifier if_statement boolean_operator not_operator identifier call attribute identifier identifier argument_list block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list true expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list true | In the middle of drawing, toggling between modes should be disabled. |
def node_val_set(self, graph, node, key, branch, turn, tick, value):
if (branch, turn, tick) in self._btts:
raise TimeError
self._btts.add((branch, turn, tick))
graph, node, key, value = map(self.pack, (graph, node, key, value))
self._nodevals2set.append((graph, node, key, branch, turn, tick, value)) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier block if_statement comparison_operator tuple identifier identifier identifier attribute identifier identifier block raise_statement identifier expression_statement call attribute attribute identifier identifier identifier argument_list tuple identifier identifier identifier expression_statement assignment pattern_list identifier identifier identifier identifier call identifier argument_list attribute identifier identifier tuple identifier identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list tuple identifier identifier identifier identifier identifier identifier identifier | Set a key-value pair on a node at a specific branch and revision |
def _init_request_hooks(self):
for method_type in ('pre', 'post'):
for method in _METHODS:
event = getattr(self.app, 'on_' + method_type + '_' + method)
event_hook = getattr(hooks, method_type + '_' + method)
event += event_hook | module function_definition identifier parameters identifier block for_statement identifier tuple string string_start string_content string_end string string_start string_content string_end block for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier binary_operator binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier binary_operator binary_operator identifier string string_start string_content string_end identifier expression_statement augmented_assignment identifier identifier | initialize pre request hooks |
def babel_extract(config, input, output, target, keywords):
click.echo(
click.style(
"Starting Extractions config:{0} input:{1} output:{2} keywords:{3}".format(
config, input, output, keywords
),
fg="green",
)
)
keywords = " -k ".join(keywords)
os.popen(
"pybabel extract -F {0} -k {1} -o {2} {3}".format(
config, keywords, output, input
)
)
click.echo(click.style("Starting Update target:{0}".format(target), fg="green"))
os.popen("pybabel update -N -i {0} -d {1}".format(output, target))
click.echo(click.style("Finish, you can start your translations", fg="green")) | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end | Babel, Extracts and updates all messages marked for translation |
def mutable_record_transform(cls):
if not (len(cls.bases) > 0
and isinstance(cls.bases[0], astroid.Call)
and cls.bases[0].func.as_string() == 'mutablerecords.Record'):
return
try:
if len(cls.bases[0].args) >= 2:
for a in cls.bases[0].args[1].elts:
cls.locals[a] = [None]
if len(cls.bases[0].args) >= 3:
for a,b in cls.bases[0].args[2].items:
cls.locals[a.value] = [None]
except:
raise SyntaxError('Invalid mutablerecords syntax') | module function_definition identifier parameters identifier block if_statement not_operator parenthesized_expression boolean_operator boolean_operator comparison_operator call identifier argument_list attribute identifier identifier integer call identifier argument_list subscript attribute identifier identifier integer attribute identifier identifier comparison_operator call attribute attribute subscript attribute identifier identifier integer identifier identifier argument_list string string_start string_content string_end block return_statement try_statement block if_statement comparison_operator call identifier argument_list attribute subscript attribute identifier identifier integer identifier integer block for_statement identifier attribute subscript attribute subscript attribute identifier identifier integer identifier integer identifier block expression_statement assignment subscript attribute identifier identifier identifier list none if_statement comparison_operator call identifier argument_list attribute subscript attribute identifier identifier integer identifier integer block for_statement pattern_list identifier identifier attribute subscript attribute subscript attribute identifier identifier integer identifier integer identifier block expression_statement assignment subscript attribute identifier identifier attribute identifier identifier list none except_clause block raise_statement call identifier argument_list string string_start string_content string_end | Transform mutable records usage by updating locals. |
def exec_cmd(self, cmdstr):
parts = cmdstr.split()
if len(parts):
cmd, args = parts[0], parts[1:]
self._dispatch(cmd, args)
else:
pass | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement call identifier argument_list identifier block expression_statement assignment pattern_list identifier identifier expression_list subscript identifier integer subscript identifier slice integer expression_statement call attribute identifier identifier argument_list identifier identifier else_clause block pass_statement | Parse line from CLI read loop and execute provided command |
def euclidean_dissim(a, b, **_):
if np.isnan(a).any() or np.isnan(b).any():
raise ValueError("Missing values detected in numerical columns.")
return np.sum((a - b) ** 2, axis=1) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block if_statement boolean_operator call attribute call attribute identifier identifier argument_list identifier identifier argument_list call attribute call attribute identifier identifier argument_list identifier identifier argument_list block raise_statement call identifier argument_list string string_start string_content string_end return_statement call attribute identifier identifier argument_list binary_operator parenthesized_expression binary_operator identifier identifier integer keyword_argument identifier integer | Euclidean distance dissimilarity function |
def parse_int_arg(name, default):
return default if request.args.get(name) is None \
else int(request.args.get(name)) | module function_definition identifier parameters identifier identifier block return_statement conditional_expression identifier comparison_operator call attribute attribute identifier identifier identifier argument_list identifier none line_continuation call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier | Return a given URL parameter as int or return the default value. |
def scrape_links(html, engine):
soup = BeautifulSoup(html, 'lxml')
links = []
if engine == 'd':
results = soup.findAll('a', {'class': 'result__a'})
for result in results:
link = result.get('href')[15:]
link = link.replace('/blob/', '/raw/')
links.append(link)
elif engine == 'g':
results = soup.findAll('h3', {'class': 'r'})
for result in results:
link = result.a['href'][7:].split('&')[0]
link = link.replace('/blob/', '/raw/')
links.append(link)
return links | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier list if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary pair string string_start string_content string_end string string_start string_content string_end for_statement identifier identifier block expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end slice integer expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary pair string string_start string_content string_end string string_start string_content string_end for_statement identifier identifier block expression_statement assignment identifier subscript call attribute subscript subscript attribute identifier identifier string string_start string_content string_end slice integer identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | function to scrape file links from html response |
def _prune(self):
delkeys = [k for k in self.keys() if k not in self.__ringbuffer]
for k in delkeys:
super(KRingbuffer,self).__delitem__(k) | module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier call attribute identifier identifier argument_list if_clause comparison_operator identifier attribute identifier identifier for_statement identifier identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier | Primitive way to keep dict in sync with RB. |
def map(self, method: str, *args, _threaded: bool = True, **kwargs
) -> "AttrIndexedDict":
"For all stored items, run a method they possess."
work = lambda item: getattr(item, method)(*args, **kwargs)
if _threaded:
pool = ThreadPool(int(config.CFG["GENERAL"]["parallel_requests"]))
try:
pool.map(work, self.data.values())
except KeyboardInterrupt:
LOG.warning("CTRL-C caught, finishing current tasks...")
pool.terminate()
else:
pool.close()
pool.join()
return self
for item in self.data.values():
work(item)
return self | module function_definition identifier parameters identifier typed_parameter identifier type identifier list_splat_pattern identifier typed_default_parameter identifier type identifier true dictionary_splat_pattern identifier type string string_start string_content string_end block expression_statement string string_start string_content string_end expression_statement assignment identifier lambda lambda_parameters identifier call call identifier argument_list identifier identifier argument_list list_splat identifier dictionary_splat identifier if_statement identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end try_statement block expression_statement call attribute identifier identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list except_clause 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 else_clause block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list return_statement identifier for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call identifier argument_list identifier return_statement identifier | For all stored items, run a method they possess. |
def make_csv_tables(self):
logger.info('Generate csv report tables')
report_parts = []
for sr in self.subreports:
for data_item in sr.report_data:
report_parts.append(TextPart(fmt='csv', text=data_item.csv, ext='csv'))
return report_parts | 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 identifier list for_statement identifier attribute identifier identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier attribute identifier identifier keyword_argument identifier string string_start string_content string_end return_statement identifier | Builds the report as a list of csv tables with titles. |
def spin_px(self):
return conversions.primary_spin(self.mass1, self.mass2, self.spin1x,
self.spin2x) | module function_definition identifier parameters identifier block return_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier | Returns the x-component of the spin of the primary mass. |
def _do_batched_write_command(
namespace, operation, command, docs, check_keys, opts, ctx):
if ctx.sock_info.compression_context:
return _batched_write_command_compressed(
namespace, operation, command, docs, check_keys, opts, ctx)
return _batched_write_command(
namespace, operation, command, docs, check_keys, opts, ctx) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier block if_statement attribute attribute identifier identifier identifier block return_statement call identifier argument_list identifier identifier identifier identifier identifier identifier identifier return_statement call identifier argument_list identifier identifier identifier identifier identifier identifier identifier | Batched write commands entry point. |
def on_rulebook(self, *args):
if self.rulebook is None:
return
self.rulebook.connect(self._trigger_redata, weak=False)
self.redata() | module function_definition identifier parameters identifier list_splat_pattern identifier block if_statement comparison_operator attribute identifier identifier none block return_statement expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier false expression_statement call attribute identifier identifier argument_list | Make sure to update when the rulebook changes |
def missing_db_response(func):
@wraps(func)
def with_exception_handling(*args, **kwargs):
try:
return func(*args, **kwargs)
except ConnectionError as error:
return (dict(error='Unable to connect to Configuration Db.',
error_message=str(error),
links=dict(root='{}'.format(get_root_url()))),
HTTPStatus.NOT_FOUND)
return with_exception_handling | module function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block try_statement block return_statement call identifier argument_list list_splat identifier dictionary_splat identifier except_clause as_pattern identifier as_pattern_target identifier block return_statement tuple call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier call identifier argument_list identifier keyword_argument identifier call identifier argument_list keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list call identifier argument_list attribute identifier identifier return_statement identifier | Decorator to check connection exceptions |
def log_before_after(name: str, desc: str):
def func_decorator(f):
@ft.wraps(f)
def wrapper(*args, **kwargs):
LOG.info("\n%s - %s", name, desc)
res = f(*args, **kwargs)
if StepResult.ERROR not in res:
LOG.info("%s - OK\n", name)
else:
LOG.error("%s - ERROR\n", name)
return res
return wrapper
return func_decorator | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier block function_definition identifier parameters identifier block decorated_definition decorator call attribute identifier identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end identifier identifier expression_statement assignment identifier call identifier argument_list list_splat identifier dictionary_splat identifier if_statement comparison_operator attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end identifier return_statement identifier return_statement identifier return_statement identifier | Log customized stirng before & after running func. |
async def get_default(cls):
data = await cls._handler.read(id=cls._default_fabric_id)
return cls(data) | module function_definition identifier parameters identifier block expression_statement assignment identifier await call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier return_statement call identifier argument_list identifier | Get the 'default' Fabric for the MAAS. |
async def on_shutdown(app):
for method in app.get("close_methods", []):
logger.debug("Calling < %s >", method)
if asyncio.iscoroutinefunction(method):
await method()
else:
method() | module function_definition identifier parameters identifier block for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end list block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement call attribute identifier identifier argument_list identifier block expression_statement await call identifier argument_list else_clause block expression_statement call identifier argument_list | app SHUTDOWN event handler |
def sphinx(self):
try:
assert __IPYTHON__
classdoc = ''
except (NameError, AssertionError):
scls = self.sphinx_class()
classdoc = ' ({})'.format(scls) if scls else ''
prop_doc = '**{name}**{cls}: {doc}{info}'.format(
name=self.name,
cls=classdoc,
doc=self.doc,
info=', {}'.format(self.info) if self.info else '',
)
return prop_doc | module function_definition identifier parameters identifier block try_statement block assert_statement identifier expression_statement assignment identifier string string_start string_end except_clause tuple identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier conditional_expression call attribute string string_start string_content string_end identifier argument_list identifier identifier string string_start string_end expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier conditional_expression call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier string string_start string_end return_statement identifier | Generate Sphinx-formatted documentation for the Property |
def _read_credential_file(self, cfg):
self.username = cfg.get("rackspace_cloud", "username")
try:
self.password = cfg.get("rackspace_cloud", "api_key", raw=True)
except ConfigParser.NoOptionError as e:
self.password = cfg.get("rackspace_cloud", "password", raw=True) | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end try_statement block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier true except_clause as_pattern attribute identifier identifier as_pattern_target identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier true | Parses the credential file with Rackspace-specific labels. |
async def write(self, data, eof = False, buffering = True):
if not self.outputstream:
self.outputstream = Stream()
self._startResponse()
elif (not buffering or eof) and not self._sendHeaders:
self._startResponse()
if not isinstance(data, bytes):
data = data.encode(self.encoding)
await self.outputstream.write(data, self.connection, eof, False, buffering) | module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier true block if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list elif_clause boolean_operator parenthesized_expression boolean_operator not_operator identifier identifier not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement await call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier identifier false identifier | Write output to current output stream |
def copyFilepath( self ):
clipboard = QApplication.instance().clipboard()
clipboard.setText(self.filepath())
clipboard.setText(self.filepath(), clipboard.Selection) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier | Copies the current filepath contents to the current clipboard. |
def _lcm(a, b):
if a == 0 or b == 0:
return 0
else:
return abs(a * b) // gcd(a, b) | module function_definition identifier parameters identifier identifier block if_statement boolean_operator comparison_operator identifier integer comparison_operator identifier integer block return_statement integer else_clause block return_statement binary_operator call identifier argument_list binary_operator identifier identifier call identifier argument_list identifier identifier | Least Common Multiple between 2 integers. |
def remove_from_gallery(self):
url = self._imgur._base_url + "/3/gallery/{0}".format(self.id)
self._imgur._send_request(url, needs_auth=True, method='DELETE')
if isinstance(self, Image):
item = self._imgur.get_image(self.id)
else:
item = self._imgur.get_album(self.id)
_change_object(self, item)
return self | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator attribute attribute identifier identifier identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier true keyword_argument identifier string string_start string_content string_end if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier else_clause block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call identifier argument_list identifier identifier return_statement identifier | Remove this image from the gallery. |
def model_exchange(model):
lower_default, upper_default = None, None
if model.default_flux_limit is not None:
lower_default = -model.default_flux_limit
upper_default = model.default_flux_limit
compounds = []
for compound, reaction_id, lower, upper in sorted(
itervalues(model.exchange)):
d = OrderedDict([('id', compound.name)])
if reaction_id is not None:
d['reaction'] = reaction_id
lower = _get_output_limit(lower, lower_default)
upper = _get_output_limit(upper, upper_default)
d.update(_generate_limit_items(lower, upper))
compounds.append(d)
return OrderedDict([('compounds', compounds)]) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier expression_list none none if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier unary_operator attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier list for_statement pattern_list identifier identifier identifier identifier call identifier argument_list call identifier argument_list attribute identifier identifier block expression_statement assignment identifier call identifier argument_list list tuple string string_start string_content string_end attribute identifier identifier if_statement comparison_operator identifier none block expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement call identifier argument_list list tuple string string_start string_content string_end identifier | Return exchange definition as YAML dict. |
def load(self):
basepath = os.path.dirname(os.path.abspath(__file__))
filename = os.sep.join([basepath, c.FOLDER_JSON, c.FILE_GAME_VERSIONS])
Handler.ALL_VERS_DATA = {}
with open(filename, "r") as f:
data = json.loads( f.read() )
self.update(data)
self._updated = False | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list list identifier attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier dictionary with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier false | load ALL_VERS_DATA from disk |
def submit_button(*args, **kwargs):
submit_button = wtforms.SubmitField(*args, **kwargs)
submit_button.input_type = 'submit_button'
return submit_button | module function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list list_splat identifier dictionary_splat identifier expression_statement assignment attribute identifier identifier string string_start string_content string_end return_statement identifier | Create a submit button |
def visit_Subscript(self, node: ast.Subscript) -> Any:
value = self.visit(node=node.value)
a_slice = self.visit(node=node.slice)
result = value[a_slice]
self.recomputed_values[node] = result
return result | module function_definition identifier parameters identifier typed_parameter identifier type attribute identifier identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement assignment identifier subscript identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier return_statement identifier | Visit the ``slice`` and a ``value`` and get the element. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.