code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def itermonthdays(cls, year, month):
for day in NepCal.itermonthdates(year, month):
if day.month == month:
yield day.day
else:
yield 0 | module function_definition identifier parameters identifier identifier identifier block for_statement identifier call attribute identifier identifier argument_list identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block expression_statement yield attribute identifier identifier else_clause block expression_statement yield integer | Similar to itermonthdates but returns day number instead of NepDate object |
def reduce(self):
support = frozenset(range(1, self.nvars+1))
new_clauses = set()
for clause in self.clauses:
vs = list(support - {abs(uniqid) for uniqid in clause})
if vs:
for num in range(1 << len(vs)):
new_part = {v if bit_on(num, i) else ~v
for i, v in enumerate(vs)}
new_clauses.add(clause | new_part)
else:
new_clauses.add(clause)
return self.__class__(self.nvars, new_clauses) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list integer binary_operator attribute identifier identifier integer expression_statement assignment identifier call identifier argument_list for_statement identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list binary_operator identifier set_comprehension call identifier argument_list identifier for_in_clause identifier identifier if_statement identifier block for_statement identifier call identifier argument_list binary_operator integer call identifier argument_list identifier block expression_statement assignment identifier set_comprehension conditional_expression identifier call identifier argument_list identifier identifier unary_operator identifier for_in_clause pattern_list identifier identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list binary_operator identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list attribute identifier identifier identifier | Reduce to a canonical form. |
def signals(self, signals=('QUIT', 'USR1', 'USR2')):
for sig in signals:
signal.signal(getattr(signal, 'SIG' + sig), self.handler) | module function_definition identifier parameters identifier default_parameter identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier binary_operator string string_start string_content string_end identifier attribute identifier identifier | Register our signal handler |
def ensure_iam(self, publisher=None):
topic = self.get_topic_param()
client = self.session.client('pubsub', 'v1', 'projects.topics')
policy = client.execute_command('getIamPolicy', {'resource': topic})
policy.pop('etag')
found = False
for binding in policy.get('bindings', {}):
if binding['role'] != 'roles/pubsub.publisher':
continue
if publisher in binding['members']:
return
found = binding
if not found:
policy.setdefault(
'bindings', {'members': [publisher], 'role': 'roles/pubsub.publisher'})
else:
found['members'].append(publisher)
client.execute_command('setIamPolicy', {'resource': topic, 'body': {'policy': policy}}) | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list 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 string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary pair string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier false for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary block if_statement comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block continue_statement if_statement comparison_operator identifier subscript identifier string string_start string_content string_end block return_statement expression_statement assignment identifier identifier if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end dictionary pair string string_start string_content string_end list identifier pair string string_start string_content string_end string string_start string_content string_end else_clause block expression_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end dictionary pair string string_start string_content string_end identifier | Ensure the given identities are in the iam role bindings for the topic. |
def update_active(self):
if self.active is not None:
self.update_state(self.active, "normal")
if self.current_iid == self.active:
self._active = None
return
self._active = self.current_iid
if self.active is not None:
self.update_state(self.active, "active") | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier none return_statement expression_statement assignment attribute identifier identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end | Update the active marker on the marker Canvas |
def _symbolic_product_helper():
from sympy import symbols, Matrix
D11, D12, D13, D21, D22, D23, D31, D32, D33 =\
symbols('D11, D12, D13, D21, D22, D23, D31, D32, D33')
D = Matrix([[D11, D12, D13], [D21, D22, D23], [D31, D32, D33]])
grad = Matrix([['dx', 'dy', 'dz']]).T
div = grad.T
a = div * D * grad
print(a[0]) | module function_definition identifier parameters block import_from_statement dotted_name identifier dotted_name identifier dotted_name identifier expression_statement assignment pattern_list identifier identifier identifier identifier identifier identifier identifier identifier identifier line_continuation call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list list list identifier identifier identifier list identifier identifier identifier list identifier identifier identifier expression_statement assignment identifier attribute call identifier argument_list list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier binary_operator binary_operator identifier identifier identifier expression_statement call identifier argument_list subscript identifier integer | Use SymPy to generate the 3D products for diffusion_stencil_3d. |
def SetValue(self, row, col, value, refresh=True):
value = "".join(value.split("\n"))
key = row, col, self.grid.current_table
old_code = self.grid.code_array(key)
if old_code is None:
old_code = ""
if value != old_code:
self.grid.actions.set_code(key, value) | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier true block expression_statement assignment identifier call attribute string string_start string_end identifier argument_list call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end expression_statement assignment identifier expression_list identifier identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier string string_start string_end if_statement comparison_operator identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier identifier | Set the value of a cell, merge line breaks |
def memoize(f):
@wraps(f)
def w(*args, **kw):
memoize.mem[f] = v = f(*args, **kw)
return v
return w | module function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment subscript attribute identifier identifier identifier assignment identifier call identifier argument_list list_splat identifier dictionary_splat identifier return_statement identifier return_statement identifier | Cache value returned by the function. |
def make_end_to_end_distance_plot(nb_segments, end_to_end_distance, neurite_type):
plt.figure()
plt.plot(nb_segments, end_to_end_distance)
plt.title(neurite_type)
plt.xlabel('Number of segments')
plt.ylabel('End-to-end distance')
plt.show() | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list | Plot end-to-end distance vs number of segments |
def print_col_perc_table(table, row_labels, col_labels):
r1c1, r1c2, r2c1, r2c2 = map(float, table)
col1 = r1c1 + r2c1
col2 = r1c2 + r2c2
blocks = [
(r1c1, col1),
(r1c2, col2),
(r2c1, col1),
(r2c2, col2)]
new_table = []
for cell, row in blocks:
try:
x = cell / row
except ZeroDivisionError:
x = 0
new_table.append(x)
s = print_2x2_table(new_table, row_labels, col_labels, fmt="%.2f")
s = s.splitlines(False)
last_space = s[0].rindex(" ")
new_s = [i[:last_space] for i in s]
return '\n'.join(new_s) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier identifier call identifier argument_list identifier identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier list tuple identifier identifier tuple identifier identifier tuple identifier identifier tuple identifier identifier expression_statement assignment identifier list for_statement pattern_list identifier identifier identifier block try_statement block expression_statement assignment identifier binary_operator identifier identifier except_clause identifier block expression_statement assignment identifier integer expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list false expression_statement assignment identifier call attribute subscript identifier integer identifier argument_list string string_start string_content string_end expression_statement assignment identifier list_comprehension subscript identifier slice identifier for_in_clause identifier identifier return_statement call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier | given a table, print the cols as percentages |
def handle_finish(queue_name):
task_id = request.form.get('task_id', type=str)
owner = request.form.get('owner', request.remote_addr, type=str)
error = request.form.get('error', type=str) is not None
try:
work_queue.finish(queue_name, task_id, owner, error=error)
except work_queue.Error, e:
return utils.jsonify_error(e)
db.session.commit()
logging.debug('Task finished: queue=%r, task_id=%r, owner=%r, error=%r',
queue_name, task_id, owner, error)
return flask.jsonify(success=True) | 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 keyword_argument identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end attribute identifier identifier keyword_argument identifier identifier expression_statement assignment identifier comparison_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier none try_statement block expression_statement call attribute identifier identifier argument_list identifier identifier identifier keyword_argument identifier identifier except_clause attribute identifier identifier identifier block return_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier identifier identifier return_statement call attribute identifier identifier argument_list keyword_argument identifier true | Marks a task on a queue as finished. |
def pub(self, topic, message):
with self.random_connection() as client:
client.pub(topic, message)
return self.wait_response() | module function_definition identifier parameters identifier identifier identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier identifier return_statement call attribute identifier identifier argument_list | Publish the provided message to the provided topic |
def serve(opts):
resources = _load(opts.resources, opts.output_dir)
opts.output_dir = resources.output_dir
if not os.path.exists(opts.output_dir):
sys.stderr.write("Resources dir '{}' not found. Did you fetch?\n".format(opts.output_dir))
return 1
backend.PyPIResource.build_pypi_indexes(opts.output_dir)
os.chdir(opts.output_dir)
HTTPServer.allow_reuse_address = True
httpd = HTTPServer((opts.host, opts.port), SimpleHTTPRequestHandler)
if opts.ssl_cert:
httpd.socket = ssl.wrap_socket(httpd.socket, certfile=opts.ssl_cert, server_side=True)
print("Serving at: http{}://{}:{}/".format(
's' if opts.ssl_cert else '', socket.gethostname(), opts.port))
httpd.serve_forever() | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list attribute identifier identifier return_statement integer expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier true expression_statement assignment identifier call identifier argument_list tuple attribute identifier identifier attribute identifier identifier identifier if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier true expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list conditional_expression string string_start string_content string_end attribute identifier identifier string string_start string_end call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list | Run a light-weight HTTP server hosting previously mirrored resources |
def _check_y(y):
if not isinstance(y, np.ndarray):
raise TypeError("y must be numpy array. Typically y contains "
"the entire test set labels. Got " + str(y) + " of type " + str(type(y))) | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier attribute identifier identifier block raise_statement call identifier argument_list binary_operator binary_operator binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end call identifier argument_list call identifier argument_list identifier | Makes sure a `y` argument is a vliad numpy dataset. |
def cross_entropy_error(self, input_data, targets, average=True,
cache=None, prediction=False):
if cache is not None:
activations = cache
else:
activations = \
self.feed_forward(input_data, prediction=prediction)
loss = cross_entropy_logistic(activations, targets)
if average: loss /= targets.shape[0]
return loss.get() | module function_definition identifier parameters identifier identifier identifier default_parameter identifier true default_parameter identifier none default_parameter identifier false block if_statement comparison_operator identifier none block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier line_continuation call attribute identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier if_statement identifier block expression_statement augmented_assignment identifier subscript attribute identifier identifier integer return_statement call attribute identifier identifier argument_list | Return the cross entropy error |
def new_bundle(self, name: str, created_at: dt.datetime=None) -> models.Bundle:
new_bundle = self.Bundle(name=name, created_at=created_at)
return new_bundle | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_default_parameter identifier type attribute identifier identifier none type attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier return_statement identifier | Create a new file bundle. |
def OnContextMenu(self, event):
self.grid.PopupMenu(self.grid.contextmenu)
event.Skip() | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list | Context menu event handler |
def format_installed_dap_list(simple=False):
lines = []
if simple:
for pkg in sorted(get_installed_daps()):
lines.append(pkg)
else:
for pkg, instances in sorted(get_installed_daps_detailed().items()):
versions = []
for instance in instances:
location = utils.unexpanduser(instance['location'])
version = instance['version']
if not versions:
version = utils.bold(version)
versions.append('{v}:{p}'.format(v=version, p=location))
pkg = utils.bold(pkg)
lines.append('{pkg} ({versions})'.format(pkg=pkg, versions=' '.join(versions)))
return lines | module function_definition identifier parameters default_parameter identifier false block expression_statement assignment identifier list if_statement identifier block for_statement identifier call identifier argument_list call identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier else_clause block for_statement pattern_list identifier identifier call identifier argument_list call attribute call identifier argument_list identifier argument_list block expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement not_operator identifier block expression_statement assignment identifier 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 keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier 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 keyword_argument identifier identifier keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list identifier return_statement identifier | Formats all installed DAPs in a human readable form to list of lines |
def ensure_annotations(resources, data):
transcript_gff = tz.get_in(["rnaseq", "transcripts"], resources)
if transcript_gff and utils.file_exists(transcript_gff):
out_dir = os.path.join(tz.get_in(["dirs", "work"], data),
"inputs", "data", "annotations")
resources["rnaseq"]["gene_bed"] = gtf.gtf_to_bed(transcript_gff, out_dir)
return resources | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end identifier if_statement boolean_operator identifier call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment subscript subscript identifier string string_start string_content string_end string string_start string_content string_end call attribute identifier identifier argument_list identifier identifier return_statement identifier | Prepare any potentially missing annotations for downstream processing in a local directory. |
def pw_compare_class_sets(self, cset1: Set[ClassId], cset2: Set[ClassId]) -> Tuple[ICValue, ICValue, ICValue]:
pairs = self.mica_ic_df.loc[cset1, cset2]
max0 = pairs.max(axis=0)
max1 = pairs.max(axis=1)
idxmax0 = pairs.idxmax(axis=0)
idxmax1 = pairs.idxmax(axis=1)
mean0 = max0.mean()
mean1 = max1.mean()
return (mean0+mean1)/2, mean0, mean1 | module function_definition identifier parameters identifier typed_parameter identifier type generic_type identifier type_parameter type identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type generic_type identifier type_parameter type identifier type identifier type identifier block expression_statement assignment identifier subscript attribute attribute identifier identifier identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list return_statement expression_list binary_operator parenthesized_expression binary_operator identifier identifier integer identifier identifier | Compare two class profiles |
def _attach_obj(self, req, obj):
json.dump(obj, req)
req['content-type'] = self._content_type | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier | Helper method to attach obj to req as JSON data. |
def process_view(self, request, view_func, view_args, view_kwargs):
view_keys = list(VIEW_METHOD_DATA.keys())
for key in view_keys:
del VIEW_METHOD_DATA[key]
self.view_data = {}
try:
cbv = view_func.view_class
except AttributeError:
cbv = False
if cbv:
self.view_data['cbv'] = True
klass = view_func.view_class
self.view_data['bases'] = [base.__name__ for base in inspect.getmro(klass)]
for member in inspect.getmembers(view_func.view_class):
if member[0] in VIEW_METHOD_WHITEIST and member[0] not in PATCHED_METHODS[klass]:
decorate_method(klass, member[0])
PATCHED_METHODS[klass].append(member[0]) | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list for_statement identifier identifier block delete_statement subscript identifier identifier expression_statement assignment attribute identifier identifier dictionary try_statement block expression_statement assignment identifier attribute identifier identifier except_clause identifier block expression_statement assignment identifier false if_statement identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end true expression_statement assignment identifier attribute identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end list_comprehension attribute identifier identifier for_in_clause identifier call attribute identifier identifier argument_list identifier for_statement identifier call attribute identifier identifier argument_list attribute identifier identifier block if_statement boolean_operator comparison_operator subscript identifier integer identifier comparison_operator subscript identifier integer subscript identifier identifier block expression_statement call identifier argument_list identifier subscript identifier integer expression_statement call attribute subscript identifier identifier identifier argument_list subscript identifier integer | Collect data on Class-Based Views |
def humanTimeConverter():
if len(sys.argv) == 2:
print humanFriendlyTime(seconds=int(sys.argv[1]))
else:
for line in sys.stdin:
print humanFriendlyTime(int(line))
sys.exit(0) | module function_definition identifier parameters block if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block print_statement call identifier argument_list keyword_argument identifier call identifier argument_list subscript attribute identifier identifier integer else_clause block for_statement identifier attribute identifier identifier block print_statement call identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list integer | Cope whether we're passed a time in seconds on the command line or via stdin |
def _add_get_tracking_url(cls):
def get_tracking_url(self):
url = reverse('admin:tracking_fields_trackingevent_changelist')
object_id = '{0}%3A{1}'.format(
ContentType.objects.get_for_model(self).pk,
self.pk
)
return '{0}?object={1}'.format(url, object_id)
if not hasattr(cls, 'get_tracking_url'):
setattr(cls, 'get_tracking_url', get_tracking_url) | module function_definition identifier parameters identifier block function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute call attribute attribute identifier identifier identifier argument_list identifier identifier attribute identifier identifier return_statement call attribute string string_start string_content string_end identifier argument_list identifier identifier if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement call identifier argument_list identifier string string_start string_content string_end identifier | Add a method to get the tracking url of an object. |
def _update_color_rgb(self, event=None):
if event is None or event.widget.old_value != event.widget.get():
r = self.red.get()
g = self.green.get()
b = self.blue.get()
h, s, v = rgb_to_hsv(r, g, b)
self.hue.set(h)
self.saturation.set(s)
self.value.set(v)
args = (r, g, b)
if self.alpha_channel:
args += (self.alpha.get(),)
self.alphabar.set_color(args)
hexa = rgb_to_hexa(*args)
self.hexa.delete(0, "end")
self.hexa.insert(0, hexa)
self.square.set_hsv((h, s, v))
self.bar.set(h)
self._update_preview() | module function_definition identifier parameters identifier default_parameter identifier none block if_statement boolean_operator comparison_operator identifier none comparison_operator attribute attribute identifier identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list identifier identifier 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 assignment identifier tuple identifier identifier identifier if_statement attribute identifier identifier block expression_statement augmented_assignment identifier tuple call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list list_splat identifier expression_statement call attribute attribute identifier identifier identifier argument_list integer string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list integer identifier expression_statement call attribute attribute identifier identifier identifier argument_list tuple identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | Update display after a change in the RGB spinboxes. |
def isHereDoc(self, block, column):
dataObject = block.userData()
data = dataObject.data if dataObject is not None else None
return self._syntax.isHereDoc(data, column) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier conditional_expression attribute identifier identifier comparison_operator identifier none none return_statement call attribute attribute identifier identifier identifier argument_list identifier identifier | Check if character at column is a here document |
def _query_uncompressed(options, collection_name, num_to_skip,
num_to_return, query, field_selector, opts, check_keys=False):
op_query, max_bson_size = _query(
options,
collection_name,
num_to_skip,
num_to_return,
query,
field_selector,
opts,
check_keys)
rid, msg = __pack_message(2004, op_query)
return rid, msg, max_bson_size | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier default_parameter identifier false block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier identifier identifier identifier identifier identifier identifier identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list integer identifier return_statement expression_list identifier identifier identifier | Internal query message helper. |
def authenticate(self, username, password):
if username is None or password is None:
return False
if not re.match("^[A-Za-z0-9_-]*$", username):
return False
user_dn = self.get_user_dn(username)
server = ldap3.Server(
self.uri,
use_ssl=self.use_ssl
)
connection = ldap3.Connection(server, user=user_dn, password=password)
return connection.bind() | module function_definition identifier parameters identifier identifier identifier block if_statement boolean_operator comparison_operator identifier none comparison_operator identifier none block return_statement false if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end identifier block return_statement false expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list | Authenticate the user with a bind on the LDAP server |
def enable_mesos_basic_authentication(principal, password):
restart = False
secrets_file = '/etc/mesos/secrets'
secrets_entry = '%s %s' % (principal, password)
if not file_contains(filename=secrets_file,
text=secrets_entry, use_sudo=True):
file_append(filename=secrets_file, text=secrets_entry, use_sudo=True)
file_attribs(secrets_file, mode=700, sudo=True)
restart = True
with quiet():
if secrets_file not in sudo('cat /etc/mesos-master/credentials'):
sudo('echo %s > /etc/mesos-master/credentials' % secrets_file)
restart = True
if not exists('/etc/mesos-master/\?authenticate', use_sudo=True):
sudo('touch /etc/mesos-master/\?authenticate')
file_attribs('/etc/mesos-master/\?authenticate',
mode=700,
sudo=True)
restart = True
if restart:
restart_service('mesos-master') | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier false expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier if_statement not_operator call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier true block expression_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier true expression_statement call identifier argument_list identifier keyword_argument identifier integer keyword_argument identifier true expression_statement assignment identifier true with_statement with_clause with_item call identifier argument_list block if_statement comparison_operator identifier call identifier argument_list string string_start string_content string_end block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier true if_statement not_operator call identifier argument_list string string_start string_content string_end keyword_argument identifier true block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier integer keyword_argument identifier true expression_statement assignment identifier true if_statement identifier block expression_statement call identifier argument_list string string_start string_content string_end | enables and adds a new authorized principal |
def find_packages(name, pkg_dir):
for c in (FileSystemPackageBuilder, ZipPackageBuilder, ExcelPackageBuilder):
package_path, cache_path = c.make_package_path(pkg_dir, name)
if package_path.exists():
yield c.type_code, package_path, cache_path | module function_definition identifier parameters identifier identifier block for_statement identifier tuple identifier identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier identifier if_statement call attribute identifier identifier argument_list block expression_statement yield expression_list attribute identifier identifier identifier identifier | Locate pre-built packages in the _packages directory |
def import_usr_dir(usr_dir):
if not usr_dir:
return
if usr_dir == INTERNAL_USR_DIR_PACKAGE:
importlib.import_module(INTERNAL_USR_DIR_PACKAGE)
return
dir_path = os.path.abspath(os.path.expanduser(usr_dir).rstrip("/"))
containing_dir, module_name = os.path.split(dir_path)
tf.logging.info("Importing user module %s from path %s", module_name,
containing_dir)
sys.path.insert(0, containing_dir)
importlib.import_module(module_name)
sys.path.pop(0) | module function_definition identifier parameters identifier block if_statement not_operator identifier block return_statement if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute call attribute attribute identifier identifier identifier argument_list identifier identifier argument_list string string_start string_content string_end expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list integer identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list integer | Import module at usr_dir, if provided. |
def _to_desired_dates(self, arr):
times = utils.times.extract_months(
arr[internal_names.TIME_STR], self.months
)
return arr.sel(time=times) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list subscript identifier attribute identifier identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier | Restrict the xarray DataArray or Dataset to the desired months. |
async def remove_user(self, username):
client_facade = client.UserManagerFacade.from_connection(
self.connection())
user = tag.user(username)
await client_facade.RemoveUser([client.Entity(user)]) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement await call attribute identifier identifier argument_list list call attribute identifier identifier argument_list identifier | Remove a user from this controller. |
def _get_asset(self, asset_uid):
uri = self.uri + '/v2/assets/' + asset_uid
headers = self._get_headers()
return self.service._get(uri, headers=headers) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator binary_operator attribute identifier identifier string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier | Returns raw response for an given asset by its unique id. |
def pop_range(self, start, stop=None, withscores=True, **options):
return self.backend.execute(
self.client.zpopbyscore(self.id, start, stop,
withscores=withscores, **options),
partial(self._range, withscores)) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier true dictionary_splat_pattern identifier block return_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier identifier keyword_argument identifier identifier dictionary_splat identifier call identifier argument_list attribute identifier identifier identifier | Remove and return a range from the ordered set by score. |
def post_message(self, msg):
super(mavlogfile, self).post_message(msg)
if self.planner_format:
self.f.read(1)
self.timestamp = msg._timestamp
self._last_message = msg
if msg.get_type() != "BAD_DATA":
self._last_timestamp = msg._timestamp
msg._link = self._link | module function_definition identifier parameters identifier identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list integer expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier identifier if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier | add timestamp to message |
def use_plenary_grade_system_view(self):
self._object_views['grade_system'] = PLENARY
for session in self._get_provider_sessions():
try:
session.use_plenary_grade_system_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 GradeSystemLookupSession.use_plenary_grade_system_view |
def serve(self, host='127.0.0.1', port=5000):
from meinheld import server, middleware
server.listen((host, port))
server.run(middleware.WebSocketMiddleware(self.app)) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier integer block import_from_statement dotted_name identifier dotted_name identifier dotted_name identifier expression_statement call attribute identifier identifier argument_list tuple identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier | Serve predictions as an API endpoint. |
def paragraph(node):
text = ''
if node.string_content is not None:
text = node.string_content
o = nodes.paragraph('', ' '.join(text))
o.line = node.sourcepos[0][0]
for n in MarkDown(node):
o.append(n)
return o | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_end if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_end call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment attribute identifier identifier subscript subscript attribute identifier identifier integer integer for_statement identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Process a paragraph, which includes all content under it |
def usergroups_list(self, **kwargs) -> SlackResponse:
self._validate_xoxp_token()
return self.api_call("usergroups.list", http_verb="GET", params=kwargs) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier type identifier block expression_statement call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier | List all User Groups for a team |
def count(self):
cursor = self.conn.cursor()
with contextlib.closing(cursor):
cursor.execute('SELECT COUNT(*) FROM events')
res = cursor.fetchone()
return res[0] | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list with_statement with_clause with_item call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list return_statement subscript identifier integer | Return the number of events in the db. |
def copy_path_to_clipboard(self):
path = self.get_current_path()
QtWidgets.QApplication.clipboard().setText(path)
debug('path copied: %s' % path) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier | Copies the file path to the clipboard |
def increment(self, key: Any, by: int = 1) -> None:
if key is not None:
self[key] = self.get(key, 0) + by | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier integer type none block if_statement comparison_operator identifier none block expression_statement assignment subscript identifier identifier binary_operator call attribute identifier identifier argument_list identifier integer identifier | Increments the value set against a key. If the key is not present, 0 is assumed as the initial state |
def _get_project_types(self):
project_types = get_available_project_types()
projects = []
for project in project_types:
projects.append(project.PROJECT_TYPE_NAME)
return projects | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier | Get all available project types. |
def make_dir(cls, directory_name):
if not os.path.exists(directory_name):
os.makedirs(directory_name) | module function_definition identifier parameters identifier identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier | Create a directory in the system |
def validate(self, value):
if not isinstance(value, (list, tuple)) or isinstance(value, str_types):
self.raise_error('Only lists and tuples may be used in the ListField vs provided {0}'
.format(type(value).__name__))
super(ListField, self).validate(value) | module function_definition identifier parameters identifier identifier block if_statement boolean_operator not_operator call identifier argument_list identifier tuple identifier identifier call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute call identifier argument_list identifier identifier expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier | Make sure that the inspected value is of type `list` or `tuple` |
def tcp_receive(self):
data = self.conn.recv(self.BUFFER_SIZE)
if type(data) != str:
data = data.decode("utf-8")
return str(data) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier if_statement comparison_operator 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 call identifier argument_list identifier | Receive data from TCP port. |
def do_GET(self):
if not self._client_allowed():
return
try:
(_, _, path, query, _) = urlsplit(self.path)
params = parse_qs(query)
for prefix, handler in self._GET_handlers:
if self._maybe_handle(prefix, handler, path, params):
return
if path == '/':
self._handle_runs('', {})
return
content = 'Invalid GET request {}'.format(self.path).encode('utf-8'),
self._send_content(content, 'text/html', code=400)
except (IOError, ValueError):
pass | module function_definition identifier parameters identifier block if_statement not_operator call attribute identifier identifier argument_list block return_statement try_statement block expression_statement assignment tuple_pattern identifier identifier identifier identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier for_statement pattern_list identifier identifier attribute identifier identifier block if_statement call attribute identifier identifier argument_list identifier identifier identifier identifier block return_statement if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_end dictionary return_statement expression_statement assignment identifier expression_list call attribute call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end keyword_argument identifier integer except_clause tuple identifier identifier block pass_statement | GET method implementation for BaseHTTPRequestHandler. |
def _get_deadline(results, timeout=None):
start_time = time()
all_deadlines = set(result.get_deadline() for result in results)
all_deadlines.discard(None)
if timeout is not None:
all_deadlines.add(start_time + timeout)
return min(all_deadlines) if all_deadlines else None | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier generator_expression call attribute identifier identifier argument_list for_in_clause identifier identifier expression_statement call attribute identifier identifier argument_list none if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list binary_operator identifier identifier return_statement conditional_expression call identifier argument_list identifier identifier none | returns the earliest deadline point in time |
def _make_parser(streamer, the_struct):
"Return a function that parses the given structure into a dict"
struct_items = [s.split(":") for s in the_struct.split()]
names = [s[0] for s in struct_items]
types = ''.join(s[1] for s in struct_items)
def f(message_stream):
return streamer.parse_as_dict(names, types, message_stream)
return f | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list string string_start string_content string_end for_in_clause identifier call attribute identifier identifier argument_list expression_statement assignment identifier list_comprehension subscript identifier integer for_in_clause identifier identifier expression_statement assignment identifier call attribute string string_start string_end identifier generator_expression subscript identifier integer for_in_clause identifier identifier function_definition identifier parameters identifier block return_statement call attribute identifier identifier argument_list identifier identifier identifier return_statement identifier | Return a function that parses the given structure into a dict |
def plot_losses(self, skip_start:int=0, skip_end:int=0, return_fig:bool=None)->Optional[plt.Figure]:
"Plot training and validation losses."
fig, ax = plt.subplots(1,1)
losses = self._split_list(self.losses, skip_start, skip_end)
iterations = self._split_list(range_of(self.losses), skip_start, skip_end)
ax.plot(iterations, losses, label='Train')
val_iter = self._split_list_val(np.cumsum(self.nb_batches), skip_start, skip_end)
val_losses = self._split_list_val(self.val_losses, skip_start, skip_end)
ax.plot(val_iter, val_losses, label='Validation')
ax.set_ylabel('Loss')
ax.set_xlabel('Batches processed')
ax.legend()
if ifnone(return_fig, defaults.return_fig): return fig
if not IN_NOTEBOOK: plot_sixel(fig) | module function_definition identifier parameters identifier typed_default_parameter identifier type identifier integer typed_default_parameter identifier type identifier integer typed_default_parameter identifier type identifier none type generic_type identifier type_parameter type attribute identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list integer integer expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list if_statement call identifier argument_list identifier attribute identifier identifier block return_statement identifier if_statement not_operator identifier block expression_statement call identifier argument_list identifier | Plot training and validation losses. |
def getSheet(book=None,sheet=None):
if book and not book.lower() in [x.lower() for x in bookNames()]:
print("book %s doesn't exist"%book)
return
if book is None:
book=activeBook().lower()
if book is None:
print("no book given or selected")
return
if sheet and not sheet.lower() in [x.lower() for x in sheetNames(book)]:
print("sheet %s doesn't exist"%sheet)
return
if sheet is None:
sheet=activeSheet().lower()
if sheet is None:
return("no sheet given or selected")
print
for poSheet in PyOrigin.WorksheetPages(book).Layers():
if poSheet.GetName().lower()==sheet.lower():
return poSheet
return False | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none block if_statement boolean_operator identifier not_operator comparison_operator call attribute identifier identifier argument_list list_comprehension call attribute identifier identifier argument_list for_in_clause identifier call identifier argument_list block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier return_statement if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute call identifier argument_list identifier argument_list if_statement comparison_operator identifier none block expression_statement call identifier argument_list string string_start string_content string_end return_statement if_statement boolean_operator identifier not_operator comparison_operator call attribute identifier identifier argument_list list_comprehension call attribute identifier identifier argument_list for_in_clause identifier call identifier argument_list identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier return_statement if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute call identifier argument_list identifier argument_list if_statement comparison_operator identifier none block return_statement parenthesized_expression string string_start string_content string_end expression_statement identifier for_statement identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list block if_statement comparison_operator call attribute call attribute identifier identifier argument_list identifier argument_list call attribute identifier identifier argument_list block return_statement identifier return_statement false | returns the pyorigin object for a sheet. |
def on_pubmsg(self, connection, event):
for message in event.arguments():
self.log(event, message)
command_args = filter(None, message.split())
command_name = command_args.pop(0)
for handler in self.events["command"]:
if handler.event.args["command"] == command_name:
self.handle_command_event(event, handler, command_args) | module function_definition identifier parameters identifier identifier identifier block for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list none call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list integer for_statement identifier subscript attribute identifier identifier string string_start string_content string_end block if_statement comparison_operator subscript attribute attribute identifier identifier identifier string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list identifier identifier identifier | Log any public messages, and also handle the command event. |
def catch_error(func):
import amqp
try:
import pika.exceptions
connect_exceptions = (
pika.exceptions.ConnectionClosed,
pika.exceptions.AMQPConnectionError,
)
except ImportError:
connect_exceptions = ()
connect_exceptions += (
select.error,
socket.error,
amqp.ConnectionError
)
def wrap(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except connect_exceptions as e:
logging.error('RabbitMQ error: %r, reconnect.', e)
self.reconnect()
return func(self, *args, **kwargs)
return wrap | module function_definition identifier parameters identifier block import_statement dotted_name identifier try_statement block import_statement dotted_name identifier identifier expression_statement assignment identifier tuple attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier except_clause identifier block expression_statement assignment identifier tuple expression_statement augmented_assignment identifier tuple attribute identifier identifier attribute identifier identifier attribute identifier identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block try_statement block return_statement call identifier argument_list identifier list_splat identifier dictionary_splat identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list return_statement call identifier argument_list identifier list_splat identifier dictionary_splat identifier return_statement identifier | Catch errors of rabbitmq then reconnect |
def unlock(self):
if not hasattr(self, 'session'):
raise RuntimeError('Error detected! The session that you want to close does not exist any more!')
logger.debug("Closed database session of '%s'" % self._database)
self.session.close()
del self.session | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block raise_statement call identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list delete_statement attribute identifier identifier | Closes the session to the database. |
def replay_data(self, replay_path):
with gfile.Open(self.abs_replay_path(replay_path), "rb") as f:
return f.read() | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block return_statement call attribute identifier identifier argument_list | Return the replay data given a path to the replay. |
def are_plugins_in_order(plugins_conf, *plugins_names):
all_plugins_names = [plugin['name'] for plugin in plugins_conf or []]
start_index = 0
for plugin_name in plugins_names:
try:
start_index = all_plugins_names.index(plugin_name, start_index)
except ValueError:
return False
return True | module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement assignment identifier list_comprehension subscript identifier string string_start string_content string_end for_in_clause identifier boolean_operator identifier list expression_statement assignment identifier integer for_statement identifier identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier except_clause identifier block return_statement false return_statement true | Check if plugins are configured in given order. |
def _get(self, url, query=None, **kwargs):
return self._request('get', url, query, **kwargs) | module function_definition identifier parameters identifier identifier default_parameter identifier none dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier dictionary_splat identifier | Wrapper for the HTTP GET request. |
def BIF_templates(self):
network_template = Template('network $name {\n}\n')
variable_template = Template(
)
property_template = Template(' property $prop ;\n')
probability_template = Template(
)
return network_template, variable_template, property_template, probability_template | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list string string_start string_content escape_sequence escape_sequence string_end expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list string string_start string_content escape_sequence string_end expression_statement assignment identifier call identifier argument_list return_statement expression_list identifier identifier identifier identifier | Create template for writing in BIF format |
def on_top_level_changed(self, top_level):
if top_level:
self.undock_action.setDisabled(True)
else:
self.undock_action.setDisabled(False) | module function_definition identifier parameters identifier identifier block if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list true else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list false | Actions to perform when a plugin is undocked to be moved. |
def add_capability(self, cls):
if _debug: Collector._debug("add_capability %r", cls)
bases = (self.__class__, cls)
if _debug: Collector._debug(" - bases: %r", bases)
self.capabilities.append(cls)
newtype = type(self.__class__.__name__ + '+' + cls.__name__, bases, {})
self.__class__ = newtype
if hasattr(cls, '__init__'):
if _debug: Collector._debug(" - calling %r.__init__", cls)
cls.__init__(self) | module function_definition identifier parameters identifier identifier block if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier tuple attribute identifier identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list binary_operator binary_operator attribute attribute identifier identifier identifier string string_start string_content string_end attribute identifier identifier identifier dictionary expression_statement assignment attribute identifier identifier identifier if_statement call identifier argument_list identifier string string_start string_content string_end block if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier | Add a capability to this object. |
def should_stop_early(self) -> bool:
if self._patience is None:
return False
else:
return self._epochs_with_no_improvement >= self._patience | module function_definition identifier parameters identifier type identifier block if_statement comparison_operator attribute identifier identifier none block return_statement false else_clause block return_statement comparison_operator attribute identifier identifier attribute identifier identifier | Returns true if improvement has stopped for long enough. |
def reload_sources(self, names):
try:
self.like.logLike.loadSourceMaps(names, True, True)
self._scale_srcmap(self._src_expscale, check_header=False,
names=names)
except:
for name in names:
self.reload_source(name) | module function_definition identifier parameters identifier identifier block try_statement block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier true true expression_statement call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier false keyword_argument identifier identifier except_clause block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier | Recompute the source map for a list of sources in the model. |
def units(self, varname):
if not varname in self.mapping.vars:
raise fgFDMError('Unknown variable %s' % varname)
return self.mapping.vars[varname].units | module function_definition identifier parameters identifier identifier block if_statement not_operator comparison_operator identifier attribute attribute identifier identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier return_statement attribute subscript attribute attribute identifier identifier identifier identifier identifier | return the default units of a variable |
def _checkAndConvertIndex(self, index):
if index < 0:
index = len(self) + index
if index < 0 or index >= self._doc.blockCount():
raise IndexError('Invalid block index', index)
return index | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier integer block expression_statement assignment identifier binary_operator call identifier argument_list identifier identifier if_statement boolean_operator comparison_operator identifier integer comparison_operator identifier call attribute attribute identifier identifier identifier argument_list block raise_statement call identifier argument_list string string_start string_content string_end identifier return_statement identifier | Check integer index, convert from less than zero notation |
def download_content_gui(**args):
global row
if not args ['directory']:
args ['directory'] = args ['query'].replace(' ', '-')
root1 = Frame(root)
t1 = threading.Thread(target = search_function, args = (root1,
args['query'], args['website'], args['file_type'], args['limit'],args['option']))
t1.start()
task(root1)
t1.join()
row = Frame(root)
row.pack()
if args['parallel']:
download_parallel_gui(row, links, args['directory'], args['min_file_size'],
args['max_file_size'], args['no_redirects'])
else:
download_series_gui(row, links, args['directory'], args['min_file_size'],
args['max_file_size'], args['no_redirects']) | module function_definition identifier parameters dictionary_splat_pattern identifier block global_statement identifier if_statement not_operator subscript identifier string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier tuple identifier subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list expression_statement call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list if_statement subscript identifier string string_start string_content string_end block expression_statement call identifier argument_list identifier identifier subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end else_clause block expression_statement call identifier argument_list identifier identifier subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end | function to fetch links and download them |
def hash_key(self, key):
for i, destination_key in enumerate(self._dict):
if key < destination_key:
return destination_key
return key | module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block if_statement comparison_operator identifier identifier block return_statement identifier return_statement identifier | "Hash" all keys in a timerange to the same value. |
def OnAttributesToolbarToggle(self, event):
self.main_window.attributes_toolbar.SetGripperVisible(True)
attributes_toolbar_info = \
self.main_window._mgr.GetPane("attributes_toolbar")
self._toggle_pane(attributes_toolbar_info)
event.Skip() | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list true expression_statement assignment identifier line_continuation call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | Format toolbar toggle event handler |
def encode(self, value):
if type(value) == str and self.enum and value in self.enum:
value = self.enum[value]
if type(value) == int:
if self.shift > 0:
value <<= self.shift
if self.mask is not None:
value &= self.mask
return self.type.encode(value) if self.type else bytearray() | module function_definition identifier parameters identifier identifier block if_statement boolean_operator boolean_operator comparison_operator call identifier argument_list identifier identifier attribute identifier identifier comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier if_statement comparison_operator call identifier argument_list identifier identifier block if_statement comparison_operator attribute identifier identifier integer block expression_statement augmented_assignment identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement augmented_assignment identifier attribute identifier identifier return_statement conditional_expression call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier call identifier argument_list | Encodes the given value according to this FieldDefinition. |
def load_search_space(path):
content = json.dumps(get_json_content(path))
if not content:
raise ValueError('searchSpace file should not be empty')
return content | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end return_statement identifier | load search space content |
def start(self, *args, **kwargs):
self.queue = Queue()
thread = Thread(target=self._threaded, args=args, kwargs=kwargs)
thread.start()
return Asynchronous.Result(self.queue, thread) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment attribute identifier identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list attribute identifier identifier identifier | Start execution of the function. |
def edit(community):
form = EditCommunityForm(formdata=request.values, obj=community)
deleteform = DeleteCommunityForm()
ctx = mycommunities_ctx()
ctx.update({
'form': form,
'is_new': False,
'community': community,
'deleteform': deleteform,
})
if form.validate_on_submit():
for field, val in form.data.items():
setattr(community, field, val)
file = request.files.get('logo', None)
if file:
if not community.save_logo(file.stream, file.filename):
form.logo.errors.append(_(
'Cannot add this file as a logo. Supported formats: '
'PNG, JPG and SVG. Max file size: 1.5 MB.'))
if not form.logo.errors:
db.session.commit()
flash("Community successfully edited.", category='success')
return redirect(url_for('.edit', community_id=community.id))
return render_template(
current_app.config['COMMUNITIES_EDIT_TEMPLATE'],
**ctx
) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end false pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier if_statement call attribute identifier identifier argument_list block for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call identifier argument_list identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end none if_statement identifier block if_statement not_operator call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end if_statement not_operator attribute attribute identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end return_statement call identifier argument_list call identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier return_statement call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end dictionary_splat identifier | Create or edit a community. |
def wait_for_relation(service_name, relation_name, timeout=120):
start_time = time.time()
while True:
relation = unit_info(service_name, 'relations').get(relation_name)
if relation is not None and relation['state'] == 'up':
break
if time.time() - start_time >= timeout:
raise RuntimeError('timeout waiting for relation to be up')
time.sleep(SLEEP_AMOUNT) | module function_definition identifier parameters identifier identifier default_parameter identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list while_statement true block expression_statement assignment identifier call attribute call identifier argument_list identifier string string_start string_content string_end identifier argument_list identifier if_statement boolean_operator comparison_operator identifier none comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block break_statement if_statement comparison_operator binary_operator call attribute identifier identifier argument_list identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier | Wait `timeout` seconds for a given relation to come up. |
def _get_data_attr(data, attr):
if isinstance(data, dict):
data = data['__id']
data_obj = Data.objects.get(id=data)
return getattr(data_obj, attr) | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier return_statement call identifier argument_list identifier identifier | Get data object field. |
def add_reader(self, fd, callback):
" Start watching the file descriptor for read availability. "
h = msvcrt.get_osfhandle(fd)
self._read_fds[h] = callback | module function_definition identifier parameters identifier identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript attribute identifier identifier identifier identifier | Start watching the file descriptor for read availability. |
def _find_usage_instances(self):
paginator = self.conn.get_paginator('describe_db_instances')
for page in paginator.paginate():
for instance in page['DBInstances']:
self.limits['Read replicas per master']._add_current_usage(
len(instance['ReadReplicaDBInstanceIdentifiers']),
aws_type='AWS::RDS::DBInstance',
resource_id=instance['DBInstanceIdentifier']
) | 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 for_statement identifier call attribute identifier identifier argument_list block for_statement identifier subscript identifier string string_start string_content string_end block expression_statement call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list call identifier argument_list subscript identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end | find usage for DB Instances and related limits |
def convert(cls, record):
if isinstance(record, list):
return [cls._convert(r) for r in record]
else:
return [cls._convert(record)] | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block return_statement list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier identifier else_clause block return_statement list call attribute identifier identifier argument_list identifier | Converts a single dictionary or list of dictionaries into converted list of dictionaries. |
def _pid_to_id(self, pid):
return d1_common.url.joinPathElements(
self._base_url,
self._version_tag,
"resolve",
d1_common.url.encodePathElement(pid),
) | module function_definition identifier parameters identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list identifier | Converts a pid to a URI that can be used as an OAI-ORE identifier. |
def _getEventsByDay(self, request, firstDay, lastDay):
return getAllEventsByDay(request, firstDay, lastDay, home=self) | module function_definition identifier parameters identifier identifier identifier identifier block return_statement call identifier argument_list identifier identifier identifier keyword_argument identifier identifier | Return my child events for the dates given, grouped by day. |
def update_command(args):
updated = update_requirements_file(
args.requirements_file, args.skip_packages)
if updated:
print('Updated requirements in {}:'.format(args.requirements_file))
for item in updated:
print(' * {} from {} to {}.'.format(*item))
else:
print('All dependencies in {} are up-to-date.'.format(
args.requirements_file)) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier if_statement identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier for_statement identifier identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list list_splat identifier else_clause block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier | Updates all dependencies the specified requirements file. |
def _SafeEncodeBytes(field, value):
try:
if field.repeated:
result = [base64.urlsafe_b64encode(byte) for byte in value]
else:
result = base64.urlsafe_b64encode(value)
complete = True
except TypeError:
result = value
complete = False
return CodecResult(value=result, complete=complete) | module function_definition identifier parameters identifier identifier block try_statement block if_statement attribute identifier identifier block expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier true except_clause identifier block expression_statement assignment identifier identifier expression_statement assignment identifier false return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier | Encode the bytes in value as urlsafe base64. |
def remove_external_references_from_srl_layer(self):
if self.srl_layer is not None:
for pred in self.srl_layer.get_predicates():
pred.remove_external_references()
pred.remove_external_references_from_roles() | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Removes all external references present in the term layer |
def light(cls):
"Make the current foreground color light."
wAttributes = cls._get_text_attributes()
wAttributes |= win32.FOREGROUND_INTENSITY
cls._set_text_attributes(wAttributes) | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement augmented_assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Make the current foreground color light. |
def _add_header_domains_xml(self, document):
for domain, attrs in self.header_domains.items():
header_element = document.createElement(
'allow-http-request-headers-from'
)
header_element.setAttribute('domain', domain)
header_element.setAttribute('headers', ','.join(attrs['headers']))
if not attrs['secure']:
header_element.setAttribute('secure', 'false')
document.documentElement.appendChild(header_element) | module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list subscript identifier string string_start string_content string_end if_statement not_operator subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Generates the XML elements for allowed header domains. |
def update_entries(entries: Entries, data: dict) -> None:
for entry in entries:
entry.update(data) | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type none block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier | Update each entry in the list with some data. |
def build(self) -> Application:
pipelines = self._build_pipelines()
self._factory.new('Application', pipelines)
return self._factory['Application'] | module function_definition identifier parameters identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier return_statement subscript attribute identifier identifier string string_start string_content string_end | Put the application together. |
def _get_stream(self) -> Iterator:
if self._stream is None:
self._stream = iter(self._get_stream_fn())
return self._stream | module function_definition identifier parameters identifier type identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call identifier argument_list call attribute identifier identifier argument_list return_statement attribute identifier identifier | Possibly create and return raw dataset stream iterator. |
def read_mac(self):
words = [self.read_efuse(2), self.read_efuse(1)]
bitstring = struct.pack(">II", *words)
bitstring = bitstring[2:8]
try:
return tuple(ord(b) for b in bitstring)
except TypeError:
return tuple(bitstring) | module function_definition identifier parameters identifier block expression_statement assignment identifier list call attribute identifier identifier argument_list integer call attribute identifier identifier argument_list integer expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end list_splat identifier expression_statement assignment identifier subscript identifier slice integer integer try_statement block return_statement call identifier generator_expression call identifier argument_list identifier for_in_clause identifier identifier except_clause identifier block return_statement call identifier argument_list identifier | Read MAC from EFUSE region |
def timestep_text(self):
if self.header.analysis_period.timestep == 1:
return 'Hourly'
else:
return '{} Minute'.format(int(60 / self.header.analysis_period.timestep)) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute attribute attribute identifier identifier identifier identifier integer block return_statement string string_start string_content string_end else_clause block return_statement call attribute string string_start string_content string_end identifier argument_list call identifier argument_list binary_operator integer attribute attribute attribute identifier identifier identifier identifier | Return a text string representing the timestep of the collection. |
def _send(self):
while len(self.queue) > 0:
metric = self.queue.popleft()
path = '%s.%s.%s' % (
metric.getPathPrefix(),
metric.getCollectorPath(),
metric.getMetricPath()
)
topic, value, timestamp = str(metric).split()
logging.debug(
"Sending.. topic[%s], value[%s], timestamp[%s]",
path,
value,
timestamp
)
self.api.metric(path, (timestamp, value), host=metric.host) | module function_definition identifier parameters identifier block while_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier binary_operator string string_start string_content string_end tuple call attribute identifier identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement assignment pattern_list identifier identifier identifier call attribute call identifier argument_list identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier tuple identifier identifier keyword_argument identifier attribute identifier identifier | Take metrics from queue and send it to Datadog API |
def paired_paths(main_path, fmt, formats):
if not formats:
return [(main_path, {'extension': os.path.splitext(main_path)[1]})]
formats = long_form_multiple_formats(formats)
base = base_path(main_path, fmt)
paths = [full_path(base, fmt) for fmt in formats]
if main_path not in paths:
raise InconsistentPath(u"Paired paths '{}' do not include the current notebook path '{}'. "
u"Current format is '{}', and paired formats are '{}'."
.format("','".join(paths), main_path, short_form_one_format(fmt),
short_form_multiple_formats(formats)))
if len(paths) > len(set(paths)):
raise InconsistentPath(u'Duplicate paired paths for this notebook. Please fix jupytext.formats.')
return list(zip(paths, formats)) | module function_definition identifier parameters identifier identifier identifier block if_statement not_operator identifier block return_statement list tuple identifier dictionary pair string string_start string_content string_end subscript call attribute attribute identifier identifier identifier argument_list identifier integer expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier list_comprehension call identifier argument_list identifier identifier for_in_clause identifier identifier if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier call identifier argument_list identifier call identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier call identifier argument_list call identifier argument_list identifier block raise_statement call identifier argument_list string string_start string_content string_end return_statement call identifier argument_list call identifier argument_list identifier identifier | Return the list of paired notebooks, given main path, and the list of formats |
def doc_open():
doc_index = os.path.join(DOCS_DIRECTORY, 'build', 'html', 'index.html')
if sys.platform == 'darwin':
subprocess.check_call(['open', doc_index])
elif sys.platform == 'win32':
subprocess.check_call(['start', doc_index], shell=True)
elif sys.platform == 'linux2':
subprocess.check_call(['xdg-open', doc_index])
else:
print_failure_message(
"Unsupported platform. Please open `{0}' manually.".format(
doc_index)) | module function_definition identifier parameters block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list list string string_start string_content string_end identifier elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list list string string_start string_content string_end identifier keyword_argument identifier true elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list list string string_start string_content string_end identifier else_clause block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier | Build the HTML docs and open them in a web browser. |
def _bpe_to_words(sentence, delimiter='@@'):
words = []
word = ''
delimiter_len = len(delimiter)
for subwords in sentence:
if len(subwords) >= delimiter_len and subwords[-delimiter_len:] == delimiter:
word += subwords[:-delimiter_len]
else:
word += subwords
words.append(word)
word = ''
return words | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier list expression_statement assignment identifier string string_start string_end expression_statement assignment identifier call identifier argument_list identifier for_statement identifier identifier block if_statement boolean_operator comparison_operator call identifier argument_list identifier identifier comparison_operator subscript identifier slice unary_operator identifier identifier block expression_statement augmented_assignment identifier subscript identifier slice unary_operator identifier else_clause block expression_statement augmented_assignment identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier string string_start string_end return_statement identifier | Convert a sequence of bpe words into sentence. |
def q(self, val):
self._q = np.asarray(val)
self.Q = cumsum(val) | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier call identifier argument_list identifier | Setter method for q. |
def diff(self):
self._copyfiles = False
self._updatefiles = False
self._purge = False
self._creatdirs = False
self._updatefiles = False
self.log('Difference of directory %s from %s\n' %
(self._dir2, self._dir1))
self._diff(self._dir1, self._dir2) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier false expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier | Only report difference in content between two directories |
def init(self, aggregators):
assert len(aggregators) == self.num_aggregation_workers, aggregators
if len(self.remote_evaluators) < self.num_aggregation_workers:
raise ValueError(
"The number of aggregation workers should not exceed the "
"number of total evaluation workers ({} vs {})".format(
self.num_aggregation_workers, len(self.remote_evaluators)))
assigned_evaluators = collections.defaultdict(list)
for i, ev in enumerate(self.remote_evaluators):
assigned_evaluators[i % self.num_aggregation_workers].append(ev)
self.workers = aggregators
for i, worker in enumerate(self.workers):
worker.init.remote(
self.broadcasted_weights, assigned_evaluators[i],
self.max_sample_requests_in_flight_per_worker,
self.replay_proportion, self.replay_buffer_num_slots,
self.train_batch_size, self.sample_batch_size)
self.agg_tasks = TaskPool()
for agg in self.workers:
agg.set_weights.remote(self.broadcasted_weights)
self.agg_tasks.add(agg, agg.get_train_batches.remote())
self.initialized = True | module function_definition identifier parameters identifier identifier block assert_statement comparison_operator call identifier argument_list identifier attribute identifier identifier identifier if_statement comparison_operator call identifier argument_list attribute identifier identifier attribute identifier identifier block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block expression_statement call attribute subscript identifier binary_operator identifier attribute identifier identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier subscript identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list for_statement identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier true | Deferred init so that we can pass in previously created workers. |
def largest_indices(arr, n):
"Returns the `n` largest indices from a numpy array `arr`."
flat = arr.flatten()
indices = np.argpartition(flat, -n)[-n:]
indices = indices[np.argsort(-flat[indices])]
return np.unravel_index(indices, arr.shape) | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier subscript call attribute identifier identifier argument_list identifier unary_operator identifier slice unary_operator identifier expression_statement assignment identifier subscript identifier call attribute identifier identifier argument_list unary_operator subscript identifier identifier return_statement call attribute identifier identifier argument_list identifier attribute identifier identifier | Returns the `n` largest indices from a numpy array `arr`. |
def show_setup(self):
shell = os.getenv('SHELL')
if not shell:
raise SystemError("No $SHELL env var found")
shell = os.path.basename(shell)
if shell not in self.script_body:
raise SystemError("Unsupported shell: %s" % shell)
tplvars = {
"prog": '-'.join(self.prog.split()[:-1]),
"shell": shell,
"name": self.name
}
print(self.trim(self.script_header % tplvars))
print(self.trim(self.script_body[shell] % tplvars))
print(self.trim(self.script_footer % tplvars)) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier attribute identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list subscript call attribute attribute identifier identifier identifier argument_list slice unary_operator integer pair string string_start string_content string_end identifier pair string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list call attribute identifier identifier argument_list binary_operator attribute identifier identifier identifier expression_statement call identifier argument_list call attribute identifier identifier argument_list binary_operator subscript attribute identifier identifier identifier identifier expression_statement call identifier argument_list call attribute identifier identifier argument_list binary_operator attribute identifier identifier identifier | Provide a helper script for the user to setup completion. |
def apis(self):
value = self.attributes['apis']
if isinstance(value, six.string_types):
value = shlex.split(value)
return value | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier | List of API to test |
def lookup_dirent(event, filesystem_content, journal_content):
for dirent in filesystem_content[event.inode]:
if dirent.path.endswith(event.name):
return dirent
path = lookup_folder(event, filesystem_content)
if path is not None:
return Dirent(event.inode, path, -1, None, False, 0, 0, 0, 0)
path = lookup_deleted_folder(event, filesystem_content, journal_content)
if path is not None:
return Dirent(event.inode, path, -1, None, False, 0, 0, 0, 0)
raise LookupError("File %s not found" % event.name) | module function_definition identifier parameters identifier identifier identifier block for_statement identifier subscript identifier attribute identifier identifier block if_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block return_statement identifier expression_statement assignment identifier call identifier argument_list identifier identifier if_statement comparison_operator identifier none block return_statement call identifier argument_list attribute identifier identifier identifier unary_operator integer none false integer integer integer integer expression_statement assignment identifier call identifier argument_list identifier identifier identifier if_statement comparison_operator identifier none block return_statement call identifier argument_list attribute identifier identifier identifier unary_operator integer none false integer integer integer integer raise_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier | Lookup the dirent given a journal event. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.