code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def power_on(self):
try:
self.send_command("POWER_ON")
self._power = POWER_ON
self._state = STATE_ON
return True
except requests.exceptions.RequestException:
_LOGGER.error("Connection error: power on command not sent.")
return False | module function_definition identifier parameters identifier block try_statement block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier return_statement true except_clause attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement false | Turn off receiver via command. |
def _get_version_for_class_from_state(state, klass):
names = [_importable_name(klass)]
from .util import class_rename_registry
names.extend(class_rename_registry.old_handled_by(klass))
for n in names:
try:
return state['class_tree_versions'][n]
except KeyError:
continue
if _debug:
logger.debug('unable to obtain a __serialize_version for class %s', klass)
return float('inf') | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list call identifier argument_list identifier import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier for_statement identifier identifier block try_statement block return_statement subscript subscript identifier string string_start string_content string_end identifier except_clause identifier block continue_statement if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement call identifier argument_list string string_start string_content string_end | retrieves the version of the current klass from the state mapping from old locations to new ones. |
def pairwise_compare(afa, leven, threads, print_list, ignore_gaps):
seqs = {seq[0]: seq for seq in nr_fasta([afa], append_index = True)}
num_seqs = len(seqs)
pairs = ((i[0], i[1], ignore_gaps) for i in itertools.combinations(list(seqs.values()), 2))
pool = multithread(threads)
if leven is True:
pident = pool.map(compare_seqs_leven, pairs)
else:
compare = pool.imap_unordered(compare_seqs, pairs)
pident = [i for i in tqdm(compare, total = (num_seqs*num_seqs)/2)]
pool.close()
pool.terminate()
pool.join()
return to_dictionary(pident, print_list) | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier dictionary_comprehension pair subscript identifier integer identifier for_in_clause identifier call identifier argument_list list identifier keyword_argument identifier true expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier generator_expression tuple subscript identifier integer subscript identifier integer identifier for_in_clause identifier call attribute identifier identifier argument_list call identifier argument_list call attribute identifier identifier argument_list integer expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier true block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier list_comprehension identifier for_in_clause identifier call identifier argument_list identifier keyword_argument identifier binary_operator parenthesized_expression binary_operator identifier identifier integer expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list return_statement call identifier argument_list identifier identifier | make pairwise sequence comparisons between aligned sequences |
def markLoadingStarted(self):
if self.isThreadEnabled():
XLoaderWidget.start(self)
if self.showTreePopup():
tree = self.treePopupWidget()
tree.setCursor(Qt.WaitCursor)
tree.clear()
tree.setUpdatesEnabled(False)
tree.blockSignals(True)
self._baseHints = (self.hint(), tree.hint())
tree.setHint('Loading records...')
self.setHint('Loading records...')
else:
self._baseHints = (self.hint(), '')
self.setHint('Loading records...')
self.setCursor(Qt.WaitCursor)
self.blockSignals(True)
self.setUpdatesEnabled(False)
self.clear()
use_dummy = not self.isRequired() or self.isCheckable()
if use_dummy:
self.addItem('')
self.loadingStarted.emit() | module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier if_statement call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list false expression_statement call attribute identifier identifier argument_list true expression_statement assignment attribute identifier identifier tuple call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment attribute identifier identifier tuple call attribute identifier identifier argument_list string string_start string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list true expression_statement call attribute identifier identifier argument_list false expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier boolean_operator not_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_end expression_statement call attribute attribute identifier identifier identifier argument_list | Marks this widget as loading records. |
def _assert_safe_casting(cls, data, subarr):
if not issubclass(data.dtype.type, np.signedinteger):
if not np.array_equal(data, subarr):
raise TypeError('Unsafe NumPy casting, you must '
'explicitly cast') | module function_definition identifier parameters identifier identifier identifier block if_statement not_operator call identifier argument_list attribute attribute identifier identifier identifier attribute identifier identifier block if_statement not_operator call attribute identifier identifier argument_list identifier identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end | Ensure incoming data can be represented as ints. |
def toner_status(self, filter_supported: bool = True) -> Dict[str, Any]:
toner_status = {}
for color in self.COLOR_NAMES:
try:
toner_stat = self.data.get(
'{}_{}'.format(SyncThru.TONER, color), {})
if filter_supported and toner_stat.get('opt', 0) == 0:
continue
else:
toner_status[color] = toner_stat
except (KeyError, AttributeError):
toner_status[color] = {}
return toner_status | module function_definition identifier parameters identifier typed_default_parameter identifier type identifier true type generic_type identifier type_parameter type identifier type identifier block expression_statement assignment identifier dictionary for_statement identifier attribute identifier identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier identifier dictionary if_statement boolean_operator identifier comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end integer integer block continue_statement else_clause block expression_statement assignment subscript identifier identifier identifier except_clause tuple identifier identifier block expression_statement assignment subscript identifier identifier dictionary return_statement identifier | Return the state of all toners cartridges. |
def __get_last_update_time():
now = datetime.datetime.utcnow()
first_tuesday = __get_first_tuesday(now)
if first_tuesday < now:
return first_tuesday
else:
first_of_month = datetime.datetime(now.year, now.month, 1)
last_month = first_of_month + datetime.timedelta(days=-1)
return __get_first_tuesday(last_month) | module function_definition identifier parameters block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier identifier block return_statement identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier integer expression_statement assignment identifier binary_operator identifier call attribute identifier identifier argument_list keyword_argument identifier unary_operator integer return_statement call identifier argument_list identifier | Returns last FTP site update time |
def individuals(self, ind_ids=None):
query = self.query(Individual)
if ind_ids:
query = query.filter(Individual.ind_id.in_(ind_ids))
return query | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier | Fetch all individuals from the database. |
def loadBestScore(self):
try:
with open(self.scores_file, 'r') as f:
self.best_score = int(f.readline(), 10)
except:
return False
return True | module function_definition identifier parameters identifier block try_statement block with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment attribute identifier identifier call identifier argument_list call attribute identifier identifier argument_list integer except_clause block return_statement false return_statement true | load local best score from the default file |
def panic(self, *args):
self._err("fatal", *args)
if self.test_errs_mode is False:
sys.exit(1) | module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end list_splat identifier if_statement comparison_operator attribute identifier identifier false block expression_statement call attribute identifier identifier argument_list integer | Creates a fatal error and exit |
def diff(self, other):
diff = {}
for k in self.__class__.defaults:
left = getattr(self, k)
right = getattr(other, k)
if left != right:
diff[k] = (left, right)
return diff | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary for_statement identifier attribute attribute identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment subscript identifier identifier tuple identifier identifier return_statement identifier | Return differences between self and other as dictionary of 2-tuples. |
def point_arrays(self):
pdata = self.GetPointData()
narr = pdata.GetNumberOfArrays()
if hasattr(self, '_point_arrays'):
keys = list(self._point_arrays.keys())
if narr == len(keys):
if keys:
if self._point_arrays[keys[0]].size == self.n_points:
return self._point_arrays
else:
return self._point_arrays
self._point_arrays = PointScalarsDict(self)
for i in range(narr):
name = pdata.GetArrayName(i)
self._point_arrays[name] = self._point_scalar(name)
self._point_arrays.enable_callback()
return self._point_arrays | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator identifier call identifier argument_list identifier block if_statement identifier block if_statement comparison_operator attribute subscript attribute identifier identifier subscript identifier integer identifier attribute identifier identifier block return_statement attribute identifier identifier else_clause block return_statement attribute identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list identifier for_statement identifier call identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript attribute identifier identifier identifier call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list return_statement attribute identifier identifier | Returns the all point arrays |
def toggleCollapseBefore( self ):
if ( self.isCollapsed() ):
self.uncollapse()
else:
self.collapse( XSplitterHandle.CollapseDirection.Before ) | module function_definition identifier parameters identifier block if_statement parenthesized_expression call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list else_clause block expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier | Collapses the splitter before this handle. |
def __fetch_data(self, url):
url += '&api_key=' + self.api_key
try:
response = urlopen(url)
root = ET.fromstring(response.read())
except HTTPError as exc:
root = ET.fromstring(exc.read())
raise ValueError(root.get('message'))
return root | module function_definition identifier parameters identifier identifier block expression_statement augmented_assignment identifier binary_operator string string_start string_content string_end attribute identifier identifier try_statement block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list raise_statement call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier | helper function for fetching data given a request URL |
def convert_level(self, record):
level = record.levelno
if level >= logging.CRITICAL:
return levels.CRITICAL
if level >= logging.ERROR:
return levels.ERROR
if level >= logging.WARNING:
return levels.WARNING
if level >= logging.INFO:
return levels.INFO
return levels.DEBUG | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier attribute identifier identifier block return_statement attribute identifier identifier if_statement comparison_operator identifier attribute identifier identifier block return_statement attribute identifier identifier if_statement comparison_operator identifier attribute identifier identifier block return_statement attribute identifier identifier if_statement comparison_operator identifier attribute identifier identifier block return_statement attribute identifier identifier return_statement attribute identifier identifier | Converts a logging level into a logbook level. |
def auth(self):
self.send(nsq.auth(self.auth_secret))
frame, data = self.read_response()
if frame == nsq.FRAME_TYPE_ERROR:
raise data
try:
response = json.loads(data.decode('utf-8'))
except ValueError:
self.close_stream()
raise errors.NSQException(
'failed to parse AUTH response JSON from nsqd: '
'{!r}'.format(data))
self.on_auth.send(self, response=response)
return response | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier attribute identifier identifier block raise_statement identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end except_clause identifier block expression_statement call attribute identifier identifier argument_list raise_statement call attribute identifier identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier return_statement identifier | Send authorization secret to nsqd. |
def plot_all(self, show=True, **kwargs):
figs = []; app = figs.append
app(self.plot_stacked_hist(show=show))
app(self.plot_efficiency(show=show))
app(self.plot_pie(show=show))
return figs | module function_definition identifier parameters identifier default_parameter identifier true dictionary_splat_pattern identifier block expression_statement assignment identifier list expression_statement assignment identifier attribute identifier identifier expression_statement call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier identifier return_statement identifier | Call all plot methods provided by the parser. |
def _tag_net_direction(data):
src = data['packet']['src_domain']
dst = data['packet']['dst_domain']
if src == 'internal':
if dst == 'internal' or 'multicast' in dst or 'broadcast' in dst:
return 'internal'
else:
return 'outgoing'
elif dst == 'internal':
return 'incoming'
else:
return None | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator identifier string string_start string_content string_end block if_statement boolean_operator boolean_operator comparison_operator identifier string string_start string_content string_end comparison_operator string string_start string_content string_end identifier comparison_operator string string_start string_content string_end identifier block return_statement string string_start string_content string_end else_clause block return_statement string string_start string_content string_end elif_clause comparison_operator identifier string string_start string_content string_end block return_statement string string_start string_content string_end else_clause block return_statement none | Create a tag based on the direction of the traffic |
def graph_format(new_mem, old_mem, is_firstiteration=True):
if is_firstiteration:
output = " n/a "
elif new_mem - old_mem > 50000000:
output = " +++++"
elif new_mem - old_mem > 20000000:
output = " ++++ "
elif new_mem - old_mem > 5000000:
output = " +++ "
elif new_mem - old_mem > 1000000:
output = " ++ "
elif new_mem - old_mem > 50000:
output = " + "
elif old_mem - new_mem > 10000000:
output = "--- "
elif old_mem - new_mem > 2000000:
output = " -- "
elif old_mem - new_mem > 100000:
output = " - "
else:
output = " "
return output | module function_definition identifier parameters identifier identifier default_parameter identifier true block if_statement identifier block expression_statement assignment identifier string string_start string_content string_end elif_clause comparison_operator binary_operator identifier identifier integer block expression_statement assignment identifier string string_start string_content string_end elif_clause comparison_operator binary_operator identifier identifier integer block expression_statement assignment identifier string string_start string_content string_end elif_clause comparison_operator binary_operator identifier identifier integer block expression_statement assignment identifier string string_start string_content string_end elif_clause comparison_operator binary_operator identifier identifier integer block expression_statement assignment identifier string string_start string_content string_end elif_clause comparison_operator binary_operator identifier identifier integer block expression_statement assignment identifier string string_start string_content string_end elif_clause comparison_operator binary_operator identifier identifier integer block expression_statement assignment identifier string string_start string_content string_end elif_clause comparison_operator binary_operator identifier identifier integer block expression_statement assignment identifier string string_start string_content string_end elif_clause comparison_operator binary_operator identifier identifier integer block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier string string_start string_content string_end return_statement identifier | Show changes graphically in memory consumption |
def _select_ftdi_channel(channel):
if channel < 0 or channel > 8:
raise ArgumentError("FTDI-selected multiplexer only has channels 0-7 valid, "
"make sure you specify channel with -c channel=number", channel=channel)
from pylibftdi import BitBangDevice
bb = BitBangDevice(auto_detach=False)
bb.direction = 0b111
bb.port = channel | module function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator identifier integer comparison_operator identifier integer block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end keyword_argument identifier identifier import_from_statement dotted_name identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier false expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier identifier | Select multiplexer channel. Currently uses a FTDI chip via pylibftdi |
def changelist_view(self, request, extra_context=None):
if extra_context is None:
extra_context = {}
response = self.adv_filters_handle(request,
extra_context=extra_context)
if response:
return response
return super(AdminAdvancedFiltersMixin, self
).changelist_view(request, extra_context=extra_context) | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier dictionary expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier if_statement identifier block return_statement identifier return_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier keyword_argument identifier identifier | Add advanced_filters form to changelist context |
def retrace(self, rewards, dones, q_values, state_values, rho, final_values):
rho_bar = torch.min(torch.ones_like(rho) * self.retrace_rho_cap, rho)
q_retraced_buffer = torch.zeros_like(rewards)
next_value = final_values
for i in reversed(range(rewards.size(0))):
q_retraced = rewards[i] + self.discount_factor * next_value * (1.0 - dones[i])
next_value = rho_bar[i] * (q_retraced - q_values[i]) + state_values[i]
q_retraced_buffer[i] = q_retraced
return q_retraced_buffer | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator call attribute identifier identifier argument_list identifier attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier identifier for_statement identifier call identifier argument_list call identifier argument_list call attribute identifier identifier argument_list integer block expression_statement assignment identifier binary_operator subscript identifier identifier binary_operator binary_operator attribute identifier identifier identifier parenthesized_expression binary_operator float subscript identifier identifier expression_statement assignment identifier binary_operator binary_operator subscript identifier identifier parenthesized_expression binary_operator identifier subscript identifier identifier subscript identifier identifier expression_statement assignment subscript identifier identifier identifier return_statement identifier | Calculate Q retraced targets |
def valuePasses(self, value):
return self._conditional_cmp[self.op](value, self.value) | module function_definition identifier parameters identifier identifier block return_statement call subscript attribute identifier identifier attribute identifier identifier argument_list identifier attribute identifier identifier | Returns whether this value passes this filter |
def event_dispatcher(nameko_config, **kwargs):
amqp_uri = nameko_config[AMQP_URI_CONFIG_KEY]
serializer, _ = serialization.setup(nameko_config)
serializer = kwargs.pop('serializer', serializer)
ssl = nameko_config.get(AMQP_SSL_CONFIG_KEY)
publisher = Publisher(amqp_uri, serializer=serializer, ssl=ssl, **kwargs)
def dispatch(service_name, event_type, event_data):
exchange = get_event_exchange(service_name)
publisher.publish(
event_data,
exchange=exchange,
routing_key=event_type
)
return dispatch | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier subscript identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier dictionary_splat identifier function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement identifier | Return a function that dispatches nameko events. |
def filter_belief():
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
stmts_json = body.get('statements')
belief_cutoff = body.get('belief_cutoff')
if belief_cutoff is not None:
belief_cutoff = float(belief_cutoff)
stmts = stmts_from_json(stmts_json)
stmts_out = ac.filter_belief(stmts, belief_cutoff)
return _return_stmts(stmts_out) | module function_definition identifier parameters block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement dictionary expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier return_statement call identifier argument_list identifier | Filter to beliefs above a given threshold. |
def build_vec(self):
for item in all_calls:
self.__dict__[item] = []
for dev in self.devices:
for item in all_calls:
if self.system.__dict__[dev].n == 0:
val = False
else:
val = self.system.__dict__[dev].calls.get(item, False)
self.__dict__[item].append(val) | module function_definition identifier parameters identifier block for_statement identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier list for_statement identifier attribute identifier identifier block for_statement identifier identifier block if_statement comparison_operator attribute subscript attribute attribute identifier identifier identifier identifier identifier integer block expression_statement assignment identifier false else_clause block expression_statement assignment identifier call attribute attribute subscript attribute attribute identifier identifier identifier identifier identifier identifier argument_list identifier false expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list identifier | build call validity vector for each device |
def process_shells_ordered(self, shells):
output = []
for shell in shells:
entry = shell['entry']
config = ShellConfig(script=entry['script'], title=entry['title'] if 'title' in entry else '',
model=shell['model'], env=shell['env'], item=shell['item'],
dry_run=shell['dry_run'], debug=shell['debug'], strict=shell['strict'],
variables=shell['variables'],
temporary_scripts_path=shell['temporary_scripts_path'])
result = Adapter(self.process_shell(get_creator_by_name(shell['creator']), entry, config))
output += result.output
self.__handle_variable(entry, result.output)
if not result.success:
return {'success': False, 'output': output}
return {'success': True, 'output': output} | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier conditional_expression subscript identifier string string_start string_content string_end comparison_operator string string_start string_content string_end identifier string string_start string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list call identifier argument_list subscript identifier string string_start string_content string_end identifier identifier expression_statement augmented_assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier if_statement not_operator attribute identifier identifier block return_statement dictionary pair string string_start string_content string_end false pair string string_start string_content string_end identifier return_statement dictionary pair string string_start string_content string_end true pair string string_start string_content string_end identifier | Processing a list of shells one after the other. |
def chunk(seq, n):
for i in range(0, len(seq), n):
yield seq[i:i + n] | module function_definition identifier parameters identifier identifier block for_statement identifier call identifier argument_list integer call identifier argument_list identifier identifier block expression_statement yield subscript identifier slice identifier binary_operator identifier identifier | Yield successive n-sized chunks from seq. |
def minver_error(pkg_name):
print(
'ERROR: specify minimal version of "{}" using '
'">=" or "=="'.format(pkg_name),
file=sys.stderr
)
sys.exit(1) | module function_definition identifier parameters identifier block expression_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 identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list integer | Report error about missing minimum version constraint and exit. |
def load_defense_output(filename):
result = {}
with open(filename) as f:
for row in csv.reader(f):
try:
image_filename = row[0]
if image_filename.endswith('.png') or image_filename.endswith('.jpg'):
image_filename = image_filename[:image_filename.rfind('.')]
label = int(row[1])
except (IndexError, ValueError):
continue
result[image_filename] = label
return result | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block for_statement identifier call attribute identifier identifier argument_list identifier block try_statement block expression_statement assignment identifier subscript identifier integer if_statement boolean_operator call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier subscript identifier slice call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list subscript identifier integer except_clause tuple identifier identifier block continue_statement expression_statement assignment subscript identifier identifier identifier return_statement identifier | Loads output of defense from given file. |
def cli(env, identifier, credential_id):
mgr = SoftLayer.ObjectStorageManager(env.client)
credential = mgr.delete_credential(identifier, credential_id=credential_id)
env.fout(credential) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Delete the credential of an Object Storage Account. |
def add_to_js(self, name, var):
frame = self.page().mainFrame()
frame.addToJavaScriptWindowObject(name, var) | module function_definition identifier parameters identifier identifier 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 identifier identifier | Add an object to Javascript. |
def stderr(msg, silent=False):
if not silent:
print(msg, file=sys.stderr) | module function_definition identifier parameters identifier default_parameter identifier false block if_statement not_operator identifier block expression_statement call identifier argument_list identifier keyword_argument identifier attribute identifier identifier | write msg to stderr if not silent |
def not_next(e):
def match_not_next(s, grm=None, pos=0):
try:
e(s, grm, pos)
except PegreError as ex:
return PegreResult(s, Ignore, (pos, pos))
else:
raise PegreError('Negative lookahead failed', pos)
return match_not_next | module function_definition identifier parameters identifier block function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier integer block try_statement block expression_statement call identifier argument_list identifier identifier identifier except_clause as_pattern identifier as_pattern_target identifier block return_statement call identifier argument_list identifier identifier tuple identifier identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end identifier return_statement identifier | Create a PEG function for negative lookahead. |
def _string_parser(strip_whitespace):
def _parse_string_value(element_text, _state):
if element_text is None:
value = ''
elif strip_whitespace:
value = element_text.strip()
else:
value = element_text
return value
return _parse_string_value | module function_definition identifier parameters identifier block function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block expression_statement assignment identifier string string_start string_end elif_clause identifier block expression_statement assignment identifier call attribute identifier identifier argument_list else_clause block expression_statement assignment identifier identifier return_statement identifier return_statement identifier | Return a parser function for parsing string values. |
def _validate_handler(column_name, value, predicate_refs):
if value is not None:
for predicate_ref in predicate_refs:
predicate, predicate_name, predicate_args = _decode_predicate_ref(predicate_ref)
validate_result = predicate(value, *predicate_args)
if isinstance(validate_result, dict) and 'value' in validate_result:
value = validate_result['value']
elif type(validate_result) != bool:
raise Exception(
'predicate (name={}) can only return bool or dict(value=new_value) value'.format(predicate_name))
elif not validate_result:
raise ModelInvalid(u'db model validate failed: column={}, value={}, predicate={}, arguments={}'.format(
column_name, value, predicate_name, ','.join(map(str, predicate_args))
))
return value | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier none block for_statement identifier identifier block expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier list_splat identifier if_statement boolean_operator call identifier argument_list identifier identifier comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end elif_clause comparison_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier elif_clause not_operator identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier identifier call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier identifier return_statement identifier | handle predicate's return value |
def _get_key(cls, device_id):
var_name = "USER_KEY_{0:08X}".format(device_id)
if var_name not in os.environ:
raise NotFoundError("No user key could be found for devices", device_id=device_id,
expected_variable_name=var_name)
key_var = os.environ[var_name]
if len(key_var) != 64:
raise NotFoundError("User key in variable is not the correct length, should be 64 hex characters",
device_id=device_id, key_value=key_var)
try:
key = binascii.unhexlify(key_var)
except ValueError:
raise NotFoundError("User key in variable could not be decoded from hex", device_id=device_id,
key_value=key_var)
if len(key) != 32:
raise NotFoundError("User key in variable is not the correct length, should be 64 hex characters",
device_id=device_id, key_value=key_var)
return key | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier if_statement comparison_operator identifier attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier subscript attribute identifier identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause identifier block raise_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier return_statement identifier | Attempt to get a user key from an environment variable |
def on_episode_begin(self, episode, logs):
assert episode not in self.metrics
assert episode not in self.starts
self.metrics[episode] = []
self.starts[episode] = timeit.default_timer() | module function_definition identifier parameters identifier identifier identifier block assert_statement comparison_operator identifier attribute identifier identifier assert_statement comparison_operator identifier attribute identifier identifier expression_statement assignment subscript attribute identifier identifier identifier list expression_statement assignment subscript attribute identifier identifier identifier call attribute identifier identifier argument_list | Initialize metrics at the beginning of each episode |
def find_close_value(self, LIST, value):
diff = inf
for a in LIST:
if abs(value - a) < diff:
diff = abs(value - a)
result = a
return(result) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier identifier for_statement identifier identifier block if_statement comparison_operator call identifier argument_list binary_operator identifier identifier identifier block expression_statement assignment identifier call identifier argument_list binary_operator identifier identifier expression_statement assignment identifier identifier return_statement parenthesized_expression identifier | take a LIST and find the nearest value in LIST to 'value' |
async def refresh(self):
while True:
await asyncio.sleep(5/6 * self.lifetime)
request = stun.Message(message_method=stun.Method.REFRESH,
message_class=stun.Class.REQUEST)
request.attributes['LIFETIME'] = self.lifetime
await self.request(request)
logger.info('TURN allocation refreshed %s', self.relayed_address) | module function_definition identifier parameters identifier block while_statement true block expression_statement await call attribute identifier identifier argument_list binary_operator binary_operator integer integer attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute attribute identifier identifier identifier keyword_argument identifier attribute attribute identifier identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end attribute identifier identifier expression_statement await call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier | Periodically refresh the TURN allocation. |
def _calc_strain_max(self, loc_input, loc_layer, motion, *args):
return motion.calc_peak(
self.calc_strain_tf(loc_input, loc_layer)) | module function_definition identifier parameters identifier identifier identifier identifier list_splat_pattern identifier block return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier | Compute the effective strain at the center of a layer. |
def send(self):
self.log.info("Saying hello (%d)." % self.counter)
f = stomper.Frame()
f.unpack(stomper.send(DESTINATION, 'hello there (%d)' % self.counter))
self.counter += 1
self.transport.write(f.pack()) | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier binary_operator string string_start string_content string_end attribute identifier identifier expression_statement augmented_assignment attribute identifier identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list | Send out a hello message periodically. |
def draw(self):
indices = np.arange(len(self.classes_))
prev = np.zeros(len(self.classes_))
colors = resolve_colors(
colors=self.colors,
n_colors=len(self.classes_))
for idx, row in enumerate(self.predictions_):
self.ax.bar(indices, row, label=self.classes_[idx],
bottom=prev, color=colors[idx])
prev += row
return self.ax | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier call identifier argument_list attribute identifier identifier for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier keyword_argument identifier subscript attribute identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier subscript identifier identifier expression_statement augmented_assignment identifier identifier return_statement attribute identifier identifier | Renders the class prediction error across the axis. |
def write_json_to_file(self, net_type, filename, indent='no-indent'):
export_data.write_json_to_file(self, net_type, filename, indent) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier identifier identifier identifier | Save dat or viz as a JSON to file. |
def rel_path(self, other):
try:
memo_dict = self._memo['rel_path']
except KeyError:
memo_dict = {}
self._memo['rel_path'] = memo_dict
else:
try:
return memo_dict[other]
except KeyError:
pass
if self is other:
result = '.'
elif not other in self._path_elements:
try:
other_dir = other.get_dir()
except AttributeError:
result = str(other)
else:
if other_dir is None:
result = other.name
else:
dir_rel_path = self.rel_path(other_dir)
if dir_rel_path == '.':
result = other.name
else:
result = dir_rel_path + OS_SEP + other.name
else:
i = self._path_elements.index(other) + 1
path_elems = ['..'] * (len(self._path_elements) - i) \
+ [n.name for n in other._path_elements[i:]]
result = OS_SEP.join(path_elems)
memo_dict[other] = result
return result | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end except_clause identifier block expression_statement assignment identifier dictionary expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end identifier else_clause block try_statement block return_statement subscript identifier identifier except_clause identifier block pass_statement if_statement comparison_operator identifier identifier block expression_statement assignment identifier string string_start string_content string_end elif_clause not_operator comparison_operator identifier attribute identifier identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list except_clause identifier block expression_statement assignment identifier call identifier argument_list identifier else_clause block if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier binary_operator binary_operator identifier identifier attribute identifier identifier else_clause block expression_statement assignment identifier binary_operator call attribute attribute identifier identifier identifier argument_list identifier integer expression_statement assignment identifier binary_operator binary_operator list string string_start string_content string_end parenthesized_expression binary_operator call identifier argument_list attribute identifier identifier identifier line_continuation list_comprehension attribute identifier identifier for_in_clause identifier subscript attribute identifier identifier slice identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier identifier identifier return_statement identifier | Return a path to "other" relative to this directory. |
def csv_writer(csvfile):
if sys.version_info >= (3,):
writer = csv.writer(csvfile, delimiter=',', lineterminator='\n')
else:
writer = csv.writer(csvfile, delimiter=b',', lineterminator='\n')
return writer | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier tuple integer block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content escape_sequence string_end else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content escape_sequence string_end return_statement identifier | Get a CSV writer for the version of python that is being run. |
def chi_eff(self):
return conversions.chi_eff(self.mass1, self.mass2, self.spin1z,
self.spin2z) | 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 effective spin. |
def rotate_point(self, p):
p = Quaternion(0, p[0], p[1], p[2], False)
q1 = self.normalize()
q2 = self.inverse()
r = (q1*p)*q2
return r.x, r.y, r.z | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list integer subscript identifier integer subscript identifier integer subscript identifier integer false expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier identifier identifier return_statement expression_list attribute identifier identifier attribute identifier identifier attribute identifier identifier | Rotate a Point instance using this quaternion. |
def _set_subset_indices(self, y_min, y_max, x_min, x_max):
y_coords, x_coords = self.xd.lsm.coords
dx = self.xd.lsm.dx
dy = self.xd.lsm.dy
lsm_y_indices_from_y, lsm_x_indices_from_y = \
np.where((y_coords >= (y_min - 2*dy)) &
(y_coords <= (y_max + 2*dy)))
lsm_y_indices_from_x, lsm_x_indices_from_x = \
np.where((x_coords >= (x_min - 2*dx)) &
(x_coords <= (x_max + 2*dx)))
lsm_y_indices = np.intersect1d(lsm_y_indices_from_y,
lsm_y_indices_from_x)
lsm_x_indices = np.intersect1d(lsm_x_indices_from_y,
lsm_x_indices_from_x)
self.xslice = slice(np.amin(lsm_x_indices),
np.amax(lsm_x_indices)+1)
self.yslice = slice(np.amin(lsm_y_indices),
np.amax(lsm_y_indices)+1) | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment pattern_list identifier identifier attribute attribute attribute identifier identifier identifier identifier expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier expression_statement assignment pattern_list identifier identifier line_continuation call attribute identifier identifier argument_list binary_operator parenthesized_expression comparison_operator identifier parenthesized_expression binary_operator identifier binary_operator integer identifier parenthesized_expression comparison_operator identifier parenthesized_expression binary_operator identifier binary_operator integer identifier expression_statement assignment pattern_list identifier identifier line_continuation call attribute identifier identifier argument_list binary_operator parenthesized_expression comparison_operator identifier parenthesized_expression binary_operator identifier binary_operator integer identifier parenthesized_expression comparison_operator identifier parenthesized_expression binary_operator identifier binary_operator integer identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list call attribute identifier identifier argument_list identifier binary_operator call attribute identifier identifier argument_list identifier integer expression_statement assignment attribute identifier identifier call identifier argument_list call attribute identifier identifier argument_list identifier binary_operator call attribute identifier identifier argument_list identifier integer | load subset based on extent |
def validate(self):
extents_valid = (0 <= self.lower_extent <= self.upper_extent
<= self.global_size)
if not extents_valid:
raise ValueError("Dimension '{d}' fails 0 <= {el} <= {eu} <= {gs}"
.format(d=self.name, gs=self.global_size,
el=self.lower_extent, eu=self.upper_extent)) | module function_definition identifier parameters identifier block expression_statement assignment identifier parenthesized_expression comparison_operator integer attribute identifier identifier attribute identifier identifier attribute identifier identifier if_statement not_operator identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier | Validate the contents of a dimension data dictionary |
def config_cred(config, providers):
expected = ['aws', 'azure', 'gcp', 'alicloud']
cred = {}
to_remove = []
for item in providers:
if any(item.startswith(itemb) for itemb in expected):
try:
cred[item] = dict(list(config[item].items()))
except KeyError as e:
print("No credentials section in config file for {} -"
" provider will be skipped.".format(e))
to_remove.append(item)
else:
print("Unsupported provider: '{}' listed in config - ignoring"
.format(item))
to_remove.append(item)
return cred, to_remove | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier dictionary expression_statement assignment identifier list for_statement identifier identifier block if_statement call identifier generator_expression call attribute identifier identifier argument_list identifier for_in_clause identifier identifier block try_statement block expression_statement assignment subscript identifier identifier call identifier argument_list call identifier argument_list call attribute subscript identifier identifier identifier argument_list except_clause as_pattern identifier as_pattern_target identifier block expression_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 identifier expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement expression_list identifier identifier | Read credentials from configfile. |
def sech(x, context=None):
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_sech,
(BigFloat._implicit_convert(x),),
context,
) | module function_definition identifier parameters identifier default_parameter identifier none block return_statement call identifier argument_list identifier attribute identifier identifier tuple call attribute identifier identifier argument_list identifier identifier | Return the hyperbolic secant of x. |
def filter_users(self, users):
return [LeaderboardInstance(x) for x in self._leaderboard if x['user_id'] in users] | module function_definition identifier parameters identifier identifier block return_statement list_comprehension call identifier argument_list identifier for_in_clause identifier attribute identifier identifier if_clause comparison_operator subscript identifier string string_start string_content string_end identifier | Expects an interable of User IDs ints |
def precesion(date):
zeta, theta, z = np.deg2rad(_precesion(date))
return rot3(zeta) @ rot2(-theta) @ rot3(z) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list call identifier argument_list identifier return_statement binary_operator binary_operator call identifier argument_list identifier call identifier argument_list unary_operator identifier call identifier argument_list identifier | Precession as a rotation matrix |
def yaml(self):
return ordered_dump(OrderedDict(self),
Dumper=yaml.SafeDumper,
default_flow_style=False) | module function_definition identifier parameters identifier block return_statement call identifier argument_list call identifier argument_list identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier false | returns the yaml output of the dict. |
def addItem(self, item):
try:
self.tree.addItem(item)
except AttributeError, e:
raise VersionError('Saved versions are immutable') | module function_definition identifier parameters identifier identifier block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list identifier except_clause identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end | Adds an item if the tree is mutable |
def nonparabolicity(self, **kwargs):
Eg = self.Eg_Gamma(**kwargs)
meff = self.meff_e_Gamma(**kwargs)
T = kwargs.get('T', 300.)
return k*T/Eg * (1 - meff)**2 | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list dictionary_splat identifier expression_statement assignment identifier call attribute identifier identifier argument_list dictionary_splat identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end float return_statement binary_operator binary_operator binary_operator identifier identifier identifier binary_operator parenthesized_expression binary_operator integer identifier integer | Returns the Kane band nonparabolicity parameter for the Gamma-valley. |
def load_model_from_package(name, **overrides):
cls = importlib.import_module(name)
return cls.load(**overrides) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list dictionary_splat identifier | Load a model from an installed package. |
def _init_get_dict():
get_dict = {'main chain': PandasPdb._get_mainchain,
'hydrogen': PandasPdb._get_hydrogen,
'c-alpha': PandasPdb._get_calpha,
'carbon': PandasPdb._get_carbon,
'heavy': PandasPdb._get_heavy}
return get_dict | module function_definition identifier parameters block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_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 return_statement identifier | Initialize dictionary for filter operations. |
def build_progress_message(total=None,
running=None,
finished=None,
failed=None,
cached=None):
progress_message = {}
if total:
progress_message['total'] = total
if running:
progress_message['running'] = running
if finished:
progress_message['finished'] = finished
if failed:
progress_message['failed'] = failed
if cached:
progress_message['cached'] = cached
return progress_message | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier dictionary if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier return_statement identifier | Build the progress message with correct formatting. |
def execute(self, eopatch):
feature_type, feature_name = next(self.feature(eopatch))
eopatch[feature_type][feature_name] = self.process(eopatch[feature_type][feature_name])
return eopatch | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment subscript subscript identifier identifier identifier call attribute identifier identifier argument_list subscript subscript identifier identifier identifier return_statement identifier | Execute method takes EOPatch and changes the specified feature |
def dumped(text, level, indent=2):
return indented("{\n%s\n}" % indented(text, level + 1, indent) or "None", level, indent) + "\n" | module function_definition identifier parameters identifier identifier default_parameter identifier integer block return_statement binary_operator call identifier argument_list boolean_operator binary_operator string string_start string_content escape_sequence escape_sequence string_end call identifier argument_list identifier binary_operator identifier integer identifier string string_start string_content string_end identifier identifier string string_start string_content escape_sequence string_end | Put curly brackets round an indented text |
def get(self, key, *, encoding=_NOTSET):
return self.execute(b'GET', key, encoding=encoding) | module function_definition identifier parameters identifier identifier keyword_separator default_parameter identifier identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier keyword_argument identifier identifier | Get the value of a key. |
def availablePageSizes(self):
sizes = [x for x in dir(QPagedPaintDevice)
if type(getattr(QPagedPaintDevice, x)) == QPagedPaintDevice.PageSize]
return sizes | module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier call identifier argument_list identifier if_clause comparison_operator call identifier argument_list call identifier argument_list identifier identifier attribute identifier identifier return_statement identifier | List available page sizes. |
def add_list_opt(self, opt, values):
self.add_opt(opt)
for val in values:
self.add_opt(val) | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier | Add an option with a list of non-file parameters. |
def multipartite(corpus, featureset_names, min_weight=1, filters={}):
pairs = Counter()
node_type = {corpus._generate_index(p): {'type': 'paper'}
for p in corpus.papers}
for featureset_name in featureset_names:
ftypes = {}
featureset = _get_featureset(corpus, featureset_name)
for paper, feature in featureset.iteritems():
if featureset_name in filters:
if not filters[featureset_name](featureset, feature):
continue
if len(feature) < 1:
continue
for f in list(zip(*feature))[0]:
ftypes[f] = {'type': featureset_name}
pairs[(paper, f)] += 1
node_type.update(ftypes)
return _generate_graph(nx.DiGraph, pairs, node_attrs=node_type,
min_weight=min_weight) | module function_definition identifier parameters identifier identifier default_parameter identifier integer default_parameter identifier dictionary block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier dictionary_comprehension pair call attribute identifier identifier argument_list identifier dictionary pair string string_start string_content string_end string string_start string_content string_end for_in_clause identifier attribute identifier identifier for_statement identifier identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier call identifier argument_list identifier identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier identifier block if_statement not_operator call subscript identifier identifier argument_list identifier identifier block continue_statement if_statement comparison_operator call identifier argument_list identifier integer block continue_statement for_statement identifier subscript call identifier argument_list call identifier argument_list list_splat identifier integer block expression_statement assignment subscript identifier identifier dictionary pair string string_start string_content string_end identifier expression_statement augmented_assignment subscript identifier tuple identifier identifier integer expression_statement call attribute identifier identifier argument_list identifier return_statement call identifier argument_list attribute identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | A network of papers and one or more featuresets. |
def _combine_ngrams(ngrams, joiner) -> str:
if isinstance(ngrams, str):
return ngrams
else:
combined = joiner.join(ngrams)
return combined | module function_definition identifier parameters identifier identifier type identifier block if_statement call identifier argument_list identifier identifier block return_statement identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier | Construct keys for checking in trie |
def match(self, expression=None, xpath=None, namespaces=None):
class MatchObject(Dict):
pass
def _match(function):
self.matches.append(
MatchObject(expression=expression, xpath=xpath, function=function, namespaces=namespaces))
def wrapper(self, *args, **params):
return function(self, *args, **params)
return wrapper
return _match | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block class_definition identifier argument_list identifier block pass_statement function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement call identifier argument_list identifier list_splat identifier dictionary_splat identifier return_statement identifier return_statement identifier | decorator that allows us to match by expression or by xpath for each transformation method |
def _DecodeKey(self, key):
if self.dict.attrindex.HasBackward(key):
return self.dict.attrindex.GetBackward(key)
return key | module function_definition identifier parameters identifier identifier block if_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier return_statement identifier | Turn a key into a string if possible |
def from_entity(cls, entity: Entity) -> 'DictModel':
dict_obj = {}
for field_name in entity.meta_.attributes:
dict_obj[field_name] = getattr(entity, field_name)
return dict_obj | module function_definition identifier parameters identifier typed_parameter identifier type identifier type string string_start string_content string_end block expression_statement assignment identifier dictionary for_statement identifier attribute attribute identifier identifier identifier block expression_statement assignment subscript identifier identifier call identifier argument_list identifier identifier return_statement identifier | Convert the entity to a dictionary record |
def _on_ready_read(self):
while self.bytesAvailable():
if not self._header_complete:
self._read_header()
else:
self._read_payload() | module function_definition identifier parameters identifier block while_statement call attribute identifier identifier argument_list block if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list else_clause block expression_statement call attribute identifier identifier argument_list | Read bytes when ready read |
def _add_res(line):
global resource
fields = line.strip().split()
if resource:
ret.append(resource)
resource = {}
resource["resource name"] = fields[0]
resource["local role"] = fields[1].split(":")[1]
resource["local volumes"] = []
resource["peer nodes"] = [] | module function_definition identifier parameters identifier block global_statement identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier dictionary expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier integer expression_statement assignment subscript identifier string string_start string_content string_end subscript call attribute subscript identifier integer identifier argument_list string string_start string_content string_end integer expression_statement assignment subscript identifier string string_start string_content string_end list expression_statement assignment subscript identifier string string_start string_content string_end list | Analyse the line of local resource of ``drbdadm status`` |
def extra_reading_spec(self):
field_names = ("frame_number", "action", "reward", "done")
data_fields = {
name: tf.FixedLenFeature([1], tf.int64) for name in field_names
}
decoders = {
name: tf.contrib.slim.tfexample_decoder.Tensor(tensor_key=name)
for name in field_names
}
return (data_fields, decoders) | module function_definition identifier parameters identifier block expression_statement assignment identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier dictionary_comprehension pair identifier call attribute identifier identifier argument_list list integer attribute identifier identifier for_in_clause identifier identifier expression_statement assignment identifier dictionary_comprehension pair identifier call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list keyword_argument identifier identifier for_in_clause identifier identifier return_statement tuple identifier identifier | Additional data fields to store on disk and their decoders. |
def add_peer(self, peerAddr, networks=None):
if _debug: BTR._debug("add_peer %r networks=%r", peerAddr, networks)
if peerAddr in self.peers:
if not networks:
networks = []
else:
self.peers[peerAddr].extend(networks)
else:
if not networks:
networks = []
self.peers[peerAddr] = networks | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier if_statement comparison_operator identifier attribute identifier identifier block if_statement not_operator identifier block expression_statement assignment identifier list else_clause block expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list identifier else_clause block if_statement not_operator identifier block expression_statement assignment identifier list expression_statement assignment subscript attribute identifier identifier identifier identifier | Add a peer and optionally provide a list of the reachable networks. |
def _remove_pending_return(self, job, pending_returns):
tpls_to_remove = [ ]
call_stack_copy = job.call_stack_copy()
while call_stack_copy.current_return_target is not None:
ret_target = call_stack_copy.current_return_target
call_stack_copy = call_stack_copy.ret(ret_target)
call_stack_suffix = call_stack_copy.stack_suffix(self._context_sensitivity_level)
tpl = call_stack_suffix + (ret_target,)
tpls_to_remove.append(tpl)
for tpl in tpls_to_remove:
if tpl in pending_returns:
del pending_returns[tpl]
l.debug("Removed (%s) from FakeExits dict.",
",".join([hex(i) if i is not None else 'None' for i in tpl])) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier list expression_statement assignment identifier call attribute identifier identifier argument_list while_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier binary_operator identifier tuple identifier expression_statement call attribute identifier identifier argument_list identifier for_statement identifier identifier block if_statement comparison_operator identifier identifier block delete_statement subscript identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list list_comprehension conditional_expression call identifier argument_list identifier comparison_operator identifier none string string_start string_content string_end for_in_clause identifier identifier | Remove all pending returns that are related to the current job. |
def ensure_dir_does_not_exist(*args):
path = os.path.join(*args)
if os.path.isdir(path):
shutil.rmtree(path) | module function_definition identifier parameters list_splat_pattern identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list list_splat identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier | Ensures that the given directory does not exist. |
def autolink(self, raw_url, is_email):
if self.check_url(raw_url):
url = self.rewrite_url(('mailto:' if is_email else '') + raw_url)
url = escape_html(url)
return '<a href="%s">%s</a>' % (url, escape_html(raw_url))
else:
return escape_html('<%s>' % raw_url) | module function_definition identifier parameters identifier identifier identifier block if_statement call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator parenthesized_expression conditional_expression string string_start string_content string_end identifier string string_start string_end identifier expression_statement assignment identifier call identifier argument_list identifier return_statement binary_operator string string_start string_content string_end tuple identifier call identifier argument_list identifier else_clause block return_statement call identifier argument_list binary_operator string string_start string_content string_end identifier | Filters links generated by the ``autolink`` extension. |
def _unparse_changetype(self, mod_len):
if mod_len == 2:
changetype = 'add'
elif mod_len == 3:
changetype = 'modify'
else:
raise ValueError("modlist item of wrong length")
self._unparse_attr('changetype', changetype) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier integer block expression_statement assignment identifier string string_start string_content string_end elif_clause comparison_operator identifier integer block expression_statement assignment identifier string string_start string_content string_end else_clause block raise_statement call identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier | Detect and write the changetype. |
def vectorize_raw(audio: np.ndarray) -> np.ndarray:
if len(audio) == 0:
raise InvalidAudio('Cannot vectorize empty audio!')
return vectorizers[pr.vectorizer](audio) | module function_definition identifier parameters typed_parameter identifier type attribute identifier identifier type attribute identifier identifier block if_statement comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list string string_start string_content string_end return_statement call subscript identifier attribute identifier identifier argument_list identifier | Turns audio into feature vectors, without clipping for length |
def prettify(amount, separator=','):
orig = str(amount)
new = re.sub("^(-?\d+)(\d{3})", "\g<1>{0}\g<2>".format(separator), str(amount))
if orig == new:
return new
else:
return prettify(new) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier call identifier argument_list identifier if_statement comparison_operator identifier identifier block return_statement identifier else_clause block return_statement call identifier argument_list identifier | Separate with predefined separator. |
def to_json(value, **kwargs):
if isinstance(value, HasProperties):
return value.serialize(**kwargs)
try:
return json.loads(json.dumps(value))
except TypeError:
raise TypeError(
"Cannot convert type {} to JSON without calling 'serialize' "
"on an instance of Instance Property and registering a custom "
"serializer".format(value.__class__.__name__)
) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block if_statement call identifier argument_list identifier identifier block return_statement call attribute identifier identifier argument_list dictionary_splat identifier try_statement block return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier except_clause identifier block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier | Convert instance to JSON |
def _get(self):
user = self.USER
try:
uid = pwd.getpwnam(user).pw_uid
except KeyError:
log.info('User does not exist')
return False
cmd = self.gsetting_command + ['get', str(self.SCHEMA), str(self.KEY)]
environ = {}
environ['XDG_RUNTIME_DIR'] = '/run/user/{0}'.format(uid)
result = __salt__['cmd.run_all'](cmd, runas=user, env=environ, python_shell=False)
if 'stdout' in result:
if 'uint32' in result['stdout']:
return re.sub('uint32 ', '', result['stdout'])
else:
return result['stdout']
else:
return False | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier try_statement block expression_statement assignment identifier attribute call attribute identifier identifier argument_list identifier identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement false expression_statement assignment identifier binary_operator attribute identifier identifier list string string_start string_content string_end call identifier argument_list attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier dictionary expression_statement assignment subscript identifier string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call subscript identifier string string_start string_content string_end argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier false if_statement comparison_operator string string_start string_content string_end identifier block if_statement comparison_operator string string_start string_content string_end subscript identifier string string_start string_content string_end block return_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end subscript identifier string string_start string_content string_end else_clause block return_statement subscript identifier string string_start string_content string_end else_clause block return_statement false | get the value for user in gsettings |
def _adapt_response(self, response):
errors, meta = super(ServerError, self)._adapt_response(response)
return errors[0], meta | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute call identifier argument_list identifier identifier identifier argument_list identifier return_statement expression_list subscript identifier integer identifier | Convert various error responses to standardized ErrorDetails. |
async def _send_rtcp_pli(self, media_ssrc):
if self.__rtcp_ssrc is not None:
packet = RtcpPsfbPacket(fmt=RTCP_PSFB_PLI, ssrc=self.__rtcp_ssrc, media_ssrc=media_ssrc)
await self._send_rtcp(packet) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier expression_statement await call attribute identifier identifier argument_list identifier | Send an RTCP packet to report picture loss. |
def pseudo_core_density(self):
mesh, values, attrib = self._parse_radfunc("pseudo_core_density")
return RadialFunction(mesh, values) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement call identifier argument_list identifier identifier | The pseudized radial density. |
def disable_reporting(self):
self.reporting = False
msg = bytearray([REPORT_DIGITAL + self.port_number, 0])
self.board.sp.write(msg) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier false expression_statement assignment identifier call identifier argument_list list binary_operator identifier attribute identifier identifier integer expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier | Disable the reporting of the port. |
def _batch_entry(self):
try:
while True:
self._batch_entry_run()
except:
self.exc_info = sys.exc_info()
os.kill(self.pid, signal.SIGUSR1) | module function_definition identifier parameters identifier block try_statement block while_statement true block expression_statement call attribute identifier identifier argument_list except_clause block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier | Entry point for the batcher thread. |
def run(self, bin, *args, **kwargs):
bin = self._bin(bin)
cmd = [bin] + list(args)
shell = kwargs.get("shell", False)
call = kwargs.pop("call", False)
input_ = kwargs.pop("input_", None)
if shell:
cmd = list_to_shell_command(cmd)
try:
if self._is_windows:
kwargs["shell"] = True
if input_:
p = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
**kwargs
)
output = p.communicate(encode(input_))[0]
elif call:
return subprocess.call(cmd, stderr=subprocess.STDOUT, **kwargs)
else:
output = subprocess.check_output(
cmd, stderr=subprocess.STDOUT, **kwargs
)
except CalledProcessError as e:
raise EnvCommandError(e)
return decode(output) | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator list identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end false expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end false expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier try_statement block if_statement attribute identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end true if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier dictionary_splat identifier expression_statement assignment identifier subscript call attribute identifier identifier argument_list call identifier argument_list identifier integer elif_clause identifier block return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier dictionary_splat identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier dictionary_splat identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list identifier return_statement call identifier argument_list identifier | Run a command inside the Python environment. |
def find_validation_workspaces(name, rounds=None):
workspaces = []
if rounds is not None:
rounds = indices_from_str(rounds)
else:
rounds = itertools.count(1)
for round in rounds:
workspace = pipeline.ValidatedDesigns(name, round)
if not workspace.exists(): break
workspaces.append(workspace)
if not workspaces:
scripting.print_error_and_die('No validated designs found.')
return workspaces | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier list if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list integer for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement not_operator call attribute identifier identifier argument_list block break_statement expression_statement call attribute identifier identifier argument_list identifier if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier | Find all the workspaces containing validated designs. |
def _document_root(self, fully_qualified=True):
nsmap = {"xsi": utils.NAMESPACES["xsi"], "xlink": utils.NAMESPACES["xlink"]}
if fully_qualified:
nsmap["mets"] = utils.NAMESPACES["mets"]
else:
nsmap[None] = utils.NAMESPACES["mets"]
attrib = {
"{}schemaLocation".format(utils.lxmlns("xsi")): utils.SCHEMA_LOCATIONS
}
if self.objid:
attrib["OBJID"] = self.objid
return etree.Element(utils.lxmlns("mets") + "mets", nsmap=nsmap, attrib=attrib) | module function_definition identifier parameters identifier default_parameter identifier true block expression_statement assignment identifier dictionary pair string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end pair string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end else_clause block expression_statement assignment subscript identifier none subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier dictionary pair call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier return_statement call attribute identifier identifier argument_list binary_operator call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier | Return the mets Element for the document root. |
def as_enum(enum):
if isinstance(enum, string_types):
try:
enum = getattr(gl, 'GL_' + enum.upper())
except AttributeError:
try:
enum = _internalformats['GL_' + enum.upper()]
except KeyError:
raise ValueError('Could not find int value for enum %r' % enum)
return enum | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier binary_operator string string_start string_content string_end call attribute identifier identifier argument_list except_clause identifier block try_statement block expression_statement assignment identifier subscript identifier binary_operator string string_start string_content string_end call attribute identifier identifier argument_list except_clause identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier return_statement identifier | Turn a possibly string enum into an integer enum. |
def close(self):
if not (yield from super().close()):
return False
nio = self._ethernet_adapter.get_nio(0)
if isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
if self._local_udp_tunnel:
self.manager.port_manager.release_udp_port(self._local_udp_tunnel[0].lport, self._project)
self.manager.port_manager.release_udp_port(self._local_udp_tunnel[1].lport, self._project)
self._local_udp_tunnel = None
yield from self._stop_ubridge()
if self.is_running():
self._terminate_process()
return True | module function_definition identifier parameters identifier block if_statement not_operator parenthesized_expression yield call attribute call identifier argument_list identifier argument_list block return_statement false expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list integer if_statement call identifier argument_list identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier if_statement attribute identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute subscript attribute identifier identifier integer identifier attribute identifier identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute subscript attribute identifier identifier integer identifier attribute identifier identifier expression_statement assignment attribute identifier identifier none expression_statement yield call attribute identifier identifier argument_list if_statement call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list return_statement true | Closes this VPCS VM. |
def next(self):
base_depth = self.__root.count(os.path.sep)
for root, subFolders, files in os.walk(self.__root):
if not self.filter_folder(root):
continue
if self.__depth_limit is not None:
curr_depth = root.count(os.path.sep)
if curr_depth - base_depth > self.__depth_limit:
continue
if self.__ret_folders:
yield root
if self.__ret_files:
for f in files:
yield os.path.join(root, f)
raise StopIteration | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier for_statement pattern_list identifier identifier identifier call attribute identifier identifier argument_list attribute identifier identifier block if_statement not_operator call attribute identifier identifier argument_list identifier block continue_statement if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier if_statement comparison_operator binary_operator identifier identifier attribute identifier identifier block continue_statement if_statement attribute identifier identifier block expression_statement yield identifier if_statement attribute identifier identifier block for_statement identifier identifier block expression_statement yield call attribute attribute identifier identifier identifier argument_list identifier identifier raise_statement identifier | Return all files in folder. |
def tail(self, fname, encoding, window, position=None):
if window <= 0:
raise ValueError('invalid window %r' % window)
encodings = ENCODINGS
if encoding:
encodings = [encoding] + ENCODINGS
for enc in encodings:
try:
f = self.open(encoding=enc)
if f:
return self.tail_read(f, window, position=position)
return False
except IOError, err:
if err.errno == errno.ENOENT:
return []
raise
except UnicodeDecodeError:
pass | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none block if_statement comparison_operator identifier integer block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier identifier if_statement identifier block expression_statement assignment identifier binary_operator list identifier identifier for_statement identifier identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier if_statement identifier block return_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier identifier return_statement false except_clause identifier identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block return_statement list raise_statement except_clause identifier block pass_statement | Read last N lines from file fname. |
def getAllNodes(self):
ret = TagCollection()
for tag in self:
ret.append(tag)
ret += tag.getAllChildNodes()
return ret | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement augmented_assignment identifier call attribute identifier identifier argument_list return_statement identifier | getAllNodes - Gets all the nodes, and all their children for every node within this collection |
def extract_energy(rate, sig):
mfcc = python_speech_features.mfcc(sig, rate, appendEnergy=True)
energy_row_vec = mfcc[:, 0]
energy_col_vec = energy_row_vec[:, np.newaxis]
return energy_col_vec | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier keyword_argument identifier true expression_statement assignment identifier subscript identifier slice integer expression_statement assignment identifier subscript identifier slice attribute identifier identifier return_statement identifier | Extracts the energy of frames. |
def autodocs():
"create Sphinx docs locally, and start a watchdog"
build_dir = path('docs/_build')
index_html = build_dir / 'html/index.html'
if build_dir.exists():
build_dir.rmtree()
with pushd("docs"):
print "\n*** Generating API doc ***\n"
sh("sphinx-apidoc -o apidoc -f -T -M ../src/pyrocore")
sh("sphinx-apidoc -o apidoc -f -T -M $(dirname $(python -c 'import tempita; print(tempita.__file__)'))")
print "\n*** Generating HTML doc ***\n"
sh('nohup %s/Makefile SPHINXBUILD="sphinx-autobuild -p %d'
' -i \'.*\' -i \'*.log\' -i \'*.png\' -i \'*.txt\'" html >autobuild.log 2>&1 &'
% (os.getcwd(), SPHINX_AUTOBUILD_PORT))
for i in range(25):
time.sleep(2.5)
pid = watchdog_pid()
if pid:
sh("touch docs/index.rst")
sh('ps {}'.format(pid))
url = 'http://localhost:{port:d}/'.format(port=SPHINX_AUTOBUILD_PORT)
print("\n*** Open '{}' in your browser...".format(url))
break | module function_definition identifier parameters block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list string string_start string_content string_end expression_statement assignment identifier binary_operator identifier string string_start string_content string_end if_statement call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list with_statement with_clause with_item call identifier argument_list string string_start string_content string_end block print_statement string string_start string_content escape_sequence escape_sequence string_end expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end print_statement string string_start string_content escape_sequence escape_sequence string_end expression_statement call identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content escape_sequence escape_sequence escape_sequence escape_sequence escape_sequence escape_sequence escape_sequence escape_sequence string_end tuple call attribute identifier identifier argument_list identifier for_statement identifier call identifier argument_list integer block expression_statement call attribute identifier identifier argument_list float expression_statement assignment identifier call identifier argument_list if_statement identifier block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier expression_statement call identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier break_statement | create Sphinx docs locally, and start a watchdog |
def _fixed_width_info(self, lines):
for string in lines:
for line in [string[i:i+80] for i in range(0, len(string), 80)]:
msg.info(line)
msg.blank() | module function_definition identifier parameters identifier identifier block for_statement identifier identifier block for_statement identifier list_comprehension subscript identifier slice identifier binary_operator identifier integer for_in_clause identifier call identifier argument_list integer call identifier argument_list identifier integer block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | Prints the specified string as information with fixed width of 80 chars. |
def _enum_member_error(err, eid, name, value, bitmask):
exception, msg = ENUM_ERROR_MAP[err]
enum_name = idaapi.get_enum_name(eid)
return exception(('add_enum_member(enum="{}", member="{}", value={}, bitmask=0x{:08X}) '
'failed: {}').format(
enum_name,
name,
value,
bitmask,
msg
)) | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment pattern_list identifier identifier subscript identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call identifier argument_list call attribute parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier identifier identifier identifier identifier | Format enum member error. |
def rosen(self, x, alpha=1e2):
x = [x] if isscalar(x[0]) else x
f = [sum(alpha * (x[:-1]**2 - x[1:])**2 + (1. - x[:-1])**2) for x in x]
return f if len(f) > 1 else f[0] | module function_definition identifier parameters identifier identifier default_parameter identifier float block expression_statement assignment identifier conditional_expression list identifier call identifier argument_list subscript identifier integer identifier expression_statement assignment identifier list_comprehension call identifier argument_list binary_operator binary_operator identifier binary_operator parenthesized_expression binary_operator binary_operator subscript identifier slice unary_operator integer integer subscript identifier slice integer integer binary_operator parenthesized_expression binary_operator float subscript identifier slice unary_operator integer integer for_in_clause identifier identifier return_statement conditional_expression identifier comparison_operator call identifier argument_list identifier integer subscript identifier integer | Rosenbrock test objective function |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.