code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def connect(self):
if not driver_ok:
logger.error("Visa driver NOT ok")
return False
visa_backend = '@py'
if hasattr(settings, 'VISA_BACKEND'):
visa_backend = settings.VISA_BACKEND
try:
self.rm = visa.ResourceManager(visa_backend)
except:
logger.error("Visa ResourceManager cannot load resources : %s" %self)
return False
try:
resource_prefix = self._device.visadevice.resource_name.split('::')[0]
extras = {}
if hasattr(settings, 'VISA_DEVICE_SETTINGS'):
if resource_prefix in settings.VISA_DEVICE_SETTINGS:
extras = settings.VISA_DEVICE_SETTINGS[resource_prefix]
logger.debug('VISA_DEVICE_SETTINGS for %s: %r'%(resource_prefix,extras))
self.inst = self.rm.open_resource(self._device.visadevice.resource_name, **extras)
except:
logger.error("Visa ResourceManager cannot open resource : %s" %self._device.visadevice.resource_name)
return False
logger.debug('connected visa device')
return True | module function_definition identifier parameters identifier block if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement false expression_statement assignment identifier string string_start string_content string_end if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier attribute identifier identifier try_statement block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier except_clause block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier return_statement false try_statement block expression_statement assignment identifier subscript call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier dictionary if_statement call identifier argument_list identifier string string_start string_content string_end block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute attribute attribute identifier identifier identifier identifier dictionary_splat identifier except_clause block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute attribute attribute identifier identifier identifier identifier return_statement false expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement true | establish a connection to the Instrument |
def init_with_context(self, context):
site_name = get_admin_site_name(context)
self.children += [
items.MenuItem(_('Dashboard'), reverse('{0}:index'.format(site_name))),
items.Bookmarks(),
]
for title, kwargs in get_application_groups():
if kwargs.get('enabled', True):
self.children.append(CmsModelList(title, **kwargs))
self.children += [
ReturnToSiteItem()
] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement augmented_assignment attribute identifier identifier list call attribute identifier identifier argument_list call identifier argument_list string string_start string_content string_end call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier call attribute identifier identifier argument_list for_statement pattern_list identifier identifier call identifier argument_list block if_statement call attribute identifier identifier argument_list string string_start string_content string_end true block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier dictionary_splat identifier expression_statement augmented_assignment attribute identifier identifier list call identifier argument_list | Initialize the menu items. |
def write_transforms_to_file(self, fname='ace_transforms.txt'):
self._write_columns(fname, self.x_transforms, self.y_transform) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier attribute identifier identifier | Write y and x transforms used in this run to a space-delimited txt file. |
def get(cls, id):
if CACHE:
if id in _cache['Pool']:
log.debug('cache hit for pool %d' % id)
return _cache['Pool'][id]
log.debug('cache miss for pool %d' % id)
try:
pool = Pool.list({'id': id})[0]
except (IndexError, KeyError):
raise NipapNonExistentError('no pool with ID ' + str(id) + ' found')
_cache['Pool'][id] = pool
return pool | module function_definition identifier parameters identifier identifier block if_statement identifier block if_statement comparison_operator identifier subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier return_statement subscript subscript identifier string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier try_statement block expression_statement assignment identifier subscript call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end identifier integer except_clause tuple identifier identifier block raise_statement call identifier argument_list binary_operator binary_operator string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end expression_statement assignment subscript subscript identifier string string_start string_content string_end identifier identifier return_statement identifier | Get the pool with id 'id'. |
def _module_dir(handle):
cache_dir = resolver.tfhub_cache_dir(use_temp=True)
return resolver.create_local_module_dir(
cache_dir,
hashlib.sha1(handle.encode("utf8")).hexdigest()) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier true return_statement call attribute identifier identifier argument_list identifier call attribute call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list | Returns the directory where to cache the module. |
def h5fmem(**kwargs):
fn = tempfile.mktemp()
kwargs['mode'] = 'w'
kwargs['driver'] = 'core'
kwargs['backing_store'] = False
h5f = h5py.File(fn, **kwargs)
return h5f | module function_definition identifier parameters dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list 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 string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end false expression_statement assignment identifier call attribute identifier identifier argument_list identifier dictionary_splat identifier return_statement identifier | Create an in-memory HDF5 file. |
def end_task(self):
self.progress(self.task_stack[-1].size)
self.task_stack.pop() | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list attribute subscript attribute identifier identifier unary_operator integer identifier expression_statement call attribute attribute identifier identifier identifier argument_list | Remove the current task from the stack. |
def modular_exp( base, exponent, modulus ):
"Raise base to exponent, reducing by modulus"
if exponent < 0:
raise NegativeExponentError( "Negative exponents (%d) not allowed" \
% exponent )
return pow( base, exponent, modulus ) | module function_definition identifier parameters identifier identifier identifier block expression_statement string string_start string_content string_end if_statement comparison_operator identifier integer block raise_statement call identifier argument_list binary_operator string string_start string_content string_end line_continuation identifier return_statement call identifier argument_list identifier identifier identifier | Raise base to exponent, reducing by modulus |
def raw_message_to(self, token, message):
if token not in self._clients:
log.critical("Client with token '{0}' not found!".format(token))
return
client = self._clients[token]
try:
client.write_message(message)
except (AttributeError, tornado.websocket.WebSocketClosedError):
log.error("Lost connection to client '{0}'".format(client))
else:
print("Sent {0} bytes.".format(len(message))) | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement expression_statement assignment identifier subscript attribute identifier identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list identifier except_clause tuple identifier attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier else_clause block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier | Convert message to JSON and send it to the client with token |
def _select_limit_statement(table, cols='*', offset=0, limit=MAX_ROWS_PER_QUERY):
return 'SELECT {0} FROM {1} LIMIT {2}, {3}'.format(join_cols(cols), wrap(table), offset, limit) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier integer default_parameter identifier identifier block return_statement call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier call identifier argument_list identifier identifier identifier | Concatenate a select with offset and limit statement. |
def on_epoch_end(self, pbar, epoch, last_metrics, **kwargs):
"Put the various losses in the recorder and show a sample image."
if not hasattr(self, 'last_gen') or not self.show_img: return
data = self.learn.data
img = self.last_gen[0]
norm = getattr(data,'norm',False)
if norm and norm.keywords.get('do_y',False): img = data.denorm(img)
img = data.train_ds.y.reconstruct(img)
self.imgs.append(img)
self.titles.append(f'Epoch {epoch}')
pbar.show_imgs(self.imgs, self.titles)
return add_metrics(last_metrics, [getattr(self.smoothenerG,'smooth',None),getattr(self.smoothenerC,'smooth',None)]) | module function_definition identifier parameters identifier identifier identifier identifier dictionary_splat_pattern identifier block expression_statement string string_start string_content string_end if_statement boolean_operator not_operator call identifier argument_list identifier string string_start string_content string_end not_operator attribute identifier identifier block return_statement expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier subscript attribute identifier identifier integer expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end false if_statement boolean_operator identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end false block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content interpolation identifier string_end expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier return_statement call identifier argument_list identifier list call identifier argument_list attribute identifier identifier string string_start string_content string_end none call identifier argument_list attribute identifier identifier string string_start string_content string_end none | Put the various losses in the recorder and show a sample image. |
def _filehandle(self):
if self._fh and self._has_file_rolled():
try:
self._fh.close()
except Exception:
pass
self._fh = None
if not self._fh:
self._open_file(self.filename)
if not self.opened_before:
self.opened_before = True
self._fh.seek(0, os.SEEK_END)
return self._fh | module function_definition identifier parameters identifier block if_statement boolean_operator attribute identifier identifier call attribute identifier identifier argument_list block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list except_clause identifier block pass_statement expression_statement assignment attribute identifier identifier none if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier true expression_statement call attribute attribute identifier identifier identifier argument_list integer attribute identifier identifier return_statement attribute identifier identifier | Return a filehandle to the file being tailed |
def _log_deprecation(self, deprecation_key):
if not self._deprecations[deprecation_key][0]:
self.log.warning(self._deprecations[deprecation_key][1])
self._deprecations[deprecation_key][0] = True | module function_definition identifier parameters identifier identifier block if_statement not_operator subscript subscript attribute identifier identifier identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list subscript subscript attribute identifier identifier identifier integer expression_statement assignment subscript subscript attribute identifier identifier identifier integer true | Logs a deprecation notice at most once per AgentCheck instance, for the pre-defined `deprecation_key` |
def _get_ordering_field_lookup(self, field_name):
field = field_name
get_field = getattr(self, "get_%s_ordering_field" % field_name, None)
if get_field:
field = get_field()
return field | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier identifier expression_statement assignment identifier call identifier argument_list identifier binary_operator string string_start string_content string_end identifier none if_statement identifier block expression_statement assignment identifier call identifier argument_list return_statement identifier | get real model field to order by |
def visit_BoolOp(self, node):
return sum((self.visit(value) for value in node.values), []) | module function_definition identifier parameters identifier identifier block return_statement call identifier argument_list generator_expression call attribute identifier identifier argument_list identifier for_in_clause identifier attribute identifier identifier list | Return type may come from any boolop operand. |
def copy(self):
other = Version(None)
other.tokens = self.tokens[:]
other.seps = self.seps[:]
return other | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list none expression_statement assignment attribute identifier identifier subscript attribute identifier identifier slice expression_statement assignment attribute identifier identifier subscript attribute identifier identifier slice return_statement identifier | Returns a copy of the version. |
def item_properties(self, handle):
logger.debug("Getting properties for handle: {}".format(handle))
properties = {
'size_in_bytes': self.get_size_in_bytes(handle),
'utc_timestamp': self.get_utc_timestamp(handle),
'hash': self.get_hash(handle),
'relpath': self.get_relpath(handle)
}
logger.debug("{} properties: {}".format(handle, properties))
return properties | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list identifier pair string string_start string_content string_end call attribute identifier identifier argument_list identifier pair string string_start string_content string_end call attribute identifier identifier argument_list identifier pair string string_start string_content string_end call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier return_statement identifier | Return properties of the item with the given handle. |
def permute_data(arrays, random_state=None):
if any(len(a) != len(arrays[0]) for a in arrays):
raise ValueError('All arrays must be the same length.')
if not random_state:
random_state = np.random
order = random_state.permutation(len(arrays[0]))
return [a[order] for a in arrays] | module function_definition identifier parameters identifier default_parameter identifier none block if_statement call identifier generator_expression comparison_operator call identifier argument_list identifier call identifier argument_list subscript identifier integer for_in_clause identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement not_operator identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list subscript identifier integer return_statement list_comprehension subscript identifier identifier for_in_clause identifier identifier | Permute multiple numpy arrays with the same order. |
def declassify(to_remove, *args, **kwargs):
def argdecorate(fn):
@wraps(fn)
def declassed(*args, **kwargs):
ret = fn(*args, **kwargs)
try:
if type(ret) is list:
return [r[to_remove] for r in ret]
return ret[to_remove]
except KeyError:
return ret
return declassed
return argdecorate | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list list_splat identifier dictionary_splat identifier try_statement block if_statement comparison_operator call identifier argument_list identifier identifier block return_statement list_comprehension subscript identifier identifier for_in_clause identifier identifier return_statement subscript identifier identifier except_clause identifier block return_statement identifier return_statement identifier return_statement identifier | flatten the return values of the mite api. |
def map_ontologies():
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
stmts_json = body.get('statements')
stmts = stmts_from_json(stmts_json)
om = OntologyMapper(stmts, wm_ontomap, scored=True, symmetric=False)
om.map_statements()
return _return_stmts(stmts) | module function_definition identifier parameters block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement dictionary expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier keyword_argument identifier true keyword_argument identifier false expression_statement call attribute identifier identifier argument_list return_statement call identifier argument_list identifier | Run ontology mapping on a list of INDRA Statements. |
def setup_logging(self):
logging.getLogger('amqp').setLevel(str_to_logging(self.get('logging', 'amqp')))
logging.getLogger('rdflib').setLevel(str_to_logging(self.get('logging', 'rdflib'))) | module function_definition identifier parameters identifier block expression_statement call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end | Setup logging module based on known modules in the config file |
def name(self):
if not hasattr(self, '_name'):
self._name = re.search('[a-z]+\.([a-z]+)\.([a-z]+)', str(self.__class__), re.IGNORECASE).group(2)
return self._name | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list attribute identifier identifier attribute identifier identifier identifier argument_list integer return_statement attribute identifier identifier | Returns the recipe name which is its class name without package. |
def copy(self):
return Poly(self.A.copy(), self.dim, self.shape,
self.dtype) | module function_definition identifier parameters identifier block return_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier | Return a copy of the polynomial. |
def _loaddata_template(self, stringbuffer, index, name, opts):
context = self._get_dump_item_context(index, name, opts)
stringbuffer.write(self.loadder_item_template.format(**context))
return stringbuffer | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list dictionary_splat identifier return_statement identifier | StringIO "templates" to build a command line for 'loaddata' |
def _make_regex(self):
rxp = "|".join(
map(self._address_rxp, self.keys()),
)
self._regex = re.compile(
rxp,
re.IGNORECASE,
) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier attribute identifier identifier | Compile rxp with all keys concatenated. |
def order_by(self, order_attribute):
to_return = []
for f in sorted(self.items, key=lambda i: getattr(i, order_attribute)):
to_return.append(f)
return to_return | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier call identifier argument_list attribute identifier identifier keyword_argument identifier lambda lambda_parameters identifier call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Return the list of items in a certain order |
def load_network_from_file( filename ):
import cPickle
network = NeuralNet( {"n_inputs":1, "layers":[[0,None]]} )
with open( filename , 'rb') as file:
store_dict = cPickle.load(file)
network.n_inputs = store_dict["n_inputs"]
network.n_weights = store_dict["n_weights"]
network.layers = store_dict["layers"]
network.weights = store_dict["weights"]
return network | module function_definition identifier parameters identifier block import_statement dotted_name identifier expression_statement assignment identifier call identifier argument_list dictionary pair string string_start string_content string_end integer pair string string_start string_content string_end list list integer none with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end return_statement identifier | Load the complete configuration of a previously stored network. |
def image_update_properties(request, image_id, remove_props=None, **kwargs):
return glanceclient(request, '2').images.update(image_id,
remove_props,
**kwargs) | module function_definition identifier parameters identifier identifier default_parameter identifier none dictionary_splat_pattern identifier block return_statement call attribute attribute call identifier argument_list identifier string string_start string_content string_end identifier identifier argument_list identifier identifier dictionary_splat identifier | Add or update a custom property of an image. |
def wider_pre_conv(layer, n_add_filters, weighted=True):
n_dim = get_n_dim(layer)
if not weighted:
return get_conv_class(n_dim)(
layer.input_channel,
layer.filters + n_add_filters,
kernel_size=layer.kernel_size,
)
n_pre_filters = layer.filters
rand = np.random.randint(n_pre_filters, size=n_add_filters)
teacher_w, teacher_b = layer.get_weights()
student_w = teacher_w.copy()
student_b = teacher_b.copy()
for i in range(len(rand)):
teacher_index = rand[i]
new_weight = teacher_w[teacher_index, ...]
new_weight = new_weight[np.newaxis, ...]
student_w = np.concatenate((student_w, new_weight), axis=0)
student_b = np.append(student_b, teacher_b[teacher_index])
new_pre_layer = get_conv_class(n_dim)(
layer.input_channel, n_pre_filters + n_add_filters, layer.kernel_size
)
new_pre_layer.set_weights(
(add_noise(student_w, teacher_w), add_noise(student_b, teacher_b))
)
return new_pre_layer | module function_definition identifier parameters identifier identifier default_parameter identifier true block expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator identifier block return_statement call call identifier argument_list identifier argument_list attribute identifier identifier binary_operator attribute identifier identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier call identifier argument_list call identifier argument_list identifier block expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier subscript identifier identifier ellipsis expression_statement assignment identifier subscript identifier attribute identifier identifier ellipsis expression_statement assignment identifier call attribute identifier identifier argument_list tuple identifier identifier keyword_argument identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier subscript identifier identifier expression_statement assignment identifier call call identifier argument_list identifier argument_list attribute identifier identifier binary_operator identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list tuple call identifier argument_list identifier identifier call identifier argument_list identifier identifier return_statement identifier | wider previous conv layer. |
def symlinks(self):
if not self._P.Block.Symlinks:
return []
return [decode_ay(path) for path in self._P.Block.Symlinks] | module function_definition identifier parameters identifier block if_statement not_operator attribute attribute attribute identifier identifier identifier identifier block return_statement list return_statement list_comprehension call identifier argument_list identifier for_in_clause identifier attribute attribute attribute identifier identifier identifier identifier | Known symlinks of the block device. |
def RenderHttpResponse(request):
start_time = time.time()
response = HTTP_REQUEST_HANDLER.HandleRequest(request)
total_time = time.time() - start_time
method_name = response.headers.get("X-API-Method", "unknown")
if response.status_code == 200:
status = "SUCCESS"
elif response.status_code == 403:
status = "FORBIDDEN"
elif response.status_code == 404:
status = "NOT_FOUND"
elif response.status_code == 501:
status = "NOT_IMPLEMENTED"
else:
status = "SERVER_ERROR"
if request.method == "HEAD":
metric_name = "api_access_probe_latency"
else:
metric_name = "api_method_latency"
stats_collector_instance.Get().RecordEvent(
metric_name, total_time, fields=(method_name, "http", status))
return response | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier string string_start string_content string_end elif_clause comparison_operator attribute identifier identifier integer block expression_statement assignment identifier string string_start string_content string_end elif_clause comparison_operator attribute identifier identifier integer block expression_statement assignment identifier string string_start string_content string_end elif_clause comparison_operator attribute identifier identifier integer block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier string string_start string_content string_end if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier string string_start string_content string_end expression_statement call attribute call attribute identifier identifier argument_list identifier argument_list identifier identifier keyword_argument identifier tuple identifier string string_start string_content string_end identifier return_statement identifier | Renders HTTP response to a given HTTP request. |
def deleteAnnotations(self,
annotation_ids,
LIMIT=25,
_print=True,
crawl=False,):
url_base = self.base_url + \
'/api/1/term/edit-annotation/{annotation_id}'
annotations = self.getAnnotations_via_id(annotation_ids,
LIMIT=LIMIT,
_print=_print,
crawl=crawl)
annotations_to_delete = []
for annotation_id in annotation_ids:
annotation = annotations[int(annotation_id)]
params = {
'value': ' ',
'annotation_tid': ' ',
'tid': ' ',
'term_version': '1',
'annotation_term_version': '1',
}
url = url_base.format(annotation_id=annotation_id)
annotation.update({**params})
annotations_to_delete.append((url, annotation))
return self.post(annotations_to_delete,
LIMIT=LIMIT,
_print=_print,
crawl=crawl) | module function_definition identifier parameters identifier identifier default_parameter identifier integer default_parameter identifier true default_parameter identifier false block expression_statement assignment identifier binary_operator attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier subscript identifier call identifier argument_list identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list dictionary dictionary_splat identifier expression_statement call attribute identifier identifier argument_list tuple identifier identifier return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | data = list of ids |
def readRGBA(self):
self.reset_bits_pending();
r = self.readUI8()
g = self.readUI8()
b = self.readUI8()
a = self.readUI8()
return (a << 24) | (r << 16) | (g << 8) | b | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list return_statement binary_operator binary_operator binary_operator parenthesized_expression binary_operator identifier integer parenthesized_expression binary_operator identifier integer parenthesized_expression binary_operator identifier integer identifier | Read a RGBA color |
def parse_xml_file(self, fileobj, id_generator=None):
root = etree.parse(fileobj).getroot()
usage_id = self._usage_id_from_node(root, None, id_generator)
return usage_id | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier none identifier return_statement identifier | Parse an open XML file, returning a usage id. |
def eat_line(self):
if self.eos:
return None
eat_length = self.eat_length
get_char = self.get_char
has_space = self.has_space
while has_space() and get_char() != '\n':
eat_length(1)
eat_length(1) | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement none expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier while_statement boolean_operator call identifier argument_list comparison_operator call identifier argument_list string string_start string_content escape_sequence string_end block expression_statement call identifier argument_list integer expression_statement call identifier argument_list integer | Move current position forward until the next line. |
def check_param_ranges(num_bins, num_groups, num_values, trim_outliers, trim_percentile):
if num_bins < minimum_num_bins:
raise ValueError('Too few bins! The number of bins must be >= 5')
if num_values < num_groups:
raise ValueError('Insufficient number of values in features (< number of nodes), or invalid membership!')
if trim_outliers:
if trim_percentile < 0 or trim_percentile >= 100:
raise ValueError('percentile of tail values to trim must be in the semi-open interval [0,1).')
elif num_values < 2:
raise ValueError('too few features to compute minimum and maximum')
return | module function_definition identifier parameters identifier identifier identifier identifier identifier block if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement identifier block if_statement boolean_operator comparison_operator identifier integer comparison_operator identifier integer block raise_statement call identifier argument_list string string_start string_content string_end elif_clause comparison_operator identifier integer block raise_statement call identifier argument_list string string_start string_content string_end return_statement | Ensuring the parameters are in valid ranges. |
def Flush(self):
super(LabelSet, self).Flush()
self.to_delete = self.to_delete.difference(self.to_set)
with data_store.DB.GetMutationPool() as mutation_pool:
mutation_pool.LabelUpdateLabels(
self.urn, self.to_set, to_delete=self.to_delete)
self.to_set = set()
self.to_delete = set() | module function_definition identifier parameters identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier with_statement with_clause with_item as_pattern call attribute attribute identifier identifier identifier argument_list as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list | Flush the data to the index. |
def render_pyquery(self, **kwargs):
from pyquery import PyQuery as pq
return pq(self.render(**kwargs), parser='html') | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block import_from_statement dotted_name identifier aliased_import dotted_name identifier identifier return_statement call identifier argument_list call attribute identifier identifier argument_list dictionary_splat identifier keyword_argument identifier string string_start string_content string_end | Render the graph, and return a pyquery wrapped tree |
def transformer_wikitext103_l4k_v0():
hparams = transformer_big()
hparams.optimizer = "Adafactor"
hparams.learning_rate_schedule = "rsqrt_decay"
hparams.learning_rate_warmup_steps = 10000
hparams.num_heads = 4
hparams.max_length = 4096
hparams.batch_size = 4096
hparams.shared_embedding_and_softmax_weights = False
hparams.num_hidden_layers = 8
hparams.attention_dropout = 0.1
hparams.layer_prepostprocess_dropout = 0.2
hparams.relu_dropout = 0.1
hparams.label_smoothing = 0.0
hparams.attention_dropout_broadcast_dims = "0,1"
hparams.relu_dropout_broadcast_dims = "1"
hparams.layer_prepostprocess_dropout_broadcast_dims = "1"
hparams.symbol_modality_num_shards = 1
return hparams | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier float expression_statement assignment attribute identifier identifier float expression_statement assignment attribute identifier identifier float expression_statement assignment attribute identifier identifier float expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier integer return_statement identifier | HParams for training languagemodel_wikitext103_l4k. |
def use_isolated_log_view(self):
self._log_view = ISOLATED
for session in self._get_provider_sessions():
try:
session.use_isolated_log_view()
except AttributeError:
pass | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier identifier for_statement identifier call attribute identifier identifier argument_list block try_statement block expression_statement call attribute identifier identifier argument_list except_clause identifier block pass_statement | Pass through to provider LogEntryLookupSession.use_isolated_log_view |
def watch(args):
" Watch directory for changes and auto pack sources "
assert op.isdir(args.source), "Watch mode allowed only for directories."
print 'Zeta-library v. %s watch mode' % VERSION
print '================================'
print 'Ctrl+C for exit\n'
observer = Observer()
handler = ZetaTrick(args=args)
observer.schedule(handler, args.source, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
print "\nWatch mode stoped."
observer.join() | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end assert_statement call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end print_statement binary_operator string string_start string_content string_end identifier print_statement string string_start string_content string_end print_statement string string_start string_content escape_sequence string_end expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier keyword_argument identifier true expression_statement call attribute identifier identifier argument_list try_statement block while_statement true block expression_statement call attribute identifier identifier argument_list integer except_clause identifier block expression_statement call attribute identifier identifier argument_list print_statement string string_start string_content escape_sequence string_end expression_statement call attribute identifier identifier argument_list | Watch directory for changes and auto pack sources |
def defaults():
return dict((str(k), str(v)) for k, v in cma_default_options.items()) | module function_definition identifier parameters block return_statement call identifier generator_expression tuple call identifier argument_list identifier call identifier argument_list identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list | return a dictionary with default option values and description |
def use_comparative_assessment_taken_view(self):
self._object_views['assessment_taken'] = COMPARATIVE
for session in self._get_provider_sessions():
try:
session.use_comparative_assessment_taken_view()
except AttributeError:
pass | module function_definition identifier parameters identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end identifier for_statement identifier call attribute identifier identifier argument_list block try_statement block expression_statement call attribute identifier identifier argument_list except_clause identifier block pass_statement | Pass through to provider AssessmentTakenLookupSession.use_comparative_assessment_taken_view |
def _login_request(self, username=None, secret=None):
url = 'http://' + self._host + '/login_sid.lua'
params = {}
if username:
params['username'] = username
if secret:
params['response'] = secret
plain = self._request(url, params)
dom = xml.dom.minidom.parseString(plain)
sid = get_text(dom.getElementsByTagName('SID')[0].childNodes)
challenge = get_text(
dom.getElementsByTagName('Challenge')[0].childNodes)
return (sid, challenge) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier binary_operator binary_operator string string_start string_content string_end attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier dictionary if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list attribute subscript call attribute identifier identifier argument_list string string_start string_content string_end integer identifier expression_statement assignment identifier call identifier argument_list attribute subscript call attribute identifier identifier argument_list string string_start string_content string_end integer identifier return_statement tuple identifier identifier | Send a login request with paramerters. |
def next_theme(self):
theme = self.term.theme_list.next(self.term.theme)
while not self.term.check_theme(theme):
theme = self.term.theme_list.next(theme)
self.term.set_theme(theme)
self.draw()
message = self.term.theme.display_string
self.term.show_notification(message, timeout=1) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list attribute attribute identifier identifier identifier while_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier integer | Cycle to preview the next theme from the internal list of themes. |
def check_imagemagick_supported_format(fmt):
try:
convert_output = check_output(['convert', '--version'])
except (CalledProcessError, OSError) as err:
logger.error(
"Cannot run ImageMgick's `convert` program."
" On Debian/Ubuntu, use `sudo apt-get install imagemagick`"
" to install it.")
return False
supported = []
for line in convert_output.split('\n'):
line = line.lower()
if line.startswith('delegates'):
supported += line.split(':', 1)[1].split()
fmt = fmt.lower()
if not fmt.startswith('.'):
fmt = '.' + fmt
try:
delegate = SUPPORTED_IMAGE_FORMATS[fmt]
except KeyError:
logger.error("Image format `%s` not supported by `tm_client`.")
return False
if delegate in supported:
return True
else:
logger.error("Image format `%s` not in ImageMagick's `convert` delegates.")
return False | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call identifier argument_list list string string_start string_content string_end string string_start string_content string_end except_clause as_pattern tuple identifier identifier as_pattern_target identifier 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 string string_start string_content string_end return_statement false expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement augmented_assignment identifier call attribute subscript call attribute identifier identifier argument_list string string_start string_content string_end integer integer identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier try_statement block expression_statement assignment identifier subscript identifier identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement false if_statement comparison_operator identifier identifier block return_statement true else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement false | Return ``True`` if `convert` can be run and reports supporting image format `fmt`. |
def document_type2marc(self, key, value):
if value in DOCUMENT_TYPE_REVERSE_MAP and DOCUMENT_TYPE_REVERSE_MAP[value]:
return {'a': DOCUMENT_TYPE_REVERSE_MAP[value]} | module function_definition identifier parameters identifier identifier identifier block if_statement boolean_operator comparison_operator identifier identifier subscript identifier identifier block return_statement dictionary pair string string_start string_content string_end subscript identifier identifier | Populate the ``980`` MARC field. |
def get(self, request, id):
if id:
return self._get_one(id)
else:
return self._get_all() | module function_definition identifier parameters identifier identifier identifier block if_statement identifier block return_statement call attribute identifier identifier argument_list identifier else_clause block return_statement call attribute identifier identifier argument_list | Get one user or all users |
def _GetZeepFormattedSOAPHeaders(self):
headers = self._header_handler.GetSOAPHeaders(self.CreateSoapElementForType)
soap_headers = {'RequestHeader': headers}
return soap_headers | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier return_statement identifier | Returns a dict with SOAP headers in the right format for zeep. |
def extract_ipv4(roster_order, ipv4):
for ip_type in roster_order:
for ip_ in ipv4:
if ':' in ip_:
continue
if not salt.utils.validate.net.ipv4_addr(ip_):
continue
if ip_type == 'local' and ip_.startswith('127.'):
return ip_
elif ip_type == 'private' and not salt.utils.cloud.is_public_ip(ip_):
return ip_
elif ip_type == 'public' and salt.utils.cloud.is_public_ip(ip_):
return ip_
return None | module function_definition identifier parameters identifier identifier block for_statement identifier identifier block for_statement identifier identifier block if_statement comparison_operator string string_start string_content string_end identifier block continue_statement if_statement not_operator call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list identifier block continue_statement if_statement boolean_operator comparison_operator identifier string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end block return_statement identifier elif_clause boolean_operator comparison_operator identifier string string_start string_content string_end not_operator call attribute attribute attribute identifier identifier identifier identifier argument_list identifier block return_statement identifier elif_clause boolean_operator comparison_operator identifier string string_start string_content string_end call attribute attribute attribute identifier identifier identifier identifier argument_list identifier block return_statement identifier return_statement none | Extract the preferred IP address from the ipv4 grain |
def delete(self):
response = self.pingdom.request('DELETE',
'reports.shared/%s' % self.id)
return response.json()['message'] | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end binary_operator string string_start string_content string_end attribute identifier identifier return_statement subscript call attribute identifier identifier argument_list string string_start string_content string_end | Delete this email report |
def cleanJsbConfig(self, jsbconfig):
config = json.loads(jsbconfig)
self._cleanJsbAllClassesSection(config)
self._cleanJsbAppAllSection(config)
return json.dumps(config, indent=4) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier integer | Clean up the JSB config. |
def CreateApproval(self,
reason=None,
notified_users=None,
email_cc_addresses=None):
if not reason:
raise ValueError("reason can't be empty")
if not notified_users:
raise ValueError("notified_users list can't be empty.")
approval = user_pb2.ApiHuntApproval(
reason=reason,
notified_users=notified_users,
email_cc_addresses=email_cc_addresses or [])
args = user_pb2.ApiCreateHuntApprovalArgs(
hunt_id=self.hunt_id, approval=approval)
data = self._context.SendRequest("CreateHuntApproval", args)
return HuntApproval(
data=data, username=self._context.username, context=self._context) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier boolean_operator identifier list expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute attribute identifier identifier identifier keyword_argument identifier attribute identifier identifier | Create a new approval for the current user to access this hunt. |
def graph_val_dump(self):
self._flush_graph_val()
for (graph, key, branch, turn, tick, value) in self.sql('graph_val_dump'):
yield (
self.unpack(graph),
self.unpack(key),
branch,
turn,
tick,
self.unpack(value)
) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list for_statement tuple_pattern identifier identifier identifier identifier identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement yield tuple call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier identifier identifier identifier call attribute identifier identifier argument_list identifier | Yield the entire contents of the graph_val table. |
def remove(name=None, index=None):
removed = False
count = 1
for configuration in _CONFIG.sections():
if index != None:
if count == index:
_CONFIG.remove_section(configuration)
removed = True
break
if name != None:
if configuration == name:
_CONFIG.remove_section(configuration)
removed = True
break
count += 1
if not removed:
raise JutException('Unable to find %s configuration' % name)
with open(_CONFIG_FILEPATH, 'w') as configfile:
_CONFIG.write(configfile) | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier false expression_statement assignment identifier integer for_statement identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier none block if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier true break_statement if_statement comparison_operator identifier none block if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier true break_statement expression_statement augmented_assignment identifier integer if_statement not_operator identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier | remove the specified configuration |
def concat_dim(cls, datasets, dim, vdims):
import iris
from iris.experimental.equalise_cubes import equalise_attributes
cubes = []
for c, cube in datasets.items():
cube = cube.copy()
cube.add_aux_coord(iris.coords.DimCoord([c], var_name=dim.name))
cubes.append(cube)
cubes = iris.cube.CubeList(cubes)
equalise_attributes(cubes)
return cubes.merge_cube() | module function_definition identifier parameters identifier identifier identifier identifier block import_statement dotted_name identifier import_from_statement dotted_name identifier identifier identifier dotted_name identifier expression_statement assignment identifier list for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list list identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement call identifier argument_list identifier return_statement call attribute identifier identifier argument_list | Concatenates datasets along one dimension |
def _translate_limit(self, len_, start, num):
if start > len_ or num <= 0:
return 0, 0
return min(start, len_), num | module function_definition identifier parameters identifier identifier identifier identifier block if_statement boolean_operator comparison_operator identifier identifier comparison_operator identifier integer block return_statement expression_list integer integer return_statement expression_list call identifier argument_list identifier identifier identifier | Translate limit to valid bounds. |
def _list_files(self, path):
files = []
for f in glob.glob(pathname=path):
files.append(f)
files.sort()
return files | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list keyword_argument identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list return_statement identifier | lists files in a given directory |
def filtered(self, step_names):
return Graph(steps=self.steps, dag=self.dag.filter(step_names)) | module function_definition identifier parameters identifier identifier block return_statement call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier call attribute attribute identifier identifier identifier argument_list identifier | Returns a "filtered" version of this graph. |
def to_refs(value):
from mongoframes.frames import Frame, SubFrame
if isinstance(value, Frame):
return value._id
elif isinstance(value, SubFrame):
return to_refs(value._document)
elif isinstance(value, (list, tuple)):
return [to_refs(v) for v in value]
elif isinstance(value, dict):
return {k: to_refs(v) for k, v in value.items()}
return value | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier dotted_name identifier dotted_name identifier if_statement call identifier argument_list identifier identifier block return_statement attribute identifier identifier elif_clause call identifier argument_list identifier identifier block return_statement call identifier argument_list attribute identifier identifier elif_clause call identifier argument_list identifier tuple identifier identifier block return_statement list_comprehension call identifier argument_list identifier for_in_clause identifier identifier elif_clause call identifier argument_list identifier identifier block return_statement dictionary_comprehension pair identifier call identifier argument_list identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list return_statement identifier | Convert all Frame instances within the given value to Ids |
def _is_wrapped(self, token, tokens):
for t in tokens:
is_wrapped = self._wraps((token, t))
if is_wrapped:
return True
return False | module function_definition identifier parameters identifier identifier identifier block for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list tuple identifier identifier if_statement identifier block return_statement true return_statement false | check if param token is wrapped by any token in tokens |
def y_select_cb(self, w, index):
try:
self.y_col = self.cols[index]
except IndexError as e:
self.logger.error(str(e))
else:
self.plot_two_columns(reset_ylimits=True) | module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement assignment attribute identifier identifier subscript attribute identifier identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list keyword_argument identifier true | Callback to set Y-axis column. |
def on_history_size_value_changed(self, spin):
val = int(spin.get_value())
self.settings.general.set_int('history-size', val)
self._update_history_widgets() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list | Changes the value of history_size in dconf |
def decode_values(fct):
def inner(*args, **kwargs):
data = fct(*args, **kwargs)
if 'error' not in data:
for result in data:
result['Value'] = base64.b64decode(result['Value'])
return data
return inner | module function_definition identifier parameters identifier block function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list list_splat identifier dictionary_splat identifier if_statement comparison_operator string string_start string_content string_end identifier block for_statement identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end return_statement identifier return_statement identifier | Decode base64 encoded responses from Consul storage |
def watch_logfile(self, logfile_path):
self._run_stats['logSource'] = logfile_path
log_parser = LogParser()
output_time = time.time() + WATCH_DISPLAY_REFRESH_SECONDS
try:
firstLine = True
for line in self._tail_file(open(logfile_path),
WATCH_INTERVAL_SECONDS):
if firstLine:
self._run_stats['timeRange']['start'] = get_line_time(line)
self._process_query(line, log_parser)
self._run_stats['timeRange']['end'] = get_line_time(line)
if time.time() >= output_time:
self._output_aggregated_report(sys.stderr)
output_time = time.time() + WATCH_DISPLAY_REFRESH_SECONDS
except KeyboardInterrupt:
sys.stderr.write("Interrupt received\n")
finally:
self._output_aggregated_report(sys.stdout)
return 0 | module function_definition identifier parameters identifier identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list identifier try_statement block expression_statement assignment identifier true for_statement identifier call attribute identifier identifier argument_list call identifier argument_list identifier identifier block if_statement identifier block expression_statement assignment subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement assignment subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end call identifier argument_list identifier if_statement comparison_operator call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list identifier except_clause identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content escape_sequence string_end finally_clause block expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement integer | Analyzes queries from the tail of a given log file |
def id_to_root_name(id):
name = root_names.get(id)
if not name:
name = repr(id)
return name | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator identifier block expression_statement assignment identifier call identifier argument_list identifier return_statement identifier | Convert a PDG ID to a string with root markup. |
def avail(df):
avail = DataFrame(
{
"start": df.apply(lambda col: col.first_valid_index()),
"end": df.apply(lambda col: col.last_valid_index()),
}
)
return avail[["start", "end"]] | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list lambda lambda_parameters identifier call attribute identifier identifier argument_list pair string string_start string_content string_end call attribute identifier identifier argument_list lambda lambda_parameters identifier call attribute identifier identifier argument_list return_statement subscript identifier list string string_start string_content string_end string string_start string_content string_end | Return start & end availability for each column in a DataFrame. |
def check(self, request):
if callable(self.check_func):
self.visible = self.check_func(request) | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list attribute identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier | Evaluate if we should be visible for this request |
def _get_phantom_root_catalog(self, cat_name, cat_class):
catalog_map = make_catalog_map(cat_name, identifier=PHANTOM_ROOT_IDENTIFIER)
return cat_class(osid_object_map=catalog_map, runtime=self._runtime, proxy=self._proxy) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier | Get's the catalog id corresponding to the root of all implementation catalogs. |
def expect(qubits, meas):
"For the VQE simulation without sampling."
result = {}
i = np.arange(len(qubits))
meas = tuple(meas)
def to_mask(n):
return reduce(lambda acc, im: acc | (n & (1 << im[0])) << (im[1] - im[0]), enumerate(meas), 0)
def to_key(k):
return tuple(1 if k & (1 << i) else 0 for i in meas)
mask = reduce(lambda acc, v: acc | (1 << v), meas, 0)
cnt = defaultdict(float)
for i, v in enumerate(qubits):
p = v.real ** 2 + v.imag ** 2
if p != 0.0:
cnt[i & mask] += p
return {to_key(k): v for k, v in cnt.items()} | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier dictionary expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier function_definition identifier parameters identifier block return_statement call identifier argument_list lambda lambda_parameters identifier identifier binary_operator identifier binary_operator parenthesized_expression binary_operator identifier parenthesized_expression binary_operator integer subscript identifier integer parenthesized_expression binary_operator subscript identifier integer subscript identifier integer call identifier argument_list identifier integer function_definition identifier parameters identifier block return_statement call identifier generator_expression conditional_expression integer binary_operator identifier parenthesized_expression binary_operator integer identifier integer for_in_clause identifier identifier expression_statement assignment identifier call identifier argument_list lambda lambda_parameters identifier identifier binary_operator identifier parenthesized_expression binary_operator integer identifier identifier integer expression_statement assignment identifier call identifier argument_list identifier for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement assignment identifier binary_operator binary_operator attribute identifier identifier integer binary_operator attribute identifier identifier integer if_statement comparison_operator identifier float block expression_statement augmented_assignment subscript identifier binary_operator identifier identifier identifier return_statement dictionary_comprehension pair call identifier argument_list identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list | For the VQE simulation without sampling. |
def getTypedValue(self, row):
'Returns the properly-typed value for the given row at this column.'
return wrapply(self.type, wrapply(self.getValue, row)) | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end return_statement call identifier argument_list attribute identifier identifier call identifier argument_list attribute identifier identifier identifier | Returns the properly-typed value for the given row at this column. |
def on_epoch_end(self, last_metrics, **kwargs):
"Put the various losses in the recorder."
return add_metrics(last_metrics, [s.smooth for k,s in self.smootheners.items()]) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement string string_start string_content string_end return_statement call identifier argument_list identifier list_comprehension attribute identifier identifier for_in_clause pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list | Put the various losses in the recorder. |
def accepts_numpy(func):
def wrp_accepts_numpy(self, input_, *args, **kwargs):
if not (util_type.HAVE_NUMPY and isinstance(input_, np.ndarray)):
return func(self, input_, *args, **kwargs)
else:
if UNIQUE_NUMPY:
input_list, inverse_unique = np.unique(input_, return_inverse=True)
else:
input_list = input_.flatten()
input_list = input_list.tolist()
output_list = func(self, input_list, *args, **kwargs)
if UNIQUE_NUMPY:
output_arr = np.array(output_list)[inverse_unique]
output_shape = tuple(list(input_.shape) + list(output_arr.shape[1:]))
return np.array(output_arr).reshape(output_shape)
else:
return np.array(output_list).reshape(input_.shape)
wrp_accepts_numpy = preserve_sig(wrp_accepts_numpy, func)
return wrp_accepts_numpy | module function_definition identifier parameters identifier block function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement not_operator parenthesized_expression boolean_operator attribute identifier identifier call identifier argument_list identifier attribute identifier identifier block return_statement call identifier argument_list identifier identifier list_splat identifier dictionary_splat identifier else_clause block if_statement identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier identifier list_splat identifier dictionary_splat identifier if_statement identifier block expression_statement assignment identifier subscript call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list binary_operator call identifier argument_list attribute identifier identifier call identifier argument_list subscript attribute identifier identifier slice integer return_statement call attribute call attribute identifier identifier argument_list identifier identifier argument_list identifier else_clause block return_statement call attribute call attribute identifier identifier argument_list identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier return_statement identifier | Allows the first input to be a numpy array and get result in numpy form |
def do_operation(database, keys, table, operation, latencies_ms):
key = random.choice(keys)
start = timeit.default_timer()
if operation == 'read':
read(database, table, key)
elif operation == 'update':
update(database, table, key)
else:
raise ValueError('Unknown operation: %s' % operation)
end = timeit.default_timer()
latencies_ms[operation].append((end - start) * 1000) | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call identifier argument_list identifier identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement call identifier argument_list identifier identifier identifier else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute subscript identifier identifier identifier argument_list binary_operator parenthesized_expression binary_operator identifier identifier integer | Does a single operation and records latency. |
def _mine_send(self, tag, data):
channel = salt.transport.client.ReqChannel.factory(self.opts)
data['tok'] = self.tok
try:
ret = channel.send(data)
return ret
except SaltReqTimeoutError:
log.warning('Unable to send mine data to master.')
return None
finally:
channel.close() | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement none finally_clause block expression_statement call attribute identifier identifier argument_list | Send mine data to the master |
def query_relative(self, query, event_time=None, relative_duration_before=None, relative_duration_after=None):
assert event_time is None or isinstance(event_time, datetime.datetime)
assert relative_duration_before is None or isinstance(relative_duration_before, str)
assert relative_duration_after is None or isinstance(relative_duration_after, str)
if event_time is None:
event_time = datetime.datetime.now()
if relative_duration_before is None:
relative_duration_before = self.relative_duration_before
if relative_duration_after is None:
relative_duration_after = self.relative_duration_after
time_start = event_time - create_timedelta(relative_duration_before)
time_end = event_time + create_timedelta(relative_duration_after)
return self.query_with_time(query, time_start, time_end) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block assert_statement boolean_operator comparison_operator identifier none call identifier argument_list identifier attribute identifier identifier assert_statement boolean_operator comparison_operator identifier none call identifier argument_list identifier identifier assert_statement boolean_operator comparison_operator identifier none call identifier argument_list identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier binary_operator identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator identifier call identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier identifier identifier | Perform the query and calculate the time range based on the relative values. |
def sparql(self, stringa):
qres = self.rdfgraph.query(stringa)
return list(qres) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement call identifier argument_list identifier | wrapper around a sparql query |
def compress_js(self, paths, templates=None, **kwargs):
js = self.concatenate(paths)
if templates:
js = js + self.compile_templates(templates)
if not settings.DISABLE_WRAPPER:
js = settings.JS_WRAPPER % js
compressor = self.js_compressor
if compressor:
js = getattr(compressor(verbose=self.verbose), 'compress_js')(js)
return js | module function_definition identifier parameters identifier identifier default_parameter identifier none dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement assignment identifier binary_operator identifier call attribute identifier identifier argument_list identifier if_statement not_operator attribute identifier identifier block expression_statement assignment identifier binary_operator attribute identifier identifier identifier expression_statement assignment identifier attribute identifier identifier if_statement identifier block expression_statement assignment identifier call call identifier argument_list call identifier argument_list keyword_argument identifier attribute identifier identifier string string_start string_content string_end argument_list identifier return_statement identifier | Concatenate and compress JS files |
def adj_nodes_gcp(gcp_nodes):
for node in gcp_nodes:
node.cloud = "gcp"
node.cloud_disp = "GCP"
node.private_ips = ip_to_str(node.private_ips)
node.public_ips = ip_to_str(node.public_ips)
node.zone = node.extra['zone'].name
return gcp_nodes | module function_definition identifier parameters identifier block for_statement identifier identifier block expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier attribute subscript attribute identifier identifier string string_start string_content string_end identifier return_statement identifier | Adjust details specific to GCP. |
def _format_method_nodes(self, task_method, modulename, classname):
methodname = task_method.__name__
fullname = '.'.join((modulename, classname, methodname))
signature = Signature(task_method, bound_method=True)
desc_sig_node = self._format_signature(
signature, modulename, classname, fullname, 'py:meth')
content_node = desc_content()
content_node += self._create_doc_summary(task_method, fullname,
'py:meth')
desc_node = desc()
desc_node['noindex'] = True
desc_node['domain'] = 'py'
desc_node['objtype'] = 'method'
desc_node += desc_sig_node
desc_node += content_node
return desc_node | module function_definition identifier parameters identifier identifier 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 tuple identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier true expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list expression_statement augmented_assignment identifier call attribute identifier identifier argument_list identifier identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end true 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 string string_start string_content string_end expression_statement augmented_assignment identifier identifier expression_statement augmented_assignment identifier identifier return_statement identifier | Create a ``desc`` node summarizing a method docstring. |
def export(datastore_key, calc_id=-1, exports='csv', export_dir='.'):
dstore = util.read(calc_id)
parent_id = dstore['oqparam'].hazard_calculation_id
if parent_id:
dstore.parent = util.read(parent_id)
dstore.export_dir = export_dir
with performance.Monitor('export', measuremem=True) as mon:
for fmt in exports.split(','):
fnames = export_((datastore_key, fmt), dstore)
nbytes = sum(os.path.getsize(f) for f in fnames)
print('Exported %s in %s' % (general.humansize(nbytes), fnames))
if mon.duration > 1:
print(mon)
dstore.close() | module function_definition identifier parameters identifier default_parameter identifier unary_operator integer default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier attribute subscript identifier string string_start string_content string_end identifier if_statement identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier true as_pattern_target identifier block for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list tuple identifier identifier identifier expression_statement assignment identifier call identifier generator_expression call attribute attribute identifier identifier identifier argument_list identifier for_in_clause identifier identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | Export an output from the datastore. |
def add_update_callback(self, callback, sensor):
self._updateCallbacks.append([callback, sensor])
_LOGGING.debug('Added update callback to %s on %s', callback, sensor) | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list list identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier | Register as callback for when a matching device sensor changes. |
def cli(ctx):
cmd = click.prompt('Command')
desc = click.prompt('Description ')
alias = click.prompt('Alias (optional)', default='')
utils.save_command(cmd, desc, alias)
utils.log(ctx, 'Saved the new command - {} - with the description - {}.'.format(cmd, desc)) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_end expression_statement call attribute identifier identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier | Saves a new command |
def _parse(partial_dt):
dt = None
try:
if isinstance(partial_dt, datetime):
dt = partial_dt
if isinstance(partial_dt, date):
dt = _combine_date_time(partial_dt, time(0, 0, 0))
if isinstance(partial_dt, time):
dt = _combine_date_time(date.today(), partial_dt)
if isinstance(partial_dt, (int, float)):
dt = datetime.fromtimestamp(partial_dt)
if isinstance(partial_dt, (str, bytes)):
dt = parser.parse(partial_dt, default=timezone.now())
if dt is not None and timezone.is_naive(dt):
dt = timezone.make_aware(dt)
return dt
except ValueError:
return None | module function_definition identifier parameters identifier block expression_statement assignment identifier none try_statement block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier call identifier argument_list integer integer integer if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier if_statement call identifier argument_list identifier tuple identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call identifier argument_list identifier tuple identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier call attribute identifier identifier argument_list if_statement boolean_operator comparison_operator identifier none call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier except_clause identifier block return_statement none | parse a partial datetime object to a complete datetime object |
def request_get_user(self, user_ids) -> dict:
method_params = {'user_ids': user_ids}
response = self.session.send_method_request('users.get', method_params)
self.check_for_errors('users.get', method_params, response)
return response | module function_definition identifier parameters identifier identifier type identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier return_statement identifier | Method to get users by ID, do not need authorization |
def ask_captcha(length=4):
captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length))
ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False) | module function_definition identifier parameters default_parameter identifier integer block expression_statement assignment identifier call attribute string string_start string_end identifier generator_expression call attribute identifier identifier argument_list attribute identifier identifier for_in_clause identifier call identifier argument_list identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression identifier keyword_argument identifier list identifier call attribute identifier identifier argument_list keyword_argument identifier false | Prompts the user for a random string. |
def size_from_name(size, sizes):
by_name = [s for s in sizes if s.name == size]
if len(by_name) > 1:
raise Exception('more than one image named %s exists' % size)
return by_name[0] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause comparison_operator attribute identifier identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier return_statement subscript identifier integer | Return a size from a list of sizes. |
def add_shell_action(sub_parser: ArgumentParser) -> ArgumentParser:
sub_parser.add_argument(
'-p', '--project',
dest='project_directory',
type=str,
default=None
)
sub_parser.add_argument(
'-l', '--log',
dest='logging_path',
type=str,
default=None
)
sub_parser.add_argument(
'-o', '--output',
dest='output_directory',
type=str,
default=None
)
sub_parser.add_argument(
'-s', '--shared',
dest='shared_data_path',
type=str,
default=None
)
return sub_parser | module function_definition identifier parameters typed_parameter identifier type identifier type identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier none expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier none expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier none expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier none return_statement identifier | Populates the sub parser with the shell arguments |
def visit_FunctionBody(self, node):
for child in node.children:
return_value = self.visit(child)
if isinstance(child, ReturnStatement):
return return_value
if isinstance(child, (IfStatement, WhileStatement)):
if return_value is not None:
return return_value
return NoneType() | module function_definition identifier parameters identifier identifier block for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call identifier argument_list identifier identifier block return_statement identifier if_statement call identifier argument_list identifier tuple identifier identifier block if_statement comparison_operator identifier none block return_statement identifier return_statement call identifier argument_list | Visitor for `FunctionBody` AST node. |
def normalize(value):
if value and isinstance(value, bytes):
value = value.decode('utf-8')
return value | module function_definition identifier parameters identifier block if_statement boolean_operator identifier call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier | Simple method to always have the same kind of value |
def idfn(fixture_params: Iterable[Any]) -> str:
return ":".join((str(item) for item in fixture_params)) | module function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier block return_statement call attribute string string_start string_content string_end identifier argument_list generator_expression call identifier argument_list identifier for_in_clause identifier identifier | Function for pytest to produce uniform names for fixtures. |
def to_immutable(self):
if self._enumeration is None:
self._get_mutable_enumeration()
col_obj = self._enumeration['immutable'][self._collection_type]
return col_obj(self.header, self.values) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier subscript subscript attribute identifier identifier string string_start string_content string_end attribute identifier identifier return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier | Get an immutable version of this collection. |
def _process_json_response(self, response):
json_response = self._get_json_response(response)
if self.response_callback is not None:
json_response = self.response_callback(json_response)
response._content = json.dumps(json_response)
self.http_status_code = response.status_code
self._check_error(response, json_response)
self._check_warnings(json_response)
return json_response | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Process a given response |
def frompil(self, pillow_image):
bio = BytesIO()
pillow_image.save(bio, format='png', compress_level=1)
py_buffer = bio.getbuffer()
c_buffer = ffi.from_buffer(py_buffer)
with _LeptonicaErrorTrap():
pix = Pix(lept.pixReadMem(c_buffer, len(c_buffer)))
return pix | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier with_statement with_clause with_item call identifier argument_list block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier call identifier argument_list identifier return_statement identifier | Create a copy of a PIL.Image from this Pix |
def _query_iterator(self, result, chunksize, columns, coerce_float=True,
parse_dates=None):
while True:
data = result.fetchmany(chunksize)
if not data:
break
else:
self.frame = DataFrame.from_records(
data, columns=columns, coerce_float=coerce_float)
self._harmonize_columns(parse_dates=parse_dates)
if self.index is not None:
self.frame.set_index(self.index, inplace=True)
yield self.frame | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier true default_parameter identifier none block while_statement true block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator identifier block break_statement else_clause block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier true expression_statement yield attribute identifier identifier | Return generator through chunked result set. |
def do_help(self, arg):
if not arg or arg not in self.argparse_names():
cmd.Cmd.do_help(self, arg)
else:
try:
self.argparser.parse_args([arg, '--help'])
except Exception:
pass | module function_definition identifier parameters identifier identifier block if_statement boolean_operator not_operator identifier comparison_operator identifier call attribute identifier identifier argument_list block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier else_clause block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list list identifier string string_start string_content string_end except_clause identifier block pass_statement | Patched to show help for arparse commands |
def tasks(self, **kwargs):
tasks_result = self.service.tasks().list(**kwargs).execute()
return [Task(task) for task in tasks_result.get("items", [])] | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list dictionary_splat identifier identifier argument_list return_statement list_comprehension call identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list string string_start string_content string_end list | Fetch tasks specified criteria |
def process_details():
results = {"argv": sys.argv, "working.directory": os.getcwd()}
for key, method in {
"pid": "getpid",
"ppid": "getppid",
"login": "getlogin",
"uid": "getuid",
"euid": "geteuid",
"gid": "getgid",
"egid": "getegid",
"groups": "getgroups",
}.items():
try:
results[key] = getattr(os, method)()
except (AttributeError, OSError):
results[key] = None
return results | module function_definition identifier parameters block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end call attribute identifier identifier argument_list for_statement pattern_list identifier identifier call attribute dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end identifier argument_list block try_statement block expression_statement assignment subscript identifier identifier call call identifier argument_list identifier identifier argument_list except_clause tuple identifier identifier block expression_statement assignment subscript identifier identifier none return_statement identifier | Returns details about the current process |
def _run(name,
cmd,
output=None,
no_start=False,
stdin=None,
python_shell=True,
preserve_state=False,
output_loglevel='debug',
ignore_retcode=False,
use_vt=False,
keep_env=None):
orig_state = state(name)
exc = None
try:
ret = __salt__['container_resource.run'](
name,
cmd,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
except Exception:
raise
finally:
if preserve_state \
and orig_state == 'stopped' \
and state(name) != 'stopped':
stop(name)
if output in (None, 'all'):
return ret
else:
return ret[output] | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier false default_parameter identifier none default_parameter identifier true default_parameter identifier false default_parameter identifier string string_start string_content string_end default_parameter identifier false default_parameter identifier false default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier none try_statement block expression_statement assignment identifier call subscript identifier string string_start string_content string_end argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier except_clause identifier block raise_statement finally_clause block if_statement boolean_operator boolean_operator identifier line_continuation comparison_operator identifier string string_start string_content string_end line_continuation comparison_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement call identifier argument_list identifier if_statement comparison_operator identifier tuple none string string_start string_content string_end block return_statement identifier else_clause block return_statement subscript identifier identifier | Common logic for nspawn.run functions |
def _flush(self):
if self.file.closed:
return
cache = b"".join(self.cache)
if not cache:
return
uncompressed_data = cache[:self.MAX_CACHE_SIZE]
tail = cache[self.MAX_CACHE_SIZE:]
self.cache = [tail]
self.cache_size = len(tail)
compressed_data = zlib.compress(uncompressed_data,
self.COMPRESSION_LEVEL)
obj_size = (OBJ_HEADER_V1_STRUCT.size + LOG_CONTAINER_STRUCT.size +
len(compressed_data))
base_header = OBJ_HEADER_BASE_STRUCT.pack(
b"LOBJ", OBJ_HEADER_BASE_STRUCT.size, 1, obj_size, LOG_CONTAINER)
container_header = LOG_CONTAINER_STRUCT.pack(
ZLIB_DEFLATE, len(uncompressed_data))
self.file.write(base_header)
self.file.write(container_header)
self.file.write(compressed_data)
self.file.write(b"\x00" * (obj_size % 4))
self.uncompressed_size += OBJ_HEADER_V1_STRUCT.size + LOG_CONTAINER_STRUCT.size
self.uncompressed_size += len(uncompressed_data) | module function_definition identifier parameters identifier block if_statement attribute attribute identifier identifier identifier block return_statement expression_statement assignment identifier call attribute string string_start string_end identifier argument_list attribute identifier identifier if_statement not_operator identifier block return_statement expression_statement assignment identifier subscript identifier slice attribute identifier identifier expression_statement assignment identifier subscript identifier slice attribute identifier identifier expression_statement assignment attribute identifier identifier list identifier expression_statement assignment attribute identifier identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier parenthesized_expression binary_operator binary_operator attribute identifier identifier attribute identifier identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier integer identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end parenthesized_expression binary_operator identifier integer expression_statement augmented_assignment attribute identifier identifier binary_operator attribute identifier identifier attribute identifier identifier expression_statement augmented_assignment attribute identifier identifier call identifier argument_list identifier | Compresses and writes data in the cache to file. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.