code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def add_node_to_network(self, node, network):
network.add_node(node)
node.receive()
environment = network.nodes(type=Environment)[0]
environment.connect(whom=node)
gene = node.infos(type=LearningGene)[0].contents
if (gene == "social"):
prev_agents = RogersAgent.query\
.filter(and_(RogersAgent.failed == False,
RogersAgent.network_id == network.id,
RogersAgent.generation == node.generation - 1))\
.all()
parent = random.choice(prev_agents)
parent.connect(whom=node)
parent.transmit(what=Meme, to_whom=node)
elif (gene == "asocial"):
environment.transmit(to_whom=node)
else:
raise ValueError("{} has invalid learning gene value of {}"
.format(node, gene))
node.receive() | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier subscript call attribute identifier identifier argument_list keyword_argument identifier identifier integer expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier attribute subscript call attribute identifier identifier argument_list keyword_argument identifier identifier integer identifier if_statement parenthesized_expression comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute call attribute attribute identifier identifier line_continuation identifier argument_list call identifier argument_list comparison_operator attribute identifier identifier false comparison_operator attribute identifier identifier attribute identifier identifier comparison_operator attribute identifier identifier binary_operator attribute identifier identifier integer line_continuation identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier elif_clause parenthesized_expression comparison_operator identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier else_clause block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list | Add participant's node to a network. |
def postParse(self, original, loc, tokens):
return ComputationNode(self._combine, original, loc, tokens, ignore_no_tokens=True, ignore_one_token=True) | module function_definition identifier parameters identifier identifier identifier identifier block return_statement call identifier argument_list attribute identifier identifier identifier identifier identifier keyword_argument identifier true keyword_argument identifier true | Create a ComputationNode for Combine. |
def __AddEntryType(self, entry_type_name, entry_schema, parent_name):
entry_schema.pop('description', None)
description = 'Single entry in a %s.' % parent_name
schema = {
'id': entry_type_name,
'type': 'object',
'description': description,
'properties': {
'entry': {
'type': 'array',
'items': entry_schema,
},
},
}
self.AddDescriptorFromSchema(entry_type_name, schema)
return entry_type_name | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end none expression_statement assignment identifier binary_operator string string_start string_content string_end identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end identifier pair string string_start string_content string_end dictionary pair string string_start string_content string_end dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier identifier return_statement identifier | Add a type for a list entry. |
def getLiteral(self):
chars = u''
c = self.current()
while True:
if c and c == u"\\":
c = self.next()
if c:
chars += c
continue
elif not c or (c in self.meta_chars):
break
else:
chars += c
if self.lookahead() and self.lookahead() in self.meta_chars:
break
c = self.next()
return StringGenerator.Literal(chars) | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_end expression_statement assignment identifier call attribute identifier identifier argument_list while_statement true block if_statement boolean_operator identifier comparison_operator identifier string string_start string_content escape_sequence string_end block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement identifier block expression_statement augmented_assignment identifier identifier continue_statement elif_clause boolean_operator not_operator identifier parenthesized_expression comparison_operator identifier attribute identifier identifier block break_statement else_clause block expression_statement augmented_assignment identifier identifier if_statement boolean_operator call attribute identifier identifier argument_list comparison_operator call attribute identifier identifier argument_list attribute identifier identifier block break_statement expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list identifier | Get a sequence of non-special characters. |
def export_metrics(self, metrics):
metric_protos = []
for metric in metrics:
metric_protos.append(_get_metric_proto(metric))
self._rpc_handler.send(
metrics_service_pb2.ExportMetricsServiceRequest(
metrics=metric_protos)) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier identifier | Exports given metrics to target metric service. |
def _ensureinmemory(self):
self._setbytes_unsafe(self._datastore.getbyteslice(0, self._datastore.bytelength),
self.len, self._offset) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list integer attribute attribute identifier identifier identifier attribute identifier identifier attribute identifier identifier | Ensure the data is held in memory, not in a file. |
def display_initialize(self):
echo(self.term.home + self.term.clear)
echo(self.term.move_y(self.term.height // 2))
echo(self.term.center('Initializing page data ...').rstrip())
flushout()
if LIMIT_UCS == 0x10000:
echo('\n\n')
echo(self.term.blink_red(self.term.center(
'narrow Python build: upperbound value is {n}.'
.format(n=LIMIT_UCS)).rstrip()))
echo('\n\n')
flushout() | module function_definition identifier parameters identifier block expression_statement call identifier argument_list binary_operator attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier expression_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list binary_operator attribute attribute identifier identifier identifier integer expression_statement call identifier argument_list call attribute call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier argument_list expression_statement call identifier argument_list if_statement comparison_operator identifier integer block expression_statement call identifier argument_list string string_start string_content escape_sequence escape_sequence string_end expression_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list call attribute call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier identifier argument_list expression_statement call identifier argument_list string string_start string_content escape_sequence escape_sequence string_end expression_statement call identifier argument_list | Display 'please wait' message, and narrow build warning. |
def nextpow2(value):
if value >= 1:
return 2**np.ceil(np.log2(value)).astype(int)
elif value > 0:
return 1
elif value == 0:
return 0
else:
raise ValueError('Value must be positive') | module function_definition identifier parameters identifier block if_statement comparison_operator identifier integer block return_statement binary_operator integer call attribute call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier argument_list identifier elif_clause comparison_operator identifier integer block return_statement integer elif_clause comparison_operator identifier integer block return_statement integer else_clause block raise_statement call identifier argument_list string string_start string_content string_end | Compute the nearest power of two greater or equal to the input value |
def _from_dict(cls, _dict):
args = {}
if 'types' in _dict:
args['types'] = [
TypeLabel._from_dict(x) for x in (_dict.get('types'))
]
else:
raise ValueError(
'Required property \'types\' not present in OriginalLabelsIn JSON'
)
if 'categories' in _dict:
args['categories'] = [
Category._from_dict(x) for x in (_dict.get('categories'))
]
else:
raise ValueError(
'Required property \'categories\' not present in OriginalLabelsIn JSON'
)
return cls(**args) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier parenthesized_expression call attribute identifier identifier argument_list string string_start string_content string_end else_clause block raise_statement call identifier argument_list string string_start string_content escape_sequence escape_sequence string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier parenthesized_expression call attribute identifier identifier argument_list string string_start string_content string_end else_clause block raise_statement call identifier argument_list string string_start string_content escape_sequence escape_sequence string_end return_statement call identifier argument_list dictionary_splat identifier | Initialize a OriginalLabelsIn object from a json dictionary. |
def tick_all(self, times):
for i in range(times):
for avg in (self.m1, self.m5, self.m15, self.day):
avg.tick() | module function_definition identifier parameters identifier identifier block for_statement identifier call identifier argument_list identifier block for_statement identifier tuple attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list | Tick all the EWMAs for the given number of times |
def init(init_type='plaintext_tcp', *args, **kwargs):
global _module_instance
reset()
validate_init_types = ['plaintext_tcp', 'plaintext', 'pickle_tcp',
'pickle', 'plain']
if init_type not in validate_init_types:
raise GraphiteSendException(
"Invalid init_type '%s', must be one of: %s" %
(init_type, ", ".join(validate_init_types)))
if init_type in ['plaintext_tcp', 'plaintext', 'plain']:
_module_instance = GraphiteClient(*args, **kwargs)
if init_type in ['pickle_tcp', 'pickle']:
_module_instance = GraphitePickleClient(*args, **kwargs)
return _module_instance | module function_definition identifier parameters default_parameter identifier string string_start string_content string_end list_splat_pattern identifier dictionary_splat_pattern identifier block global_statement identifier expression_statement call identifier argument_list expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier call attribute string string_start string_content string_end identifier argument_list identifier if_statement comparison_operator identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list list_splat identifier dictionary_splat identifier if_statement comparison_operator identifier list string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list list_splat identifier dictionary_splat identifier return_statement identifier | Create the module instance of the GraphiteClient. |
def make_temp(text):
import tempfile
(handle, path) = tempfile.mkstemp(text=True)
os.close(handle)
afile = File(path)
afile.write(text)
return afile | module function_definition identifier parameters identifier block import_statement dotted_name identifier expression_statement assignment tuple_pattern identifier identifier call attribute identifier identifier argument_list keyword_argument identifier true expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Creates a temprorary file and writes the `text` into it |
def focusNextPrevChild(self, next_child):
fd = focus_registry.focused_declaration()
if next_child:
child = self.declaration.next_focus_child(fd)
reason = Qt.TabFocusReason
else:
child = self.declaration.previous_focus_child(fd)
reason = Qt.BacktabFocusReason
if child is not None and child.proxy_is_active:
return child.proxy.tab_focus_request(reason)
widget = self.widget
return type(widget).focusNextPrevChild(widget, next_child) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier attribute identifier identifier if_statement boolean_operator comparison_operator identifier none attribute identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier attribute identifier identifier return_statement call attribute call identifier argument_list identifier identifier argument_list identifier identifier | The default 'focusNextPrevChild' implementation. |
def _parity_interaction(q0: ops.Qid,
q1: ops.Qid,
rads: float,
atol: float,
gate: Optional[ops.Gate] = None):
if abs(rads) < atol:
return
if gate is not None:
g = cast(ops.Gate, gate)
yield g.on(q0), g.on(q1)
yield MS(-1 * rads).on(q0, q1)
if gate is not None:
g = protocols.inverse(gate)
yield g.on(q0), g.on(q1) | module function_definition identifier parameters typed_parameter identifier type attribute identifier identifier typed_parameter identifier type attribute identifier identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_default_parameter identifier type generic_type identifier type_parameter type attribute identifier identifier none block if_statement comparison_operator call identifier argument_list identifier identifier block return_statement if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier expression_statement yield expression_list call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier expression_statement yield call attribute call identifier argument_list binary_operator unary_operator integer identifier identifier argument_list identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement yield expression_list call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier | Yields an XX interaction framed by the given operation. |
def print_equations(self):
print("P_static: ", self.eqn_st)
print("P_thermal: ", self.eqn_th)
print("P_anharmonic: ", self.eqn_anh)
print("P_electronic: ", self.eqn_el) | module function_definition identifier parameters identifier block expression_statement call identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list string string_start string_content string_end attribute identifier identifier | show equations used for the EOS |
def iterable_hook(self, name, iterable):
for record in iterable:
self(name, record)
yield record | module function_definition identifier parameters identifier identifier identifier block for_statement identifier identifier block expression_statement call identifier argument_list identifier identifier expression_statement yield identifier | Fire an event named ``name`` with each item in iterable |
def update_dropdown_list_slot(self):
self.dropdown_widget.clear()
self.row_instance_by_index = []
for i, key in enumerate(self.row_instance_by_name.keys()):
row_instance = self.row_instance_by_name[key]
if (row_instance.isActive()):
self.row_instance_by_index.append(row_instance)
display_name = row_instance.getName()
self.dropdown_widget.insertItem(i, display_name)
row_instance.updateWidget() | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier list for_statement pattern_list identifier identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier subscript attribute identifier identifier identifier if_statement parenthesized_expression call attribute identifier identifier argument_list block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list | Keep updating the dropdown list. Say, don't let the user choose USB devices if none is available |
def _drop(self, table, existing_tables=None):
existing_tables = existing_tables if existing_tables else self.tables
if table in existing_tables:
self.execute('SET FOREIGN_KEY_CHECKS = 0')
query = 'DROP TABLE {0}'.format(wrap(table))
self.execute(query)
self.execute('SET FOREIGN_KEY_CHECKS = 1')
self._printer('\tDropped table {0}'.format(table)) | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier conditional_expression identifier identifier attribute identifier identifier if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier | Private method for executing table drop commands. |
def initialize(self):
if 'EnErrorStyle' not in self._vim.vars:
self._vim.vars['EnErrorStyle'] = 'EnError'
self._vim.command('highlight EnErrorStyle ctermbg=red gui=underline')
self._vim.command('set omnifunc=EnCompleteFunc')
self._vim.command(
'autocmd FileType package_info nnoremap <buffer> <Space> :call EnPackageDecl()<CR>')
self._vim.command('autocmd FileType package_info setlocal splitright') | module function_definition identifier parameters identifier block if_statement comparison_operator string string_start string_content string_end attribute attribute identifier identifier identifier block expression_statement assignment subscript attribute attribute identifier identifier identifier string string_start string_content string_end string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end | Sets up initial ensime-vim editor settings. |
def send_key(self, key):
if isinstance(key, Keys):
key = key.value
params = '<X_KeyEvent>{}</X_KeyEvent>'.format(key)
self.soap_request(URL_CONTROL_NRC, URN_REMOTE_CONTROL,
'X_SendKey', params) | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier string string_start string_content string_end identifier | Send a key command to the TV. |
def views(self):
if self._views:
return self._views
elif not self.abstract:
return self.read_meta()._views
raise EmptyDocumentException() | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement attribute identifier identifier elif_clause not_operator attribute identifier identifier block return_statement attribute call attribute identifier identifier argument_list identifier raise_statement call identifier argument_list | Number of views this document has received on ProvStore |
def resend_unprocessed(self):
LOG.info("Re-sending %d unprocessed items.", len(self._unprocessed))
while self._unprocessed:
to_resend = self._unprocessed[:MAX_WRITE_BATCH]
self._unprocessed = self._unprocessed[MAX_WRITE_BATCH:]
LOG.info("Sending %d items", len(to_resend))
self._write(to_resend)
LOG.info("%d unprocessed items left", len(self._unprocessed)) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list attribute identifier identifier while_statement attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier slice identifier expression_statement assignment attribute identifier identifier subscript attribute identifier identifier slice identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list attribute identifier identifier | Resend all unprocessed items |
def handle_tokennetwork_new(raiden: 'RaidenService', event: Event):
data = event.event_data
args = data['args']
block_number = data['block_number']
token_network_address = args['token_network_address']
token_address = typing.TokenAddress(args['token_address'])
block_hash = data['block_hash']
token_network_proxy = raiden.chain.token_network(token_network_address)
raiden.blockchain_events.add_token_network_listener(
token_network_proxy=token_network_proxy,
contract_manager=raiden.contract_manager,
from_block=block_number,
)
token_network_state = TokenNetworkState(
token_network_address,
token_address,
)
transaction_hash = event.event_data['transaction_hash']
new_token_network = ContractReceiveNewTokenNetwork(
transaction_hash=transaction_hash,
payment_network_identifier=event.originating_contract,
token_network=token_network_state,
block_number=block_number,
block_hash=block_hash,
)
raiden.handle_and_track_state_change(new_token_network) | module function_definition identifier parameters typed_parameter identifier type string string_start string_content string_end typed_parameter identifier type identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Handles a `TokenNetworkCreated` event. |
def output_colored(code, text, is_bold=False):
if is_bold:
code = '1;%s' % code
return '\033[%sm%s\033[0m' % (code, text) | module function_definition identifier parameters identifier identifier default_parameter identifier false block if_statement identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier return_statement binary_operator string string_start string_content escape_sequence escape_sequence string_end tuple identifier identifier | Create function to output with color sequence |
def AddRow(self, *args):
NumRows = len(self.Rows)
CurrentRowNumber = NumRows
CurrentRow = []
for i, element in enumerate(args):
element.Position = (CurrentRowNumber, i)
element.ParentContainer = self
CurrentRow.append(element)
self.Rows.append(CurrentRow) | module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier identifier expression_statement assignment identifier list for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement assignment attribute identifier identifier tuple identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Parms are a variable number of Elements |
def fgseq(code):
if isinstance(code, str):
code = nametonum(code)
if code == -1:
return ""
s = termcap.get('setaf', code) or termcap.get('setf', code)
return s | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier unary_operator integer block return_statement string string_start string_end expression_statement assignment identifier boolean_operator call attribute identifier identifier argument_list string string_start string_content string_end identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement identifier | Returns the forground color terminal escape sequence for the given color code number or color name. |
def _verify_authentication(self, handler, args, kwargs):
if not self.user_manager.session_logged_in():
raise APIForbidden()
return handler(*args, **kwargs) | module function_definition identifier parameters identifier identifier identifier identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list block raise_statement call identifier argument_list return_statement call identifier argument_list list_splat identifier dictionary_splat identifier | Verify that the user is authenticated |
def delete_mongo(database_name, collection_name,
query={}, just_one=False):
l = []
response_dict = {}
try:
mongodb_client_url = getattr(settings, 'MONGODB_CLIENT',
'mongodb://localhost:27017/')
mc = MongoClient(mongodb_client_url, document_class=OrderedDict)
db = mc[str(database_name)]
collection = db[str(collection_name)]
mysearchresult = collection.remove(query, just_one)
response_dict['code'] = 200
response_dict['type'] = "remove-confirmation"
except:
response_dict['num_results'] = 0
response_dict['code'] = 500
response_dict['type'] = "Error"
response_dict['results'] = []
response_dict['message'] = str(sys.exc_info())
return response_dict | module function_definition identifier parameters identifier identifier default_parameter identifier dictionary default_parameter identifier false block expression_statement assignment identifier list expression_statement assignment identifier dictionary try_statement block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier subscript identifier call identifier argument_list identifier expression_statement assignment identifier subscript identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end integer expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end except_clause block expression_statement assignment subscript identifier string string_start string_content string_end integer expression_statement assignment subscript identifier string string_start string_content string_end integer expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end 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 call identifier argument_list call attribute identifier identifier argument_list return_statement identifier | delete from mongo helper |
def add_data_point_xy(self, x, y):
self.x.append(x)
self.y.append(y) | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Add a new data point to the data set to be smoothed. |
def crack_k_from_sigs(generator, sig1, val1, sig2, val2):
r1, s1 = sig1
r2, s2 = sig2
if r1 != r2:
raise ValueError("r values of signature do not match")
k = (r2 * val1 - r1 * val2) * generator.inverse(r2 * s1 - r1 * s2)
return k % generator.order() | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier expression_statement assignment pattern_list identifier identifier identifier if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier binary_operator parenthesized_expression binary_operator binary_operator identifier identifier binary_operator identifier identifier call attribute identifier identifier argument_list binary_operator binary_operator identifier identifier binary_operator identifier identifier return_statement binary_operator identifier call attribute identifier identifier argument_list | Given two signatures with the same secret exponent and K value, return that K value. |
def _credit_card_type(self, card_type=None):
if card_type is None:
card_type = self.random_element(self.credit_card_types.keys())
elif isinstance(card_type, CreditCard):
return card_type
return self.credit_card_types[card_type] | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list elif_clause call identifier argument_list identifier identifier block return_statement identifier return_statement subscript attribute identifier identifier identifier | Returns a random credit card type instance. |
def RegisterBuiltin(cls, arg):
if arg in cls.types_dict:
raise RuntimeError, '%s already registered' %arg
class _Wrapper(arg):
'Wrapper for builtin %s\n%s' %(arg, cls.__doc__)
_Wrapper.__name__ = '_%sWrapper' %arg.__name__
cls.types_dict[arg] = _Wrapper | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block raise_statement expression_list identifier binary_operator string string_start string_content string_end identifier class_definition identifier argument_list identifier block expression_statement binary_operator string string_start string_content escape_sequence string_end tuple identifier attribute identifier identifier expression_statement assignment attribute identifier identifier binary_operator string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier | register a builtin, create a new wrapper. |
def handle_read(self):
while True:
try:
c = self.recv(1)
except socket.error as e:
if e.errno == errno.EWOULDBLOCK:
return
else:
raise
else:
self._do(c)
self.socket.setblocking(True)
self.send(b'A')
self.socket.setblocking(False) | module function_definition identifier parameters identifier block while_statement true block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list integer except_clause as_pattern attribute identifier identifier as_pattern_target identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block return_statement else_clause block raise_statement else_clause block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list true expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list false | Handle all the available character commands in the socket |
def to_internal_value(self, data):
course_id = data
course_video = image = ''
if data:
if isinstance(data, dict):
(course_id, image), = list(data.items())
course_video = CourseVideo(course_id=course_id)
course_video.full_clean(exclude=['video'])
return course_video, image | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier identifier expression_statement assignment identifier assignment identifier string string_start string_end if_statement identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment pattern_list tuple_pattern identifier identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier list string string_start string_content string_end return_statement expression_list identifier identifier | Convert data into CourseVideo instance and image filename tuple. |
def _colored_time(self, time_taken, color=None):
if self.timer_no_color:
return "{0:0.4f}s".format(time_taken)
return _colorize("{0:0.4f}s".format(time_taken), color) | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement attribute identifier identifier block return_statement call attribute string string_start string_content string_end identifier argument_list identifier return_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier | Get formatted and colored string for a given time taken. |
def unhook_drop(self):
widget = self.widget
widget.setAcceptDrops(False)
del widget.dragEnterEvent
del widget.dragMoveEvent
del widget.dragLeaveEvent
del widget.dropEvent | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list false delete_statement attribute identifier identifier delete_statement attribute identifier identifier delete_statement attribute identifier identifier delete_statement attribute identifier identifier | Remove hooks for drop operations. |
def fetch_datatype(self, bucket, key, r=None, pr=None, basic_quorum=None,
notfound_ok=None, timeout=None, include_context=None):
raise NotImplementedError | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block raise_statement identifier | Fetches a Riak Datatype. |
def easybake(css_in, html_in=sys.stdin, html_out=sys.stdout, last_step=None,
coverage_file=None, use_repeatable_ids=False):
html_doc = etree.parse(html_in)
oven = Oven(css_in, use_repeatable_ids)
oven.bake(html_doc, last_step)
print(etree.tostring(html_doc, method="xml").decode('utf-8'),
file=html_out)
if coverage_file:
print('SF:{}'.format(css_in.name), file=coverage_file)
print(oven.get_coverage_report(), file=coverage_file)
print('end_of_record', file=coverage_file) | module function_definition identifier parameters identifier default_parameter identifier attribute identifier identifier default_parameter identifier attribute identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call identifier argument_list call attribute call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end keyword_argument identifier identifier if_statement identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier 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 string string_start string_content string_end keyword_argument identifier identifier | Process the given HTML file stream with the css stream. |
def mouse_release_event(self, x, y, button):
if button == 1:
print("Left mouse button released @", x, y)
if button == 2:
print("Right mouse button released @", x, y) | module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator identifier integer block expression_statement call identifier argument_list string string_start string_content string_end identifier identifier if_statement comparison_operator identifier integer block expression_statement call identifier argument_list string string_start string_content string_end identifier identifier | Reports left and right mouse button releases + position |
def convert_string_to_number(value):
if value is None:
return 1
if isinstance(value, int):
return value
if value.isdigit():
return int(value)
num_list = map(lambda s: NUMBERS[s], re.findall(numbers + '+', value.lower()))
return sum(num_list) | module function_definition identifier parameters identifier block if_statement comparison_operator identifier none block return_statement integer if_statement call identifier argument_list identifier identifier block return_statement identifier if_statement call attribute identifier identifier argument_list block return_statement call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list lambda lambda_parameters identifier subscript identifier identifier call attribute identifier identifier argument_list binary_operator identifier string string_start string_content string_end call attribute identifier identifier argument_list return_statement call identifier argument_list identifier | Convert strings to numbers |
def configure_next_batch_of_vlans(self, switch_ip):
next_range = self._pop_vlan_range(
switch_ip, const.CREATE_VLAN_BATCH)
if next_range:
try:
self.driver.set_all_vlan_states(
switch_ip, next_range)
except Exception:
with excutils.save_and_reraise_exception():
LOG.error("Error encountered restoring vlans "
"for switch %(switch_ip)s",
{'switch_ip': switch_ip})
self._save_switch_vlan_range(switch_ip, [])
vxlan_range = self._get_switch_vxlan_range(switch_ip)
if vxlan_range:
try:
self._restore_vxlan_entries(switch_ip, vxlan_range)
except Exception:
with excutils.save_and_reraise_exception():
LOG.error("Error encountered restoring vxlans "
"for switch %(switch_ip)s",
{'switch_ip': switch_ip})
self._save_switch_vxlan_range(switch_ip, [])
if (not self._get_switch_vlan_range(switch_ip) and
not self._get_switch_vxlan_range(switch_ip)):
self.set_switch_ip_and_active_state(
switch_ip, const.SWITCH_ACTIVE)
LOG.info("Restore of Nexus switch "
"ip %(switch_ip)s is complete",
{'switch_ip': switch_ip})
else:
LOG.debug(("Restored batch of VLANS on "
"Nexus switch ip %(switch_ip)s"),
{'switch_ip': switch_ip}) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier if_statement identifier block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier except_clause identifier block with_statement with_clause with_item call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end dictionary pair string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier list expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block try_statement block expression_statement call attribute identifier identifier argument_list identifier identifier except_clause identifier block with_statement with_clause with_item call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end dictionary pair string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier list if_statement parenthesized_expression boolean_operator not_operator call attribute identifier identifier argument_list identifier not_operator call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end dictionary pair string string_start string_content string_end identifier else_clause block expression_statement call attribute identifier identifier argument_list parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end dictionary pair string string_start string_content string_end identifier | Get next batch of vlans and send them to Nexus. |
def commiter_factory(config: dict) -> BaseCommitizen:
name: str = config["name"]
try:
_cz = registry[name](config)
except KeyError:
msg_error = (
"The commiter has not been found in the system.\n\n"
f"Try running 'pip install {name}'\n"
)
out.error(msg_error)
raise SystemExit(NO_COMMITIZEN_FOUND)
else:
return _cz | module function_definition identifier parameters typed_parameter identifier type identifier type identifier block expression_statement assignment identifier type identifier subscript identifier string string_start string_content string_end try_statement block expression_statement assignment identifier call subscript identifier identifier argument_list identifier except_clause identifier block expression_statement assignment identifier parenthesized_expression concatenated_string string string_start string_content escape_sequence escape_sequence string_end string string_start string_content interpolation identifier string_content escape_sequence string_end expression_statement call attribute identifier identifier argument_list identifier raise_statement call identifier argument_list identifier else_clause block return_statement identifier | Return the correct commitizen existing in the registry. |
def unquote(s):
i, N = 1, len(s) - 1
ret = []
while i < N:
if s[i] == '\\' and i < N - 1:
ret.append(UNQUOTE_MAP.get(s[i+1], s[i+1]))
i += 2
else:
ret.append(s[i])
i += 1
return ''.join(ret) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier expression_list integer binary_operator call identifier argument_list identifier integer expression_statement assignment identifier list while_statement comparison_operator identifier identifier block if_statement boolean_operator comparison_operator subscript identifier identifier string string_start string_content escape_sequence string_end comparison_operator identifier binary_operator identifier integer block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list subscript identifier binary_operator identifier integer subscript identifier binary_operator identifier integer expression_statement augmented_assignment identifier integer else_clause block expression_statement call attribute identifier identifier argument_list subscript identifier identifier expression_statement augmented_assignment identifier integer return_statement call attribute string string_start string_end identifier argument_list identifier | Unquote the indicated string. |
def run_deps(self, conf, images):
for dependency_name, detached in conf.dependency_images(for_running=True):
try:
self.run_container(images[dependency_name], images, detach=detached, dependency=True)
except Exception as error:
raise BadImage("Failed to start dependency container", image=conf.name, dependency=dependency_name, error=error) | module function_definition identifier parameters identifier identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list keyword_argument identifier true block try_statement block expression_statement call attribute identifier identifier argument_list subscript identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier true except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Start containers for all our dependencies |
def _apply_concretization_strategies(self, idx, strategies, action):
for s in strategies:
try:
idxes = s.concretize(self, idx)
except SimUnsatError:
idxes = None
if idxes:
return idxes
raise SimMemoryAddressError("Unable to concretize index %s" % idx) | module function_definition identifier parameters identifier identifier identifier identifier block for_statement identifier identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier except_clause identifier block expression_statement assignment identifier none if_statement identifier block return_statement identifier raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier | Applies concretization strategies on the index, until one of them succeeds. |
async def delay(source, delay):
await asyncio.sleep(delay)
async with streamcontext(source) as streamer:
async for item in streamer:
yield item | module function_definition identifier parameters identifier identifier block expression_statement await call attribute identifier identifier argument_list identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block for_statement identifier identifier block expression_statement yield identifier | Delay the iteration of an asynchronous sequence. |
def v_type_extension(ctx, stmt):
(modulename, identifier) = stmt.keyword
revision = stmt.i_extension_revision
module = modulename_to_module(stmt.i_module, modulename, revision)
if module is None:
return
if identifier not in module.i_extensions:
if module.i_modulename == stmt.i_orig_module.i_modulename:
if identifier not in stmt.i_orig_module.i_extensions:
err_add(ctx.errors, stmt.pos, 'EXTENSION_NOT_DEFINED',
(identifier, module.arg))
return
else:
stmt.i_extension = stmt.i_orig_module.i_extensions[identifier]
else:
err_add(ctx.errors, stmt.pos, 'EXTENSION_NOT_DEFINED',
(identifier, module.arg))
return
else:
stmt.i_extension = module.i_extensions[identifier]
ext_arg = stmt.i_extension.search_one('argument')
if stmt.arg is not None and ext_arg is None:
err_add(ctx.errors, stmt.pos, 'EXTENSION_ARGUMENT_PRESENT',
identifier)
elif stmt.arg is None and ext_arg is not None:
err_add(ctx.errors, stmt.pos, 'EXTENSION_NO_ARGUMENT_PRESENT',
identifier) | module function_definition identifier parameters identifier identifier block expression_statement assignment tuple_pattern identifier identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier identifier if_statement comparison_operator identifier none block return_statement if_statement comparison_operator identifier attribute identifier identifier block if_statement comparison_operator attribute identifier identifier attribute attribute identifier identifier identifier block if_statement comparison_operator identifier attribute attribute identifier identifier identifier block expression_statement call identifier argument_list attribute identifier identifier attribute identifier identifier string string_start string_content string_end tuple identifier attribute identifier identifier return_statement else_clause block expression_statement assignment attribute identifier identifier subscript attribute attribute identifier identifier identifier identifier else_clause block expression_statement call identifier argument_list attribute identifier identifier attribute identifier identifier string string_start string_content string_end tuple identifier attribute identifier identifier return_statement else_clause block expression_statement assignment attribute identifier identifier subscript attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement boolean_operator comparison_operator attribute identifier identifier none comparison_operator identifier none block expression_statement call identifier argument_list attribute identifier identifier attribute identifier identifier string string_start string_content string_end identifier elif_clause boolean_operator comparison_operator attribute identifier identifier none comparison_operator identifier none block expression_statement call identifier argument_list attribute identifier identifier attribute identifier identifier string string_start string_content string_end identifier | verify that the extension matches the extension definition |
def process_events(self):
for event, args in iter_except(self.event_queue.popleft, IndexError):
for callback in self.event_callbacks[event]:
callback(*args) | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call identifier argument_list attribute attribute identifier identifier identifier identifier block for_statement identifier subscript attribute identifier identifier identifier block expression_statement call identifier argument_list list_splat identifier | Processes any events in the queue. |
def start(self, service):
try:
map(self.start_class, service.depends)
if service.is_running():
return
if service in self.failed:
log.warning("%s previously failed to start", service)
return
service.start()
except Exception:
log.exception("Unable to start service %s", service)
self.failed.add(service) | module function_definition identifier parameters identifier identifier block try_statement block expression_statement call identifier argument_list attribute identifier identifier attribute identifier identifier if_statement call attribute identifier identifier argument_list block return_statement if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement expression_statement call attribute identifier identifier argument_list except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Start the service, catching and logging exceptions |
def CheckFont(page, fontname):
for f in page.getFontList():
if f[4] == fontname:
return f
if f[3].lower() == fontname.lower():
return f
return None | module function_definition identifier parameters identifier identifier block for_statement identifier call attribute identifier identifier argument_list block if_statement comparison_operator subscript identifier integer identifier block return_statement identifier if_statement comparison_operator call attribute subscript identifier integer identifier argument_list call attribute identifier identifier argument_list block return_statement identifier return_statement none | Return an entry in the page's font list if reference name matches. |
def execute_with_delay(task_function, *args, **kwargs):
delay = kwargs.pop('delay', 0)
if get_setting('TEST_DISABLE_ASYNC_DELAY'):
logger.debug('Running function "%s" synchronously because '\
'TEST_DISABLE_ASYNC_DELAY is True'
% task_function.__name__)
return task_function(*args, **kwargs)
db.connections.close_all()
task_function.apply_async(args=args, kwargs=kwargs, countdown=delay) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end integer if_statement call identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end attribute identifier identifier return_statement call identifier argument_list list_splat identifier dictionary_splat identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Run a task asynchronously after at least delay_seconds |
def trim_zeros(self):
tmp = self.numpy()
f = len(self)-len(_numpy.trim_zeros(tmp, trim='f'))
b = len(self)-len(_numpy.trim_zeros(tmp, trim='b'))
return self[f:len(self)-b] | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator call identifier argument_list identifier call identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier binary_operator call identifier argument_list identifier call identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end return_statement subscript identifier slice identifier binary_operator call identifier argument_list identifier identifier | Remove the leading and trailing zeros. |
def darken_color(color, amount):
color = [int(col * (1 - amount)) for col in hex_to_rgb(color)]
return rgb_to_hex(color) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list_comprehension call identifier argument_list binary_operator identifier parenthesized_expression binary_operator integer identifier for_in_clause identifier call identifier argument_list identifier return_statement call identifier argument_list identifier | Darken a hex color. |
def _fetch(self, searchtype, fields, **kwargs):
fields['vintage'] = self.vintage
fields['benchmark'] = self.benchmark
fields['format'] = 'json'
if 'layers' in kwargs:
fields['layers'] = kwargs['layers']
returntype = kwargs.get('returntype', 'geographies')
url = self._geturl(searchtype, returntype)
try:
with requests.get(url, params=fields, timeout=kwargs.get('timeout')) as r:
content = r.json()
if "addressMatches" in content.get('result', {}):
return AddressResult(content)
if "geographies" in content.get('result', {}):
return GeographyResult(content)
raise ValueError()
except (ValueError, KeyError):
raise ValueError("Unable to parse response from Census")
except RequestException as e:
raise e | module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier try_statement block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end dictionary block return_statement call identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end dictionary block return_statement call identifier argument_list identifier raise_statement call identifier argument_list except_clause tuple identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end except_clause as_pattern identifier as_pattern_target identifier block raise_statement identifier | Fetch a response from the Geocoding API. |
def release(self, conn):
if conn.in_transaction:
raise InvalidRequestError(
"Cannot release a connection with "
"not finished transaction"
)
raw = conn.connection
res = yield from self._pool.release(raw)
return res | module function_definition identifier parameters identifier identifier block if_statement attribute 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 expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier yield call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier | Revert back connection to pool. |
def name_from_path(self):
name = os.path.splitext(os.path.basename(self.path))[0]
if name == 'catalog':
name = os.path.basename(os.path.dirname(self.path))
return name.replace('.', '_') | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier integer if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier return_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end | If catalog is named 'catalog' take name from parent directory |
def cli(env, identifier, count):
mgr = SoftLayer.TicketManager(env.client)
ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket')
env.fout(ticket.get_ticket_results(mgr, ticket_id, update_count=count)) | 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 attribute identifier identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier keyword_argument identifier identifier | Get details for a ticket. |
def change_path_prefix(self, path, old_prefix, new_prefix, app_name):
relative_path = os.path.relpath(path, old_prefix)
return os.path.join(new_prefix, app_name, relative_path) | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier return_statement call attribute attribute identifier identifier identifier argument_list identifier identifier identifier | Change path prefix and include app name. |
def read_all_from_datastore(self):
self._work = {}
client = self._datastore_client
parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id)
for entity in client.query_fetch(kind=KIND_WORK, ancestor=parent_key):
work_id = entity.key.flat_path[-1]
self.work[work_id] = dict(entity) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier dictionary expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier for_statement identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier block expression_statement assignment identifier subscript attribute attribute identifier identifier identifier unary_operator integer expression_statement assignment subscript attribute identifier identifier identifier call identifier argument_list identifier | Reads all work pieces from the datastore. |
def _norm_slice(sl, start, stop):
length = stop - start
if sl.start is None:
normstart = 0
else:
if sl.start < 0:
if sl.start < -length:
normstart = 0
else:
normstart = sl.start + length
else:
if sl.start > stop:
normstart = length
else:
normstart = sl.start - start
if sl.stop is None:
normstop = length
else:
if sl.stop < 0:
if sl.stop < -length:
normstop = 0
else:
normstop = sl.stop + length
else:
if sl.stop > stop:
normstop = length
else:
normstop = sl.stop - start
if normstop < normstart:
normstop = normstart
return slice(normstart, normstop) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier integer else_clause block if_statement comparison_operator attribute identifier identifier integer block if_statement comparison_operator attribute identifier identifier unary_operator identifier block expression_statement assignment identifier integer else_clause block expression_statement assignment identifier binary_operator attribute identifier identifier identifier else_clause block if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier binary_operator attribute identifier identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier identifier else_clause block if_statement comparison_operator attribute identifier identifier integer block if_statement comparison_operator attribute identifier identifier unary_operator identifier block expression_statement assignment identifier integer else_clause block expression_statement assignment identifier binary_operator attribute identifier identifier identifier else_clause block if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier binary_operator attribute identifier identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier identifier return_statement call identifier argument_list identifier identifier | Return a slice normalized to an farray start index. |
def delete(self, *args, **kwargs):
storage_ids = list(self.storages.values_list('pk', flat=True))
super().delete(*args, **kwargs)
Storage.objects.filter(pk__in=storage_ids, data=None).delete() | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier true expression_statement call attribute call identifier argument_list identifier argument_list list_splat identifier dictionary_splat identifier expression_statement call attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier none identifier argument_list | Delete the data model. |
def _api_wrapper(fn):
def _convert(value):
if isinstance(value, _datetime.date):
return value.strftime('%s')
return value
@_six.wraps(fn)
def _fn(self, command, **params):
with self.startup_lock:
if self.timer.ident is None:
self.timer.setDaemon(True)
self.timer.start()
params = dict((key, _convert(value))
for key, value in _six.iteritems(params)
if value is not None)
self.semaphore.acquire()
resp = fn(self, command, **params)
try:
respdata = resp.json(object_hook=_AutoCastDict)
except:
resp.raise_for_status()
raise Exception('No JSON object could be decoded')
if 'error' in respdata:
raise PoloniexCommandException(respdata['error'])
resp.raise_for_status()
return respdata
return _fn | module function_definition identifier parameters identifier block function_definition identifier parameters identifier block if_statement call identifier argument_list identifier attribute identifier identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier decorated_definition decorator call attribute identifier identifier argument_list identifier function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block with_statement with_clause with_item attribute identifier identifier block if_statement comparison_operator attribute attribute identifier identifier identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list true expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call identifier generator_expression tuple identifier call identifier argument_list identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list identifier if_clause comparison_operator identifier none expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier identifier dictionary_splat identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier except_clause block expression_statement call attribute identifier identifier argument_list raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block raise_statement call identifier argument_list subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list return_statement identifier return_statement identifier | API function decorator that performs rate limiting and error checking. |
def compute_mean_reward(rollouts, clipped):
reward_name = "reward" if clipped else "unclipped_reward"
rewards = []
for rollout in rollouts:
if rollout[-1].done:
rollout_reward = sum(getattr(frame, reward_name) for frame in rollout)
rewards.append(rollout_reward)
if rewards:
mean_rewards = np.mean(rewards)
else:
mean_rewards = 0
return mean_rewards | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier conditional_expression string string_start string_content string_end identifier string string_start string_content string_end expression_statement assignment identifier list for_statement identifier identifier block if_statement attribute subscript identifier unary_operator integer identifier block expression_statement assignment identifier call identifier generator_expression call identifier argument_list identifier identifier for_in_clause identifier identifier expression_statement call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment identifier integer return_statement identifier | Calculate mean rewards from given epoch. |
def _get_c_string(data, position):
end = data.index(b"\x00", position)
return _utf_8_decode(data[position:end], None, True)[0], end + 1 | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end identifier return_statement expression_list subscript call identifier argument_list subscript identifier slice identifier identifier none true integer binary_operator identifier integer | Decode a BSON 'C' string to python unicode string. |
def _safe_gremlin_list(inner_type, argument_value):
if not isinstance(argument_value, list):
raise GraphQLInvalidArgumentError(u'Attempting to represent a non-list as a list: '
u'{}'.format(argument_value))
stripped_type = strip_non_null_from_type(inner_type)
components = (
_safe_gremlin_argument(stripped_type, x)
for x in argument_value
)
return u'[' + u','.join(components) + u']' | module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier 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 identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier generator_expression call identifier argument_list identifier identifier for_in_clause identifier identifier return_statement binary_operator binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier string string_start string_content string_end | Represent the list of "inner_type" objects in Gremlin form. |
def _list_nodes(call=None):
local = salt.client.LocalClient()
ret = local.cmd('salt-cloud:driver:vagrant', 'grains.items', '', tgt_type='grain')
return ret | module function_definition identifier parameters default_parameter identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_end keyword_argument identifier string string_start string_content string_end return_statement identifier | List the nodes, ask all 'vagrant' minions, return dict of grains. |
def terminate(self):
if self._closed:
return
self._check_init()
for ch in self._holders:
ch.terminate()
self._closed = True | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement expression_statement call attribute identifier identifier argument_list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier true | Terminate all connections in the pool. |
def clear_thumbnails(self):
state = self.state
for l in state.layers:
keys = state.layers[l].keys()[:]
for key in keys:
if (isinstance(state.layers[l][key], SlipThumbnail)
and not isinstance(state.layers[l][key], SlipIcon)):
state.layers[l].pop(key) | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier for_statement identifier attribute identifier identifier block expression_statement assignment identifier subscript call attribute subscript attribute identifier identifier identifier identifier argument_list slice for_statement identifier identifier block if_statement parenthesized_expression boolean_operator call identifier argument_list subscript subscript attribute identifier identifier identifier identifier identifier not_operator call identifier argument_list subscript subscript attribute identifier identifier identifier identifier identifier block expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list identifier | clear all thumbnails from the map |
def _safe_match_string(value):
if not isinstance(value, six.string_types):
if isinstance(value, bytes):
value = value.decode('utf-8')
else:
raise GraphQLInvalidArgumentError(u'Attempting to convert a non-string into a string: '
u'{}'.format(value))
return json.dumps(value) | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier attribute identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end else_clause block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier | Sanitize and represent a string argument in MATCH. |
def _create_put_request(self, resource, billomat_id, command=None, send_data=None):
assert (isinstance(resource, str))
if isinstance(billomat_id, int):
billomat_id = str(billomat_id)
if not command:
command = ''
else:
command = '/' + command
response = self.session.put(
url=self.api_url + resource + '/' + billomat_id + command,
data=json.dumps(send_data),
)
return self._handle_response(response) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier none block assert_statement parenthesized_expression call identifier argument_list identifier identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator identifier block expression_statement assignment identifier string string_start string_end else_clause block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier binary_operator binary_operator binary_operator binary_operator attribute identifier identifier identifier string string_start string_content string_end identifier identifier keyword_argument identifier call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier | Creates a put request and return the response data |
def list_projects(self):
data = self._run(
url_path="projects/list"
)
projects = data['result'].get('projects', [])
return [self._project_formatter(item) for item in projects] | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end list return_statement list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier identifier | Returns the list of projects owned by user. |
def create_xml(self, useNamespace=False):
UNTL_NAMESPACE = 'http://digital2.library.unt.edu/untl/'
UNTL = '{%s}' % UNTL_NAMESPACE
NSMAP = {'untl': UNTL_NAMESPACE}
if useNamespace:
root = Element(UNTL + self.tag, nsmap=NSMAP)
else:
root = Element(self.tag)
self.sort_untl(UNTL_XML_ORDER)
for element in self.children:
if useNamespace:
create_untl_xml_subelement(root, element, UNTL)
else:
create_untl_xml_subelement(root, element)
return root | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier binary_operator string string_start string_content string_end identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier if_statement identifier block expression_statement assignment identifier call identifier argument_list binary_operator identifier attribute identifier identifier keyword_argument identifier identifier else_clause block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier for_statement identifier attribute identifier identifier block if_statement identifier block expression_statement call identifier argument_list identifier identifier identifier else_clause block expression_statement call identifier argument_list identifier identifier return_statement identifier | Create an ElementTree representation of the object. |
def copy(self):
self_copy = self.dup()
self_copy._scopes = copy.copy(self._scopes)
return self_copy | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier | Return a copy of this object. |
def strictly_decreasing(values):
return all(x > y for x, y in zip(values, values[1:])) | module function_definition identifier parameters identifier block return_statement call identifier generator_expression comparison_operator identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list identifier subscript identifier slice integer | True if values are stricly decreasing. |
def raster(times, indices, max_time=None, max_index=None,
x_label="Timestep", y_label="Index", **kwargs):
if 's' not in kwargs:
kwargs['s'] = 1
scatter(times, indices, **kwargs)
if max_time is None:
max_time = max(times)
if max_index is None:
max_index = max(indices)
axis((0, max_time, 0, max_index))
if x_label is not None: xlabel(x_label)
if y_label is not None: ylabel(y_label) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end dictionary_splat_pattern identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end integer expression_statement call identifier argument_list identifier identifier dictionary_splat identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list identifier expression_statement call identifier argument_list tuple integer identifier integer identifier if_statement comparison_operator identifier none block expression_statement call identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement call identifier argument_list identifier | Plots a raster plot given times and indices of events. |
def fetchall(self):
try:
self.repo.remotes.origin.fetch()
except git.exc.GitCommandError as err:
raise GitError(err) | module function_definition identifier parameters identifier block try_statement block expression_statement call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list except_clause as_pattern attribute attribute identifier identifier identifier as_pattern_target identifier block raise_statement call identifier argument_list identifier | Fetch all refs from the upstream repo. |
def preload(python_data: LdapObject, database: Optional[Database] = None) -> LdapObject:
changes = {}
def preload_item(value: Any) -> Any:
if isinstance(value, NotLoaded):
return value.load(database)
else:
return value
for name in python_data.keys():
value_list = python_data.get_as_list(name)
if isinstance(value_list, NotLoadedObject):
raise RuntimeError(f"{name}: Unexpected NotLoadedObject outside list.")
elif isinstance(value_list, NotLoadedList):
value_list = value_list.load(database)
else:
if any(isinstance(v, NotLoadedList) for v in value_list):
raise RuntimeError(f"{name}: Unexpected NotLoadedList in list.")
elif any(isinstance(v, NotLoadedObject) for v in value_list):
value_list = [preload_item(value) for value in value_list]
else:
value_list = None
if value_list is not None:
changes[name] = value_list
return python_data.merge(changes) | module function_definition identifier parameters typed_parameter identifier type identifier typed_default_parameter identifier type generic_type identifier type_parameter type identifier none type identifier block expression_statement assignment identifier dictionary function_definition identifier parameters typed_parameter identifier type identifier type identifier block if_statement call identifier argument_list identifier identifier block return_statement call attribute identifier identifier argument_list identifier else_clause block return_statement identifier for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call identifier argument_list identifier identifier block raise_statement call identifier argument_list string string_start interpolation identifier string_content string_end elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier else_clause block if_statement call identifier generator_expression call identifier argument_list identifier identifier for_in_clause identifier identifier block raise_statement call identifier argument_list string string_start interpolation identifier string_content string_end elif_clause call identifier generator_expression call identifier argument_list identifier identifier for_in_clause identifier identifier block expression_statement assignment identifier list_comprehension call identifier argument_list identifier for_in_clause identifier identifier else_clause block expression_statement assignment identifier none if_statement comparison_operator identifier none block expression_statement assignment subscript identifier identifier identifier return_statement call attribute identifier identifier argument_list identifier | Preload all NotLoaded fields in LdapObject. |
def server_systems(self):
response = self._post(self.apiurl + "/v2/server/systems", data={'apikey': self.apikey})
return self._raise_or_extract(response) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator attribute identifier identifier string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content string_end attribute identifier identifier return_statement call attribute identifier identifier argument_list identifier | Retrieve a list of available systems. |
def leaveEvent(self, event):
super(CallTipWidget, self).leaveEvent(event)
self._leave_event_hide() | module function_definition identifier parameters identifier identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | Reimplemented to start the hide timer. |
def global_exclude(self, pattern):
match = translate_pattern(os.path.join('**', pattern))
return self._remove_files(match.match) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list attribute identifier identifier | Exclude all files anywhere that match the pattern. |
def _compute_counts_from_intensity(intensity, bexpcube):
data = intensity.data * np.sqrt(bexpcube.data[1:] * bexpcube.data[0:-1])
return HpxMap(data, intensity.hpx) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator attribute identifier identifier call attribute identifier identifier argument_list binary_operator subscript attribute identifier identifier slice integer subscript attribute identifier identifier slice integer unary_operator integer return_statement call identifier argument_list identifier attribute identifier identifier | Make the counts map from the intensity |
def remap_link_target(path, absolute=False):
if path.startswith('@'):
return static_url(path[1:], absolute=absolute)
if absolute:
return urllib.parse.urljoin(flask.request.url, path)
return path | module function_definition identifier parameters identifier default_parameter identifier false block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block return_statement call identifier argument_list subscript identifier slice integer keyword_argument identifier identifier if_statement identifier block return_statement call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier identifier return_statement identifier | remap a link target to a static URL if it's prefixed with @ |
def svg2rlg(path, **kwargs):
"Convert an SVG file to an RLG Drawing object."
unzipped = False
if isinstance(path, str) and os.path.splitext(path)[1].lower() == ".svgz":
with gzip.open(path, 'rb') as f_in, open(path[:-1], 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
path = path[:-1]
unzipped = True
svg_root = load_svg_file(path)
if svg_root is None:
return
svgRenderer = SvgRenderer(path, **kwargs)
drawing = svgRenderer.render(svg_root)
if unzipped:
os.remove(path)
return drawing | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier false if_statement boolean_operator call identifier argument_list identifier identifier comparison_operator call attribute subscript call attribute attribute identifier identifier identifier argument_list identifier integer identifier argument_list string string_start string_content string_end block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier with_item as_pattern call identifier argument_list subscript identifier slice unary_operator integer string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier subscript identifier slice unary_operator integer expression_statement assignment identifier true expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier none block return_statement expression_statement assignment identifier call identifier argument_list identifier dictionary_splat identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Convert an SVG file to an RLG Drawing object. |
def sync_focus(self, *_):
if self.display_popup:
self.app.layout.focus(self.layout_manager.popup_dialog)
return
if self.confirm_text:
return
if self.prompt_command:
return
if self.command_mode:
return
if not self.pymux.arrangement.windows:
return
pane = self.pymux.arrangement.get_active_pane()
self.app.layout.focus(pane.terminal) | module function_definition identifier parameters identifier list_splat_pattern identifier block if_statement attribute identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute attribute identifier identifier identifier return_statement if_statement attribute identifier identifier block return_statement if_statement attribute identifier identifier block return_statement if_statement attribute identifier identifier block return_statement if_statement not_operator attribute attribute attribute identifier identifier identifier identifier block return_statement expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier | Focus the focused window from the pymux arrangement. |
def guess_type(s):
sc = s.replace(',', '')
try:
return int(sc)
except ValueError:
pass
try:
return float(sc)
except ValueError:
pass
return s | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end try_statement block return_statement call identifier argument_list identifier except_clause identifier block pass_statement try_statement block return_statement call identifier argument_list identifier except_clause identifier block pass_statement return_statement identifier | attempt to convert string value into numeric type |
def generate_wf_state_log(self):
output = '\n- - - - - -\n'
output += "WORKFLOW: %s ( %s )" % (self.current.workflow_name.upper(),
self.current.workflow.name)
output += "\nTASK: %s ( %s )\n" % (self.current.task_name, self.current.task_type)
output += "DATA:"
for k, v in self.current.task_data.items():
if v:
output += "\n\t%s: %s" % (k, v)
output += "\nCURRENT:"
output += "\n\tACTIVITY: %s" % self.current.activity
output += "\n\tPOOL: %s" % self.current.pool
output += "\n\tIN EXTERNAL: %s" % self.wf_state['in_external']
output += "\n\tLANE: %s" % self.current.lane_name
output += "\n\tTOKEN: %s" % self.current.token
sys._zops_wf_state_log = output
return output | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content escape_sequence escape_sequence string_end expression_statement augmented_assignment identifier binary_operator string string_start string_content string_end tuple call attribute attribute attribute identifier identifier identifier identifier argument_list attribute attribute attribute identifier identifier identifier identifier expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end tuple attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier expression_statement augmented_assignment identifier string string_start string_content string_end for_statement pattern_list identifier identifier call attribute attribute attribute identifier identifier identifier identifier argument_list block if_statement identifier block expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end tuple identifier identifier expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end attribute attribute identifier identifier identifier expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end attribute attribute identifier identifier identifier expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end subscript attribute identifier identifier string string_start string_content string_end expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end attribute attribute identifier identifier identifier expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end attribute attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier return_statement identifier | Logs the state of workflow and content of task_data. |
def write(self, message, flush=False):
with self.lock:
self.paralell_stream.erase()
super(Clean, self).write(message, flush) | module function_definition identifier parameters identifier identifier default_parameter identifier false block with_statement with_clause with_item attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier identifier | Write something on the default stream with a prefixed message |
def two_way_portal(self, other, **stats):
return self.character.new_portal(
self, other, symmetrical=True, **stats
) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block return_statement call attribute attribute identifier identifier identifier argument_list identifier identifier keyword_argument identifier true dictionary_splat identifier | Connect these nodes with a two-way portal and return it. |
def to_dict(self):
d = {}
if self.query_params_match is not None:
d['@query_params_match'] = self.query_params_match
if self.query_person_match is not None:
d['@query_person_match'] = self.query_person_match
if self.valid_since is not None:
d['@valid_since'] = datetime_to_str(self.valid_since)
if self.source is not None:
d['source'] = self.source.to_dict()
d.update(self.fields_to_dict())
return d | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list return_statement identifier | Return a dict representation of the record. |
def federation(self):
url = self._url + "/federation"
return _Federation(url=url,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port) | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator attribute identifier identifier string string_start string_content string_end return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier | returns the class that controls federation |
def attributes(self):
attrs = self._schema["attributes"]
return [item_attribute(attr) for attr in sorted(attrs.values(),
key=operator.itemgetter("defindex"))] | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end return_statement list_comprehension call identifier argument_list identifier for_in_clause identifier call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end | Returns all attributes in the schema |
def recurse(node, *args, **kwargs):
fwd = dict()
for node_info in _NODE_INFO_TABLE.values():
fwd[node_info.handler] = kwargs.get(node_info.handler, None)
fwd["depth"] = 0
_recurse(node, *args, **fwd) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment subscript identifier attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier none expression_statement assignment subscript identifier string string_start string_content string_end integer expression_statement call identifier argument_list identifier list_splat identifier dictionary_splat identifier | Entry point for AST recursion. |
def retrieve(self, *args, **kwargs):
lookup, key = self._lookup(*args, **kwargs)
return lookup[key] | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list list_splat identifier dictionary_splat identifier return_statement subscript identifier identifier | Retrieve the permsission function for the provided things. |
def guard_rollback_to_open(worksheet):
for analysis in worksheet.getAnalyses():
if api.get_review_status(analysis) in ["assigned"]:
return True
return False | module function_definition identifier parameters identifier block for_statement identifier call attribute identifier identifier argument_list block if_statement comparison_operator call attribute identifier identifier argument_list identifier list string string_start string_content string_end block return_statement true return_statement false | Return whether 'rollback_to_receive' transition can be performed or not |
def exception(self):
buf = traceback.format_exception_only(self.exc_type, self.exc_value)
rv = "".join(buf).strip()
return to_unicode(rv, "utf-8", "replace") | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute call attribute string string_start string_end identifier argument_list identifier identifier argument_list return_statement call identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end | String representation of the exception. |
def _postgenerate(self, res):
hp, hc = res
try:
hp = taper_timeseries(hp, tapermethod=self.current_params['taper'])
hc = taper_timeseries(hc, tapermethod=self.current_params['taper'])
except KeyError:
pass
return hp, hc | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier identifier try_statement block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier subscript attribute identifier identifier string string_start string_content string_end except_clause identifier block pass_statement return_statement expression_list identifier identifier | Applies a taper if it is in current params. |
def show(self, id):
stats = self.stats()
if stats:
print("=" * 60)
print("Profile of RDD<id=%d>" % id)
print("=" * 60)
stats.sort_stats("time", "cumulative").print_stats() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end integer expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end integer expression_statement call attribute call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier argument_list | Print the profile stats to stdout, id is the RDD id |
def record_migration(plugin, filename, script, **kwargs):
db = get_db()
db.eval(RECORD_WRAPPER, plugin, filename, script)
return True | module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list identifier identifier identifier identifier return_statement true | Only record a migration without applying it |
def remove(self, idxs):
import utool as ut
keep_idxs = ut.index_complement(idxs, len(self))
return self.take(keep_idxs) | module function_definition identifier parameters identifier identifier block import_statement aliased_import dotted_name identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier call identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier | Returns a copy with idxs removed |
def update_check(package_name, package_version, bypass_cache=False, url=None,
**extra_data):
checker = UpdateChecker(url)
checker.bypass_cache = bypass_cache
result = checker.check(package_name, package_version, **extra_data)
if result:
print(result) | module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier none dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier dictionary_splat identifier if_statement identifier block expression_statement call identifier argument_list identifier | Convenience method that outputs to stdout if an update is available. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.