code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def defan(self, pattern):
self.checkpat(pattern)
self.A_a_user_defined.extend((pattern, "an"))
return 1 | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list tuple identifier string string_start string_content string_end return_statement integer | Define the indefinate article as 'an' for words matching pattern. |
def behavior_script(url, template_parameters=None, behaviors_dir=None):
import re, logging, json
for behavior in behaviors(behaviors_dir=behaviors_dir):
if re.match(behavior['url_regex'], url):
parameters = dict()
if 'default_parameters' in behavior:
parameters.update(behavior['default_parameters'])
if template_parameters:
parameters.update(template_parameters)
template = jinja2_environment(behaviors_dir).get_template(
behavior['behavior_js_template'])
script = template.render(parameters)
logging.info(
'using template=%r populated with parameters=%r for %r',
behavior['behavior_js_template'], json.dumps(parameters), url)
return script
return None | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block import_statement dotted_name identifier dotted_name identifier dotted_name identifier for_statement identifier call identifier argument_list keyword_argument identifier identifier block if_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end identifier block expression_statement assignment identifier call identifier argument_list if_statement comparison_operator string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list identifier identifier return_statement identifier return_statement none | Returns the javascript behavior string populated with template_parameters. |
def _validate_tag_sets(tag_sets):
if tag_sets is None:
return tag_sets
if not isinstance(tag_sets, list):
raise TypeError((
"Tag sets %r invalid, must be a list") % (tag_sets,))
if len(tag_sets) == 0:
raise ValueError((
"Tag sets %r invalid, must be None or contain at least one set of"
" tags") % (tag_sets,))
for tags in tag_sets:
if not isinstance(tags, Mapping):
raise TypeError(
"Tag set %r invalid, must be an instance of dict, "
"bson.son.SON or other type that inherits from "
"collection.Mapping" % (tags,))
return tag_sets | module function_definition identifier parameters identifier block if_statement comparison_operator identifier none block return_statement identifier if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list binary_operator parenthesized_expression string string_start string_content string_end tuple identifier if_statement comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list binary_operator parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end tuple identifier for_statement identifier identifier block if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end tuple identifier return_statement identifier | Validate tag sets for a MongoReplicaSetClient. |
def docker_context():
try:
client = docker.from_env(
version = "auto"
, timeout = int(os.environ.get("DOCKER_CLIENT_TIMEOUT", 180))
, assert_hostname = False
)
info = client.info()
log.info("Connected to docker daemon\tdriver=%s\tkernel=%s", info["Driver"], info["KernelVersion"])
except (DockerException, APIError) as error:
raise BadDockerConnection(error=error)
return client | module function_definition identifier parameters block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end integer keyword_argument identifier false expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end except_clause as_pattern tuple identifier identifier as_pattern_target identifier block raise_statement call identifier argument_list keyword_argument identifier identifier return_statement identifier | Make a docker context |
def _output_tags(self):
for class_name, properties in sorted(self.resources.items()):
for key, value in sorted(properties.items()):
validator = self.override.get_validator(class_name, key)
if key == 'Tags' and validator is None:
print("from troposphere import Tags")
return
for class_name, properties in sorted(self.properties.items()):
for key, value in sorted(properties.items()):
validator = self.override.get_validator(class_name, key)
if key == 'Tags' and validator is None:
print("from troposphere import Tags")
return | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block for_statement pattern_list identifier identifier call identifier argument_list call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement boolean_operator comparison_operator identifier string string_start string_content string_end comparison_operator identifier none block expression_statement call identifier argument_list string string_start string_content string_end return_statement for_statement pattern_list identifier identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block for_statement pattern_list identifier identifier call identifier argument_list call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement boolean_operator comparison_operator identifier string string_start string_content string_end comparison_operator identifier none block expression_statement call identifier argument_list string string_start string_content string_end return_statement | Look for a Tags object to output a Tags import |
def logger(self, iteration, ret):
print("Learning rate: {:f}".format(self.lr_scheduler.get_lr()[0]))
entropies = getEntropies(self.model)
print("Entropy and max entropy: ", float(entropies[0]), entropies[1])
print("Training time for epoch=", self.epoch_train_time)
for noise in self.noise_values:
print("Noise= {:3.2f}, loss = {:5.4f}, Accuracy = {:5.3f}%".format(
noise, ret[noise]["loss"], 100.0*ret[noise]["accuracy"]))
print("Full epoch time =", self.epoch_time)
if ret[0.0]["accuracy"] > 0.7:
self.best_noise_score = max(ret[0.1]["accuracy"], self.best_noise_score)
self.best_epoch = iteration | module function_definition identifier parameters identifier identifier identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list subscript call attribute attribute identifier identifier identifier argument_list integer expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement call identifier argument_list string string_start string_content string_end call identifier argument_list subscript identifier integer subscript identifier integer expression_statement call identifier argument_list string string_start string_content string_end attribute identifier identifier for_statement identifier attribute identifier identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier subscript subscript identifier identifier string string_start string_content string_end binary_operator float subscript subscript identifier identifier string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end attribute identifier identifier if_statement comparison_operator subscript subscript identifier float string string_start string_content string_end float block expression_statement assignment attribute identifier identifier call identifier argument_list subscript subscript identifier float string string_start string_content string_end attribute identifier identifier expression_statement assignment attribute identifier identifier identifier | Print out relevant information at each epoch |
def _get_coarse_dataset(self, key, info):
angles = self.root.find('.//Tile_Angles')
if key in ['solar_zenith_angle', 'solar_azimuth_angle']:
elts = angles.findall(info['xml_tag'] + '/Values_List/VALUES')
return np.array([[val for val in elt.text.split()] for elt in elts],
dtype=np.float)
elif key in ['satellite_zenith_angle', 'satellite_azimuth_angle']:
arrays = []
elts = angles.findall(info['xml_tag'] + '[@bandId="1"]')
for elt in elts:
items = elt.findall(info['xml_item'] + '/Values_List/VALUES')
arrays.append(np.array([[val for val in item.text.split()] for item in items],
dtype=np.float))
return np.nanmean(np.dstack(arrays), -1)
else:
return | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier list string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator subscript identifier string string_start string_content string_end string string_start string_content string_end return_statement call attribute identifier identifier argument_list list_comprehension list_comprehension identifier for_in_clause identifier call attribute attribute identifier identifier identifier argument_list for_in_clause identifier identifier keyword_argument identifier attribute identifier identifier elif_clause comparison_operator identifier list string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier list expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator subscript identifier string string_start string_content string_end string string_start string_content string_end for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list list_comprehension list_comprehension identifier for_in_clause identifier call attribute attribute identifier identifier identifier argument_list for_in_clause identifier identifier keyword_argument identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier unary_operator integer else_clause block return_statement | Get the coarse dataset refered to by `key` from the XML data. |
def remote_interruptCommand(self, stepId, why):
log.msg("asked to interrupt current command: {0}".format(why))
self.activity()
if not self.command:
log.msg(" .. but none was running")
return
self.command.doInterrupt() | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement expression_statement call attribute attribute identifier identifier identifier argument_list | Halt the current step. |
def write_boundaries(self, filename):
fid = open(filename, 'w')
for i in self.Boundaries:
print(i)
fid.write(
'{0} {1} {2} {3} {4}\n'.format(
i[0][0], i[0][1], i[1][0], i[1][1], i[2]))
fid.close() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end for_statement identifier attribute identifier identifier block expression_statement call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list subscript subscript identifier integer integer subscript subscript identifier integer integer subscript subscript identifier integer integer subscript subscript identifier integer integer subscript identifier integer expression_statement call attribute identifier identifier argument_list | Write boundary lines X1 Y1 X2 Y2 TYPE to file |
def removeComments(element):
global _num_bytes_saved_in_comments
num = 0
if isinstance(element, xml.dom.minidom.Comment):
_num_bytes_saved_in_comments += len(element.data)
element.parentNode.removeChild(element)
num += 1
else:
for subelement in element.childNodes[:]:
num += removeComments(subelement)
return num | module function_definition identifier parameters identifier block global_statement identifier expression_statement assignment identifier integer if_statement call identifier argument_list identifier attribute attribute attribute identifier identifier identifier identifier block expression_statement augmented_assignment identifier call identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement augmented_assignment identifier integer else_clause block for_statement identifier subscript attribute identifier identifier slice block expression_statement augmented_assignment identifier call identifier argument_list identifier return_statement identifier | Removes comments from the element and its children. |
def compute_default_choice(self):
choices = self.choices
if len(choices) == 0:
return None
high_choice = max(choices, key=lambda choice: choice.performance)
self.redis.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "default-choice", high_choice.name)
self.refresh()
return high_choice | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block return_statement none expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier lambda lambda_parameters identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator identifier attribute identifier identifier string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list return_statement identifier | Computes and sets the default choice |
def make_node_dict(outer_list, sort="zone"):
raw_dict = {}
x = 1
for inner_list in outer_list:
for node in inner_list:
raw_dict[x] = node
x += 1
if sort == "name":
srt_dict = OrderedDict(sorted(raw_dict.items(), key=lambda k:
(k[1].cloud, k[1].name.lower())))
else:
srt_dict = OrderedDict(sorted(raw_dict.items(), key=lambda k:
(k[1].cloud, k[1].zone, k[1].name.lower())))
x = 1
node_dict = {}
for i, v in srt_dict.items():
node_dict[x] = v
x += 1
return node_dict | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier dictionary expression_statement assignment identifier integer for_statement identifier identifier block for_statement identifier identifier block expression_statement assignment subscript identifier identifier identifier expression_statement augmented_assignment identifier integer if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier lambda lambda_parameters identifier tuple attribute subscript identifier integer identifier call attribute attribute subscript identifier integer identifier identifier argument_list else_clause block expression_statement assignment identifier call identifier argument_list call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier lambda lambda_parameters identifier tuple attribute subscript identifier integer identifier attribute subscript identifier integer identifier call attribute attribute subscript identifier integer identifier identifier argument_list expression_statement assignment identifier integer expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment subscript identifier identifier identifier expression_statement augmented_assignment identifier integer return_statement identifier | Convert node data from nested-list to sorted dict. |
def dtraj_T100K_dt10_n(self, divides):
disc = np.zeros(100, dtype=int)
divides = np.concatenate([divides, [100]])
for i in range(len(divides)-1):
disc[divides[i]:divides[i+1]] = i+1
return disc[self.dtraj_T100K_dt10] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list integer keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list list identifier list integer for_statement identifier call identifier argument_list binary_operator call identifier argument_list identifier integer block expression_statement assignment subscript identifier slice subscript identifier identifier subscript identifier binary_operator identifier integer binary_operator identifier integer return_statement subscript identifier attribute identifier identifier | 100K frames trajectory at timestep 10, arbitrary n-state discretization. |
def drop_index(self, table, column):
self.execute('ALTER TABLE {0} DROP INDEX {1}'.format(wrap(table), column))
self._printer('\tDropped index from column {0}'.format(column)) | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier | Drop an index from a table. |
def knn_impute_reference(
X,
missing_mask,
k,
verbose=False,
print_interval=100):
n_rows, n_cols = X.shape
X_result, D, effective_infinity = \
knn_initialize(X, missing_mask, verbose=verbose)
for i in range(n_rows):
for j in np.where(missing_mask[i, :])[0]:
distances = D[i, :].copy()
distances[missing_mask[:, j]] = effective_infinity
neighbor_indices = np.argsort(distances)
neighbor_distances = distances[neighbor_indices]
valid_distances = neighbor_distances < effective_infinity
neighbor_distances = neighbor_distances[valid_distances][:k]
neighbor_indices = neighbor_indices[valid_distances][:k]
weights = 1.0 / neighbor_distances
weight_sum = weights.sum()
if weight_sum > 0:
column = X[:, j]
values = column[neighbor_indices]
X_result[i, j] = np.dot(values, weights) / weight_sum
return X_result | module function_definition identifier parameters identifier identifier identifier default_parameter identifier false default_parameter identifier integer block expression_statement assignment pattern_list identifier identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier identifier line_continuation call identifier argument_list identifier identifier keyword_argument identifier identifier for_statement identifier call identifier argument_list identifier block for_statement identifier subscript call attribute identifier identifier argument_list subscript identifier identifier slice integer block expression_statement assignment identifier call attribute subscript identifier identifier slice identifier argument_list expression_statement assignment subscript identifier subscript identifier slice identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier comparison_operator identifier identifier expression_statement assignment identifier subscript subscript identifier identifier slice identifier expression_statement assignment identifier subscript subscript identifier identifier slice identifier expression_statement assignment identifier binary_operator float identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier integer block expression_statement assignment identifier subscript identifier slice identifier expression_statement assignment identifier subscript identifier identifier expression_statement assignment subscript identifier identifier identifier binary_operator call attribute identifier identifier argument_list identifier identifier identifier return_statement identifier | Reference implementation of kNN imputation logic. |
def make_prototype_request(*args, **kwargs):
if args and inspect.isclass(args[0]) and issubclass(args[0], Request):
request_cls, arg_list = args[0], args[1:]
return request_cls(*arg_list, **kwargs)
if args and isinstance(args[0], Request):
if args[1:] or kwargs:
raise_args_err("can't interpret args")
return args[0]
return Request(*args, **kwargs) | module function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement boolean_operator boolean_operator identifier call attribute identifier identifier argument_list subscript identifier integer call identifier argument_list subscript identifier integer identifier block expression_statement assignment pattern_list identifier identifier expression_list subscript identifier integer subscript identifier slice integer return_statement call identifier argument_list list_splat identifier dictionary_splat identifier if_statement boolean_operator identifier call identifier argument_list subscript identifier integer identifier block if_statement boolean_operator subscript identifier slice integer identifier block expression_statement call identifier argument_list string string_start string_content string_end return_statement subscript identifier integer return_statement call identifier argument_list list_splat identifier dictionary_splat identifier | Make a prototype Request for a Matcher. |
def _delete_plot(cls, plot_id):
plot = cls._plots.get(plot_id)
if plot is None:
return
plot.cleanup()
del cls._plots[plot_id] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier none block return_statement expression_statement call attribute identifier identifier argument_list delete_statement subscript attribute identifier identifier identifier | Deletes registered plots and calls Plot.cleanup |
def julian_day(t: date) -> int:
dt = t - julian_base_date
return julian_base_number + dt.days | module function_definition identifier parameters typed_parameter identifier type identifier type identifier block expression_statement assignment identifier binary_operator identifier identifier return_statement binary_operator identifier attribute identifier identifier | Convert a Python datetime to a Julian day |
def Parse(self, stat, file_object, knowledge_base):
_, _ = stat, knowledge_base
users = {}
wtmp = file_object.read()
while wtmp:
try:
record = UtmpStruct(wtmp)
except utils.ParsingError:
break
wtmp = wtmp[record.size:]
if record.ut_type != 7:
continue
record.user = record.user.split(b"\x00", 1)[0]
try:
users[record.user] = max(users[record.user], record.sec, 0)
except KeyError:
users[record.user] = record.sec
for user, last_login in iteritems(users):
yield rdf_client.User(
username=utils.SmartUnicode(user), last_logon=last_login * 1000000) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment pattern_list identifier identifier expression_list identifier identifier expression_statement assignment identifier dictionary expression_statement assignment identifier call attribute identifier identifier argument_list while_statement identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier except_clause attribute identifier identifier block break_statement expression_statement assignment identifier subscript identifier slice attribute identifier identifier if_statement comparison_operator attribute identifier identifier integer block continue_statement expression_statement assignment attribute identifier identifier subscript call attribute attribute identifier identifier identifier argument_list string string_start string_content escape_sequence string_end integer integer try_statement block expression_statement assignment subscript identifier attribute identifier identifier call identifier argument_list subscript identifier attribute identifier identifier attribute identifier identifier integer except_clause identifier block expression_statement assignment subscript identifier attribute identifier identifier attribute identifier identifier for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement yield call attribute identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list identifier keyword_argument identifier binary_operator identifier integer | Parse the wtmp file. |
def _reconnect(self):
self.close()
self._db = psycopg2.connect(**self._db_args)
if self._search_path:
self.execute('set search_path=%s;' % self._search_path)
if self._timezone:
self.execute("set timezone='%s';" % self._timezone) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list dictionary_splat attribute identifier identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier | Closes the existing database connection and re-opens it. |
def bump_context(self, name):
data = self._context(name)
data["priority"] = self._next_priority
self._flush_tools() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list | Causes the context's tools to take priority over all others. |
def filter_by_rows(self, rows, ID=None):
rows = to_list(rows)
fil = lambda x: x in rows
applyto = {k: self._positions[k][0] for k in self.keys()}
if ID is None:
ID = self.ID
return self.filter(fil, applyto=applyto, ID=ID) | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier lambda lambda_parameters identifier comparison_operator identifier identifier expression_statement assignment identifier dictionary_comprehension pair identifier subscript subscript attribute identifier identifier identifier integer for_in_clause identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier | Keep only Measurements in corresponding rows. |
def minute_change(device):
hours = datetime.now().strftime('%H')
minutes = datetime.now().strftime('%M')
def helper(current_y):
with canvas(device) as draw:
text(draw, (0, 1), hours, fill="white", font=proportional(CP437_FONT))
text(draw, (15, 1), ":", fill="white", font=proportional(TINY_FONT))
text(draw, (17, current_y), minutes, fill="white", font=proportional(CP437_FONT))
time.sleep(0.1)
for current_y in range(1, 9):
helper(current_y)
minutes = datetime.now().strftime('%M')
for current_y in range(9, 1, -1):
helper(current_y) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block expression_statement call identifier argument_list identifier tuple integer integer identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier call identifier argument_list identifier expression_statement call identifier argument_list identifier tuple integer integer string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier call identifier argument_list identifier expression_statement call identifier argument_list identifier tuple integer identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list float for_statement identifier call identifier argument_list integer integer block expression_statement call identifier argument_list identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end for_statement identifier call identifier argument_list integer integer unary_operator integer block expression_statement call identifier argument_list identifier | When we reach a minute change, animate it. |
def returner(ret):
_options = _get_options(ret)
from_jid = _options.get('from_jid')
password = _options.get('password')
recipient_jid = _options.get('recipient_jid')
if not from_jid:
log.error('xmpp.jid not defined in salt config')
return
if not password:
log.error('xmpp.password not defined in salt config')
return
if not recipient_jid:
log.error('xmpp.recipient not defined in salt config')
return
message = ('id: {0}\r\n'
'function: {1}\r\n'
'function args: {2}\r\n'
'jid: {3}\r\n'
'return: {4}\r\n').format(
ret.get('id'),
ret.get('fun'),
ret.get('fun_args'),
ret.get('jid'),
pprint.pformat(ret.get('return')))
xmpp = SendMsgBot(from_jid, password, recipient_jid, message)
xmpp.register_plugin('xep_0030')
xmpp.register_plugin('xep_0199')
if xmpp.connect():
xmpp.process(block=True)
return True
return False | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement expression_statement assignment identifier call attribute parenthesized_expression concatenated_string string string_start string_content escape_sequence escape_sequence string_end string string_start string_content escape_sequence escape_sequence string_end string string_start string_content escape_sequence escape_sequence string_end string string_start string_content escape_sequence escape_sequence string_end string string_start string_content escape_sequence escape_sequence string_end identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier identifier identifier 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 if_statement call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list keyword_argument identifier true return_statement true return_statement false | Send an xmpp message with the data |
def modify(self, view):
view.params['extra_context'][self.get['name']] = self.get['value']
return view | module function_definition identifier parameters identifier identifier block expression_statement assignment subscript subscript attribute identifier identifier string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end return_statement identifier | adds the get item as extra context |
def create_user(
self, username, email, short_name, full_name,
institute, password=None, **extra_fields):
return self._create_user(
username=username, email=email,
short_name=short_name, full_name=full_name,
institute=institute, password=password,
is_admin=False, **extra_fields) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier default_parameter identifier none dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier false dictionary_splat identifier | Creates a new ordinary person. |
def merge_rects(rect1, rect2):
r = pygame.Rect(rect1)
t = pygame.Rect(rect2)
right = max(r.right, t.right)
bot = max(r.bottom, t.bottom)
x = min(t.x, r.x)
y = min(t.y, r.y)
return pygame.Rect(x, y, right - x, bot - y) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list identifier identifier binary_operator identifier identifier binary_operator identifier identifier | Return the smallest rect containning two rects |
def create_columns(self):
reader = self._get_csv_reader()
headings = six.next(reader)
try:
examples = six.next(reader)
except StopIteration:
examples = []
found_fields = set()
for i, value in enumerate(headings):
if i >= 20:
break
infer_field = self.has_headings and value not in found_fields
to_field = (
{
"date": "date",
"amount": "amount",
"description": "description",
"memo": "description",
"notes": "description",
}.get(value.lower(), "")
if infer_field
else ""
)
if to_field:
found_fields.add(to_field)
TransactionCsvImportColumn.objects.update_or_create(
transaction_import=self,
column_number=i + 1,
column_heading=value if self.has_headings else "",
to_field=to_field,
example=examples[i].strip() if examples else "",
) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause identifier block expression_statement assignment identifier list expression_statement assignment identifier call identifier argument_list for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement comparison_operator identifier integer block break_statement expression_statement assignment identifier boolean_operator attribute identifier identifier comparison_operator identifier identifier expression_statement assignment identifier parenthesized_expression conditional_expression call attribute dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list string string_start string_end identifier string string_start string_end if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier binary_operator identifier integer keyword_argument identifier conditional_expression identifier attribute identifier identifier string string_start string_end keyword_argument identifier identifier keyword_argument identifier conditional_expression call attribute subscript identifier identifier identifier argument_list identifier string string_start string_end | For each column in file create a TransactionCsvImportColumn |
def triangle_area(p0, p1, p2):
if p2.ndim < 2:
p2 = p2[np.newaxis, :]
area = 0.5 * np.abs(p0[0] * p1[1] - p0[0] * p2[:,1] +
p1[0] * p2[:,1] - p1[0] * p0[1] +
p2[:,0] * p0[1] - p2[:,0] * p1[1])
return area | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier subscript identifier attribute identifier identifier slice expression_statement assignment identifier binary_operator float call attribute identifier identifier argument_list binary_operator binary_operator binary_operator binary_operator binary_operator binary_operator subscript identifier integer subscript identifier integer binary_operator subscript identifier integer subscript identifier slice integer binary_operator subscript identifier integer subscript identifier slice integer binary_operator subscript identifier integer subscript identifier integer binary_operator subscript identifier slice integer subscript identifier integer binary_operator subscript identifier slice integer subscript identifier integer return_statement identifier | p2 can be a vector |
def register_series_method(method):
def inner(*args, **kwargs):
class AccessorMethod(object):
__doc__ = method.__doc__
def __init__(self, pandas_obj):
self._obj = pandas_obj
@wraps(method)
def __call__(self, *args, **kwargs):
return method(self._obj, *args, **kwargs)
register_series_accessor(method.__name__)(AccessorMethod)
return method
return inner() | module function_definition identifier parameters identifier block function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block class_definition identifier argument_list identifier block expression_statement assignment identifier attribute identifier identifier function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier identifier decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement call identifier argument_list attribute identifier identifier list_splat identifier dictionary_splat identifier expression_statement call call identifier argument_list attribute identifier identifier argument_list identifier return_statement identifier return_statement call identifier argument_list | Register a function as a method attached to the Pandas Series. |
def OnDialectChoice(self, event):
dialect_name = event.GetString()
value = list(self.choices['dialects']).index(dialect_name)
if dialect_name == 'sniffer':
if self.csvfilepath is None:
event.Skip()
return None
dialect, self.has_header = sniff(self.csvfilepath)
elif dialect_name == 'user':
event.Skip()
return None
else:
dialect = csv.get_dialect(dialect_name)
self._update_settings(dialect)
self.choice_dialects.SetValue(value) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end identifier argument_list identifier if_statement comparison_operator identifier string string_start string_content string_end block if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list return_statement none expression_statement assignment pattern_list identifier attribute identifier identifier call identifier argument_list attribute identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list return_statement none else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Updates all param widgets confirming to the selcted dialect |
def append_message(self, text, output_format=OutputFormat.NormalMessageFormat):
self._append_message(text, self._formats[output_format]) | module function_definition identifier parameters identifier identifier default_parameter identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier subscript attribute identifier identifier identifier | Parses and append message to the text edit. |
def entry_path(cls, project, location, entry_group, entry):
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}",
project=project,
location=location,
entry_group=entry_group,
entry=entry,
) | module function_definition identifier parameters identifier identifier identifier identifier identifier block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Return a fully-qualified entry string. |
def sarea_(self, col, x=None, y=None, rsum=None, rmean=None):
try:
charts = self._multiseries(col, x, y, "area", rsum, rmean)
return hv.Area.stack(charts)
except Exception as e:
self.err(e, self.sarea_, "Can not draw stacked area chart") | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier string string_start string_content string_end identifier identifier return_statement call attribute attribute identifier identifier identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier string string_start string_content string_end | Get an stacked area chart |
def placeholders(cls,dic):
keys = [str(x) for x in dic]
entete = ",".join(keys)
placeholders = ",".join(cls.named_style.format(x) for x in keys)
entete = f"({entete})"
placeholders = f"({placeholders})"
return entete, placeholders | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list_comprehension call identifier argument_list identifier for_in_clause identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier generator_expression call attribute attribute identifier identifier identifier argument_list identifier for_in_clause identifier identifier expression_statement assignment identifier string string_start string_content interpolation identifier string_content string_end expression_statement assignment identifier string string_start string_content interpolation identifier string_content string_end return_statement expression_list identifier identifier | Placeholders for fields names and value binds |
def jsonify(*args, **kwargs):
return Response(
json.dumps(
dict(
*args,
**kwargs),
cls=MongoJSONEncoder),
mimetype='application/json') | module function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement call identifier argument_list call attribute identifier identifier argument_list call identifier argument_list list_splat identifier dictionary_splat identifier keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end | jsonify with support for MongoDB ObjectId |
def convert_bytes(bytes):
bytes = float(bytes)
if bytes >= 1099511627776:
terabytes = bytes / 1099511627776
size = '%.2fT' % terabytes
elif bytes >= 1073741824:
gigabytes = bytes / 1073741824
size = '%.2fG' % gigabytes
elif bytes >= 1048576:
megabytes = bytes / 1048576
size = '%.2fM' % megabytes
elif bytes >= 1024:
kilobytes = bytes / 1024
size = '%.2fK' % kilobytes
else:
size = '%.2fb' % bytes
return size | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier binary_operator string string_start string_content string_end identifier elif_clause comparison_operator identifier integer block expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier binary_operator string string_start string_content string_end identifier elif_clause comparison_operator identifier integer block expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier binary_operator string string_start string_content string_end identifier elif_clause comparison_operator identifier integer block expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier binary_operator string string_start string_content string_end identifier else_clause block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier return_statement identifier | Convert bytes into human readable |
def slugify(s, delimiter='-'):
s = unicodedata.normalize('NFKD', to_unicode(s)).encode('ascii', 'ignore').decode('ascii')
return RE_SLUG.sub(delimiter, s).strip(delimiter).lower() | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call attribute call attribute call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier argument_list string string_start string_content string_end return_statement call attribute call attribute call attribute identifier identifier argument_list identifier identifier identifier argument_list identifier identifier argument_list | Normalize `s` into ASCII and replace non-word characters with `delimiter`. |
def signed_tree_multiplier(A, B, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone):
if len(A) == 1 or len(B) == 1:
raise pyrtl.PyrtlError("sign bit required, one or both wires too small")
aneg, bneg = A[-1], B[-1]
a = _twos_comp_conditional(A, aneg)
b = _twos_comp_conditional(B, bneg)
res = tree_multiplier(a[:-1], b[:-1]).zero_extended(len(A) + len(B))
return _twos_comp_conditional(res, aneg ^ bneg) | module function_definition identifier parameters identifier identifier default_parameter identifier attribute identifier identifier default_parameter identifier attribute identifier identifier block if_statement boolean_operator comparison_operator call identifier argument_list identifier integer comparison_operator call identifier argument_list identifier integer block raise_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment pattern_list identifier identifier expression_list subscript identifier unary_operator integer subscript identifier unary_operator integer expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call attribute call identifier argument_list subscript identifier slice unary_operator integer subscript identifier slice unary_operator integer identifier argument_list binary_operator call identifier argument_list identifier call identifier argument_list identifier return_statement call identifier argument_list identifier binary_operator identifier identifier | Same as tree_multiplier, but uses two's-complement signed integers |
def RegisterProtoDescriptors(db, *additional_descriptors):
db.RegisterFileDescriptor(artifact_pb2.DESCRIPTOR)
db.RegisterFileDescriptor(client_pb2.DESCRIPTOR)
db.RegisterFileDescriptor(config_pb2.DESCRIPTOR)
db.RegisterFileDescriptor(cron_pb2.DESCRIPTOR)
db.RegisterFileDescriptor(flow_pb2.DESCRIPTOR)
db.RegisterFileDescriptor(hunt_pb2.DESCRIPTOR)
db.RegisterFileDescriptor(output_plugin_pb2.DESCRIPTOR)
db.RegisterFileDescriptor(reflection_pb2.DESCRIPTOR)
db.RegisterFileDescriptor(stats_pb2.DESCRIPTOR)
db.RegisterFileDescriptor(user_pb2.DESCRIPTOR)
db.RegisterFileDescriptor(vfs_pb2.DESCRIPTOR)
db.RegisterFileDescriptor(checks_pb2.DESCRIPTOR)
db.RegisterFileDescriptor(deprecated_pb2.DESCRIPTOR)
db.RegisterFileDescriptor(flows_pb2.DESCRIPTOR)
db.RegisterFileDescriptor(jobs_pb2.DESCRIPTOR)
db.RegisterFileDescriptor(osquery_pb2.DESCRIPTOR)
db.RegisterFileDescriptor(wrappers_pb2.DESCRIPTOR)
for d in additional_descriptors:
db.RegisterFileDescriptor(d) | module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier | Registers all API-releated descriptors in a given symbol DB. |
def _parse_ftp_time(cls, time_text):
try:
tm_year = int(time_text[0:4])
tm_month = int(time_text[4:6])
tm_day = int(time_text[6:8])
tm_hour = int(time_text[8:10])
tm_min = int(time_text[10:12])
tm_sec = int(time_text[12:14])
except ValueError:
return None
epoch_time = calendar.timegm(
(tm_year, tm_month, tm_day, tm_hour, tm_min, tm_sec)
)
return epoch_time | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list subscript identifier slice integer integer expression_statement assignment identifier call identifier argument_list subscript identifier slice integer integer expression_statement assignment identifier call identifier argument_list subscript identifier slice integer integer expression_statement assignment identifier call identifier argument_list subscript identifier slice integer integer expression_statement assignment identifier call identifier argument_list subscript identifier slice integer integer expression_statement assignment identifier call identifier argument_list subscript identifier slice integer integer except_clause identifier block return_statement none expression_statement assignment identifier call attribute identifier identifier argument_list tuple identifier identifier identifier identifier identifier identifier return_statement identifier | Parse a time from an ftp directory listing. |
def _construct_bower_command(bower_command):
if not bower_command:
raise CommandExecutionError(
'bower_command, e.g. install, must be specified')
cmd = ['bower'] + shlex.split(bower_command)
cmd.extend(['--config.analytics', 'false',
'--config.interactive', 'false',
'--allow-root', '--json'])
return cmd | module function_definition identifier parameters identifier block if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier binary_operator list string string_start string_content string_end call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end return_statement identifier | Create bower command line string |
def preview_from_config(name, url, backend,
description=None,
frequency=DEFAULT_HARVEST_FREQUENCY,
owner=None,
organization=None,
config=None,
):
if owner and not isinstance(owner, User):
owner = User.get(owner)
if organization and not isinstance(organization, Organization):
organization = Organization.get(organization)
source = HarvestSource(
name=name,
url=url,
backend=backend,
description=description,
frequency=frequency or DEFAULT_HARVEST_FREQUENCY,
owner=owner,
organization=organization,
config=config,
)
cls = backends.get(current_app, source.backend)
max_items = current_app.config['HARVEST_PREVIEW_MAX_ITEMS']
backend = cls(source, dryrun=True, max_items=max_items)
return backend.harvest() | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block if_statement boolean_operator identifier not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement boolean_operator identifier not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier boolean_operator identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier true keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list | Preview an harvesting from a source created with the given parameters |
def _check_inputs(z, m):
try:
nz = len(z)
z = np.array(z)
except TypeError:
z = np.array([z])
nz = len(z)
try:
nm = len(m)
m = np.array(m)
except TypeError:
m = np.array([m])
nm = len(m)
if (z < 0).any() or (m < 0).any():
raise ValueError('z and m must be positive')
if nz != nm and nz > 1 and nm > 1:
raise ValueError('z and m arrays must be either equal in length, \
OR of different length with one of length 1.')
else:
if type(z) != np.ndarray:
z = np.array(z)
if type(m) != np.ndarray:
m = np.array(m)
return z, m | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause identifier block expression_statement assignment identifier call attribute identifier identifier argument_list list identifier expression_statement assignment identifier call identifier argument_list identifier try_statement block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause identifier block expression_statement assignment identifier call attribute identifier identifier argument_list list identifier expression_statement assignment identifier call identifier argument_list identifier if_statement boolean_operator call attribute parenthesized_expression comparison_operator identifier integer identifier argument_list call attribute parenthesized_expression comparison_operator identifier integer identifier argument_list block raise_statement call identifier argument_list string string_start string_content string_end if_statement boolean_operator boolean_operator comparison_operator identifier identifier comparison_operator identifier integer comparison_operator identifier integer block raise_statement call identifier argument_list string string_start string_content escape_sequence string_end else_clause block if_statement comparison_operator call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement expression_list identifier identifier | Check inputs are arrays of same length or array and a scalar. |
def login(provider_id):
provider = get_provider_or_404(provider_id)
callback_url = get_authorize_callback('login', provider_id)
post_login = request.form.get('next', get_post_login_redirect())
session[config_value('POST_OAUTH_LOGIN_SESSION_KEY')] = post_login
return provider.authorize(callback_url) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call identifier argument_list expression_statement assignment subscript identifier call identifier argument_list string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list identifier | Starts the provider login OAuth flow |
def connect_params_async(self):
kwargs = self.connect_params.copy()
kwargs.update({
'minsize': self.min_connections,
'maxsize': self.max_connections,
'autocommit': True,
})
return kwargs | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end true return_statement identifier | Connection parameters for `aiomysql.Connection` |
def serve(config):
"Serve the app with Gevent"
from gevent.pywsgi import WSGIServer
app = make_app(config=config)
host = app.config.get("HOST", '127.0.0.1')
port = app.config.get("PORT", 5000)
http_server = WSGIServer((host, port), app)
http_server.serve_forever() | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier call identifier argument_list tuple identifier identifier identifier expression_statement call attribute identifier identifier argument_list | Serve the app with Gevent |
def log_with_color(level):
def wrapper(text):
color = log_colors_config[level.upper()]
getattr(logger, level.lower())(coloring(text, color))
return wrapper | module function_definition identifier parameters identifier block function_definition identifier parameters identifier block expression_statement assignment identifier subscript identifier call attribute identifier identifier argument_list expression_statement call call identifier argument_list identifier call attribute identifier identifier argument_list argument_list call identifier argument_list identifier identifier return_statement identifier | log with color by different level |
def entities(self):
r = fapi.get_entities_with_type(self.namespace,
self.name, self.api_url)
fapi._check_response_code(r, 200)
edicts = r.json()
return [Entity(e['entityType'], e['name'], e['attributes'])
for e in edicts] | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list return_statement list_comprehension call identifier argument_list 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 for_in_clause identifier identifier | List all entities in workspace. |
def router_del(self, cluster_id, router_id):
cluster = self._storage[cluster_id]
result = cluster.router_remove(router_id)
self._storage[cluster_id] = cluster
return result | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript attribute identifier identifier identifier identifier return_statement identifier | remove router from the ShardedCluster |
def pipe(cmd, txt):
return Popen(
cmd2args(cmd),
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
shell=win32
).communicate(txt)[0] | module function_definition identifier parameters identifier identifier block return_statement subscript call attribute call identifier argument_list call identifier argument_list identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier identifier argument_list identifier integer | Pipe `txt` into the command `cmd` and return the output. |
def tryload_cache_list(dpath, fname, cfgstr_list, verbose=False):
data_list = [tryload_cache(dpath, fname, cfgstr, verbose) for cfgstr in cfgstr_list]
ismiss_list = [data is None for data in data_list]
return data_list, ismiss_list | module function_definition identifier parameters identifier identifier identifier default_parameter identifier false block expression_statement assignment identifier list_comprehension call identifier argument_list identifier identifier identifier identifier for_in_clause identifier identifier expression_statement assignment identifier list_comprehension comparison_operator identifier none for_in_clause identifier identifier return_statement expression_list identifier identifier | loads a list of similar cached datas. Returns flags that needs to be computed |
def start(self, interval, now=True):
if interval < 0:
raise ValueError('interval must be >= 0')
if self._running:
self.stop()
self._running = True
self._interval = interval
if now:
self._self_thread = hub.spawn_after(0, self)
else:
self._self_thread = hub.spawn_after(self._interval, self) | module function_definition identifier parameters identifier identifier default_parameter identifier true block if_statement comparison_operator identifier integer block raise_statement call identifier argument_list string string_start string_content string_end if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier true expression_statement assignment attribute identifier identifier identifier if_statement identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list integer identifier else_clause block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier identifier | Start running pre-set function every interval seconds. |
def lnlike(x, star):
ll = lnprior(x)
if np.isinf(ll):
return ll, (np.nan, np.nan)
per, t0, b = x
model = TransitModel('b', per=per, t0=t0, b=b, rhos=10.)(star.time)
like, d, vard = star.lnlike(model, full_output=True)
ll += like
return ll, (d,) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement call attribute identifier identifier argument_list identifier block return_statement expression_list identifier tuple attribute identifier identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier identifier identifier expression_statement assignment identifier call call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier float argument_list attribute identifier identifier expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true expression_statement augmented_assignment identifier identifier return_statement expression_list identifier tuple identifier | Return the log likelihood given parameter vector `x`. |
def increment_bucket_count(self, value):
if len(self._bounds) == 0:
self._counts_per_bucket[0] += 1
return 0
for ii, bb in enumerate(self._bounds):
if value < bb:
self._counts_per_bucket[ii] += 1
return ii
else:
last_bucket_index = len(self._bounds)
self._counts_per_bucket[last_bucket_index] += 1
return last_bucket_index | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement augmented_assignment subscript attribute identifier identifier integer integer return_statement integer for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block if_statement comparison_operator identifier identifier block expression_statement augmented_assignment subscript attribute identifier identifier identifier integer return_statement identifier else_clause block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement augmented_assignment subscript attribute identifier identifier identifier integer return_statement identifier | Increment the bucket count based on a given value from the user |
def border(self, L):
if self.shape == L_shape:
L.append(self.value)
else:
for x in self.sons:
x.border(L) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier else_clause block for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier | Append to L the border of the subtree. |
def assert_lt(left, right, message=None, extra=None):
assert left < right, _assert_fail_message(message, left, right, ">=", extra) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block assert_statement comparison_operator identifier identifier call identifier argument_list identifier identifier identifier string string_start string_content string_end identifier | Raises an AssertionError if left_hand >= right_hand. |
def update_user_password(new_pwd_user_id, new_password,**kwargs):
try:
user_i = db.DBSession.query(User).filter(User.id==new_pwd_user_id).one()
user_i.password = bcrypt.hashpw(str(new_password).encode('utf-8'), bcrypt.gensalt())
return user_i
except NoResultFound:
raise ResourceNotFoundError("User (id=%s) not found"%(new_pwd_user_id)) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block try_statement block expression_statement assignment identifier call attribute call attribute call attribute attribute identifier identifier identifier argument_list identifier identifier argument_list comparison_operator attribute identifier identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list call attribute call identifier argument_list identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list return_statement identifier except_clause identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression identifier | Update a user's password |
def detect_fastq_annotations(fastq_file):
annotations = set()
queryread = tz.first(read_fastq(fastq_file))
for k, v in BARCODEINFO.items():
if v.readprefix in queryread:
annotations.add(k)
return annotations | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | detects annotations preesent in a FASTQ file by examining the first read |
def _setup(self):
self._populate_local()
try:
self._populate_latest()
except Exception as e:
self.log.exception('Unable to retrieve latest %s version information', self.meta_name)
self._sort() | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list try_statement block expression_statement call attribute identifier identifier argument_list except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list | Run setup tasks after initialization |
def delete_by_query(self, indices, doc_types, query, **query_params):
path = self._make_path(indices, doc_types, '_query')
body = {"query": query.serialize()}
return self._send_request('DELETE', path, body, query_params) | module function_definition identifier parameters identifier identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier identifier | Delete documents from one or more indices and one or more types based on a query. |
def AddTrainingOperators(model, softmax, label):
xent = model.LabelCrossEntropy([softmax, label], 'xent')
loss = model.AveragedLoss(xent, "loss")
AddAccuracy(model, softmax, label)
model.AddGradientOperators([loss])
ITER = brew.iter(model, "iter")
LR = model.LearningRate(
ITER, "LR", base_lr=-0.1, policy="step", stepsize=1, gamma=0.999)
ONE = model.param_init_net.ConstantFill([], "ONE", shape=[1], value=1.0)
for param in model.params:
param_grad = model.param_to_grad[param]
model.WeightedSum([param, ONE, param_grad, LR], param) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list list identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement call identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end keyword_argument identifier unary_operator float keyword_argument identifier string string_start string_content string_end keyword_argument identifier integer keyword_argument identifier float expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list list string string_start string_content string_end keyword_argument identifier list integer keyword_argument identifier float for_statement identifier attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list list identifier identifier identifier identifier identifier | Adds training operators to the model. |
def basic_search(self, pattern):
lookup = None
for pattern in pattern.split():
query_part = models.Q()
for field in SEARCH_FIELDS:
query_part |= models.Q(**{'%s__icontains' % field: pattern})
if lookup is None:
lookup = query_part
else:
lookup |= query_part
return self.get_queryset().filter(lookup) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier none for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier identifier block expression_statement augmented_assignment identifier call attribute identifier identifier argument_list dictionary_splat dictionary pair binary_operator string string_start string_content string_end identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier identifier else_clause block expression_statement augmented_assignment identifier identifier return_statement call attribute call attribute identifier identifier argument_list identifier argument_list identifier | Basic search on entries. |
def removeNullPadding(str, blocksize=AES_blocksize):
'Remove padding with null bytes'
pad_len = 0
for char in str[::-1]:
if char == '\0':
pad_len += 1
else:
break
str = str[:-pad_len]
return str | module function_definition identifier parameters identifier default_parameter identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier integer for_statement identifier subscript identifier slice unary_operator integer block if_statement comparison_operator identifier string string_start string_content escape_sequence string_end block expression_statement augmented_assignment identifier integer else_clause block break_statement expression_statement assignment identifier subscript identifier slice unary_operator identifier return_statement identifier | Remove padding with null bytes |
def _check_items_limit(self):
if self.items_limit and self.items_limit == self.get_metadata('items_count'):
raise ItemsLimitReached('Finishing job after items_limit reached:'
' {} items written.'.format(self.get_metadata('items_count'))) | module function_definition identifier parameters identifier block if_statement boolean_operator attribute identifier identifier comparison_operator attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end | Raise ItemsLimitReached if the writer reached the configured items limit. |
def print_options(self):
summary = []
for opt_name, opt in self.options.items():
if opt.hidden:
continue
summary.append(opt.summary())
print("\n".join(summary)) | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement attribute identifier identifier block continue_statement expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier | print description of the component options |
def append_result(self, results, num_matches):
filename, lineno, colno, match_end, line = results
if filename not in self.files:
file_item = FileMatchItem(self, filename, self.sorting,
self.text_color)
file_item.setExpanded(True)
self.files[filename] = file_item
self.num_files += 1
search_text = self.search_text
title = "'%s' - " % search_text
nb_files = self.num_files
if nb_files == 0:
text = _('String not found')
else:
text_matches = _('matches in')
text_files = _('file')
if nb_files > 1:
text_files += 's'
text = "%d %s %d %s" % (num_matches, text_matches,
nb_files, text_files)
self.set_title(title + text)
file_item = self.files[filename]
line = self.truncate_result(line, colno, match_end)
item = LineMatchItem(file_item, lineno, colno, line, self.text_color)
self.data[id(item)] = (filename, lineno, colno) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier identifier identifier identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list true expression_statement assignment subscript attribute identifier identifier identifier identifier expression_statement augmented_assignment attribute identifier identifier integer expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier binary_operator string string_start string_content string_end identifier expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier integer block expression_statement augmented_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 identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator identifier identifier expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier attribute identifier identifier expression_statement assignment subscript attribute identifier identifier call identifier argument_list identifier tuple identifier identifier identifier | Real-time update of search results |
def Attach(self, pid):
if self.inferior.is_running:
answer = raw_input('Already attached to process ' +
str(self.inferior.pid) +
'. Detach? [y]/n ')
if answer and answer != 'y' and answer != 'yes':
return None
self.Detach()
for plugin in self.plugins:
plugin.position = None
self.inferior.Reinit(pid) | module function_definition identifier parameters identifier identifier block if_statement attribute attribute identifier identifier identifier block expression_statement assignment identifier call identifier argument_list binary_operator binary_operator string string_start string_content string_end call identifier argument_list attribute attribute identifier identifier identifier string string_start string_content string_end if_statement boolean_operator boolean_operator identifier comparison_operator identifier string string_start string_content string_end comparison_operator identifier string string_start string_content string_end block return_statement none expression_statement call attribute identifier identifier argument_list for_statement identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier none expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Attach to the process with the given pid. |
def euler_tour_dfs(G, source=None):
if source is None:
nodes = G
else:
nodes = [source]
yielder = []
visited = set()
for start in nodes:
if start in visited:
continue
visited.add(start)
stack = [(start, iter(G[start]))]
while stack:
parent, children = stack[-1]
try:
child = next(children)
if child not in visited:
yielder += [parent]
visited.add(child)
stack.append((child, iter(G[child])))
except StopIteration:
if stack:
last = stack[-1]
yielder += [last[0]]
stack.pop()
return yielder | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier list identifier expression_statement assignment identifier list expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block if_statement comparison_operator identifier identifier block continue_statement expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier list tuple identifier call identifier argument_list subscript identifier identifier while_statement identifier block expression_statement assignment pattern_list identifier identifier subscript identifier unary_operator integer try_statement block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier identifier block expression_statement augmented_assignment identifier list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list tuple identifier call identifier argument_list subscript identifier identifier except_clause identifier block if_statement identifier block expression_statement assignment identifier subscript identifier unary_operator integer expression_statement augmented_assignment identifier list subscript identifier integer expression_statement call attribute identifier identifier argument_list return_statement identifier | adaptation of networkx dfs |
def csv_array_clean_format(csv_data, c_headers=None, r_headers=None):
result = []
real_num_header = len(force_list(r_headers[0])) if r_headers else 0
result.append([""] * real_num_header + c_headers)
for k_index in range(0, len(csv_data)):
if r_headers:
result.append(
list(
itertools.chain(
[r_headers[k_index]],
csv_data[k_index])))
else:
result.append(csv_data[k_index])
return result | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier list expression_statement assignment identifier conditional_expression call identifier argument_list call identifier argument_list subscript identifier integer identifier integer expression_statement call attribute identifier identifier argument_list binary_operator binary_operator list string string_start string_end identifier identifier for_statement identifier call identifier argument_list integer call identifier argument_list identifier block if_statement identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list call attribute identifier identifier argument_list list subscript identifier identifier subscript identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list subscript identifier identifier return_statement identifier | Format csv rows parsed to Array clean format. |
def _debugGraph(self):
print("Len of graph: ", len(self.rdflib_graph))
for x, y, z in self.rdflib_graph:
print(x, y, z) | module function_definition identifier parameters identifier block expression_statement call identifier argument_list string string_start string_content string_end call identifier argument_list attribute identifier identifier for_statement pattern_list identifier identifier identifier attribute identifier identifier block expression_statement call identifier argument_list identifier identifier identifier | internal util to print out contents of graph |
def getline(self):
if self.index >= len(self.lines):
line = ''
else:
line = self.lines[self.index]
self.index += 1
return line | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier call identifier argument_list attribute identifier identifier block expression_statement assignment identifier string string_start string_end else_clause block expression_statement assignment identifier subscript attribute identifier identifier attribute identifier identifier expression_statement augmented_assignment attribute identifier identifier integer return_statement identifier | Line-getter for tokenize. |
def load_manifest(app, filename='manifest.json'):
if os.path.isabs(filename):
path = filename
else:
path = pkg_resources.resource_filename(app, filename)
with io.open(path, mode='r', encoding='utf8') as stream:
data = json.load(stream)
_registered_manifests[app] = path
return data | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier identifier identifier return_statement identifier | Load an assets json manifest |
def setup_gui_analysis_done(self):
self.progress_bar.hide()
self.lblAnalysisStatus.setText(tr('Analysis done.'))
self.pbnReportWeb.show()
self.pbnReportPDF.show()
self.pbnReportPDF.clicked.connect(self.print_map) | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier | Helper method to setup gui if analysis is done. |
def _get_tool_str(self, tool):
res = tool['file']
try:
res += '.' + tool['function']
except Exception as ex:
print('Warning - no function defined for tool ' + str(tool))
res += '\n'
return res | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end try_statement block expression_statement augmented_assignment identifier binary_operator string string_start string_content string_end subscript identifier string string_start string_content string_end except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end return_statement identifier | get a string representation of the tool |
def format(self, record):
formatted_record = super(ExcInfoOnLogLevelFormatMixIn, self).format(record)
exc_info_on_loglevel = getattr(record, 'exc_info_on_loglevel', None)
exc_info_on_loglevel_formatted = getattr(record, 'exc_info_on_loglevel_formatted', None)
if exc_info_on_loglevel is None and exc_info_on_loglevel_formatted is None:
return formatted_record
if self.level > exc_info_on_loglevel:
return formatted_record
if not record.exc_info_on_loglevel_instance and not exc_info_on_loglevel_formatted:
return formatted_record
if record.exc_info_on_loglevel_formatted is None:
if self.formatter is None:
self.formatter = logging._defaultFormatter
record.exc_info_on_loglevel_formatted = self.formatter.formatException(
record.exc_info_on_loglevel_instance
)
if formatted_record[-1:] != '\n':
formatted_record += '\n'
try:
formatted_record += record.exc_info_on_loglevel_formatted
except UnicodeError:
formatted_record += record.exc_info_on_loglevel_formatted.decode(sys.getfilesystemencoding(),
'replace')
record.exc_info_on_loglevel_instance = None
return formatted_record | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end none expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end none if_statement boolean_operator comparison_operator identifier none comparison_operator identifier none block return_statement identifier if_statement comparison_operator attribute identifier identifier identifier block return_statement identifier if_statement boolean_operator not_operator attribute identifier identifier not_operator identifier block return_statement identifier if_statement comparison_operator attribute identifier identifier none block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier if_statement comparison_operator subscript identifier slice unary_operator integer string string_start string_content escape_sequence string_end block expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end try_statement block expression_statement augmented_assignment identifier attribute identifier identifier except_clause identifier block expression_statement augmented_assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier none return_statement identifier | Format the log record to include exc_info if the handler is enabled for a specific log level |
def visit(self, node):
if isinstance(node, Placeholder):
return self.placeholders[node.id]
else:
return super(PlaceholderReplace, self).visit(node) | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block return_statement subscript attribute identifier identifier attribute identifier identifier else_clause block return_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier | Replace the placeholder if it is one or continue. |
def intersection(self, *others, **kwargs):
return self._combine_variant_collections(
combine_fn=set.intersection,
variant_collections=(self,) + others,
kwargs=kwargs) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier binary_operator tuple identifier identifier keyword_argument identifier identifier | Returns the intersection of variants in several VariantCollection objects. |
def ncVarAttributes(ncVar):
try:
return ncVar.__dict__
except Exception as ex:
logger.warn("Unable to read the attributes from {}. Reason: {}"
.format(ncVar.name, ex))
return {} | module function_definition identifier parameters identifier block try_statement block return_statement attribute identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier identifier return_statement dictionary | Returns the attributes of ncdf variable |
def _match(self):
optimized_rows = None
optimized_columns = None
for match in self.__match_rows(optimized_rows):
yield match
for match in self.__match_rows(optimized_columns,
transpose=True):
yield match | module function_definition identifier parameters identifier block expression_statement assignment identifier none expression_statement assignment identifier none for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement yield identifier for_statement identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true block expression_statement yield identifier | Find all matches and generate a position group for each match. |
def should_exclude(type_or_instance, exclusion_list):
if type_or_instance in exclusion_list:
return True
if type(type_or_instance) in exclusion_list:
return True
try:
if type_or_instance.__class__ in exclusion_list:
return True
except:
pass
return False | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier identifier block return_statement true if_statement comparison_operator call identifier argument_list identifier identifier block return_statement true try_statement block if_statement comparison_operator attribute identifier identifier identifier block return_statement true except_clause block pass_statement return_statement false | Tests whether an object should be simply returned when being wrapped |
def put(self, data, request, id):
if not id:
raise errors.MethodNotAllowed()
userdata = self._dict_to_model(data)
userdata.pk = id
try:
userdata.save(force_update=True)
except DatabaseError:
raise errors.NotFound() | module function_definition identifier parameters identifier identifier identifier identifier block if_statement not_operator identifier block raise_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list keyword_argument identifier true except_clause identifier block raise_statement call attribute identifier identifier argument_list | Update a single user. |
def compile_pillar(self):
load = {'id': self.minion_id,
'grains': self.grains,
'saltenv': self.opts['saltenv'],
'pillarenv': self.opts['pillarenv'],
'pillar_override': self.pillar_override,
'extra_minion_data': self.extra_minion_data,
'ver': '2',
'cmd': '_pillar'}
if self.ext:
load['ext'] = self.ext
try:
ret_pillar = yield self.channel.crypted_transfer_decode_dictentry(
load,
dictkey='pillar',
)
except Exception:
log.exception('Exception getting pillar:')
raise SaltClientError('Exception getting pillar.')
if not isinstance(ret_pillar, dict):
msg = ('Got a bad pillar from master, type {0}, expecting dict: '
'{1}').format(type(ret_pillar).__name__, ret_pillar)
log.error(msg)
raise SaltClientError(msg)
raise tornado.gen.Return(ret_pillar) | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end pair string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end if_statement attribute identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier try_statement block expression_statement assignment identifier yield call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end raise_statement call identifier argument_list string string_start string_content string_end if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list attribute call identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier raise_statement call identifier argument_list identifier raise_statement call attribute attribute identifier identifier identifier argument_list identifier | Return a future which will contain the pillar data from the master |
def tokey(*args):
salt = '||'.join([force_text(arg) for arg in args])
hash_ = hashlib.md5(encode(salt))
return hash_.hexdigest() | module function_definition identifier parameters list_splat_pattern identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier return_statement call attribute identifier identifier argument_list | Computes a unique key from arguments given. |
def _handle_results(options):
results_processor = options.get('_process_results')
if not results_processor:
results_processor = _process_results
processor_result = results_processor()
if isinstance(processor_result, (Async, Context)):
processor_result.start() | 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 expression_statement assignment identifier identifier expression_statement assignment identifier call identifier argument_list if_statement call identifier argument_list identifier tuple identifier identifier block expression_statement call attribute identifier identifier argument_list | Process the results of executing the Async's target. |
def start_address(self):
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.START_ADDRESS) | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end return_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier | Return the start address attribute of the BFD file being processed. |
def extract_lzh (archive, compression, cmd, verbosity, interactive, outdir):
opts = 'x'
if verbosity > 1:
opts += 'v'
opts += "w=%s" % outdir
return [cmd, opts, archive] | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier string string_start string_content string_end if_statement comparison_operator identifier integer block expression_statement augmented_assignment identifier string string_start string_content string_end expression_statement augmented_assignment identifier binary_operator string string_start string_content string_end identifier return_statement list identifier identifier identifier | Extract a LZH archive. |
def _req_directory(self, cid):
res = self._req_files(cid=cid, offset=0, limit=1, show_dir=1)
path = res['path']
count = res['count']
for d in path:
if str(d['cid']) == str(cid):
res = {
'cid': d['cid'],
'name': d['name'],
'pid': d['pid'],
'count': count,
}
return res
else:
raise RequestFailure('No directory found.') | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier integer keyword_argument identifier integer keyword_argument identifier integer expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end for_statement identifier identifier block if_statement comparison_operator call identifier argument_list subscript identifier string string_start string_content string_end call identifier argument_list identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end identifier return_statement identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end | Return name and pid of by cid |
def refuse_transfer(transfer, comment=None):
TransferResponsePermission(transfer).test()
transfer.responded = datetime.now()
transfer.responder = current_user._get_current_object()
transfer.status = 'refused'
transfer.response_comment = comment
transfer.save()
return transfer | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement call attribute call identifier argument_list identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list return_statement identifier | Refuse an incoming a transfer request |
def load_unixtime(buf, pos):
secs, pos = load_le32(buf, pos)
dt = datetime.fromtimestamp(secs, UTC)
return dt, pos | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier return_statement expression_list identifier identifier | Load LE32 unix timestamp |
def createTable(dbconn, pd):
cols = ('%s %s' % (defn.name, getTypename(defn)) for defn in pd.fields)
sql = 'CREATE TABLE IF NOT EXISTS %s (%s)' % (pd.name, ', '.join(cols))
dbconn.execute(sql)
dbconn.commit() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier generator_expression binary_operator string string_start string_content string_end tuple attribute identifier identifier call identifier argument_list identifier for_in_clause identifier attribute identifier identifier expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | Creates a database table for the given PacketDefinition. |
def previous_track(self):
if self._input_func in self._netaudio_func_list:
body = {"cmd0": "PutNetAudioCommand/CurUp",
"cmd1": "aspMainZone_WebUpdateStatus/",
"ZoneName": "MAIN ZONE"}
try:
return bool(self.send_post_command(
self._urls.command_netaudio_post, body))
except requests.exceptions.RequestException:
_LOGGER.error(
"Connection error: previous track command not sent.")
return False | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end try_statement block return_statement call identifier argument_list call attribute identifier identifier argument_list attribute attribute identifier identifier identifier identifier except_clause attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement false | Send previous track command to receiver command via HTTP post. |
def convert_to_record(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
result = func(self, *args, **kwargs)
if result is not None:
if isinstance(result, dict):
return _record(result)
return (_record(i) for i in result)
return result
return wrapper | module function_definition identifier parameters identifier block decorated_definition decorator call attribute identifier identifier argument_list identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier list_splat identifier dictionary_splat identifier if_statement comparison_operator identifier none block if_statement call identifier argument_list identifier identifier block return_statement call identifier argument_list identifier return_statement generator_expression call identifier argument_list identifier for_in_clause identifier identifier return_statement identifier return_statement identifier | Wrap mongodb record to a dict record with default value None |
def _bin(self, bin):
bin_path = (self._bin_dir / bin).with_suffix(".exe" if self._is_windows else "")
if not bin_path.exists():
return bin
return str(bin_path) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute parenthesized_expression binary_operator attribute identifier identifier identifier identifier argument_list conditional_expression string string_start string_content string_end attribute identifier identifier string string_start string_end if_statement not_operator call attribute identifier identifier argument_list block return_statement identifier return_statement call identifier argument_list identifier | Return path to the given executable. |
def import_mod(mod_name:str, ignore_errors=False):
"Return module from `mod_name`."
splits = str.split(mod_name, '.')
try:
if len(splits) > 1 : mod = importlib.import_module('.' + '.'.join(splits[1:]), splits[0])
else: mod = importlib.import_module(mod_name)
return mod
except:
if not ignore_errors: print(f"Module {mod_name} doesn't exist.") | module function_definition identifier parameters typed_parameter identifier type identifier default_parameter identifier false block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end try_statement block if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list subscript identifier slice integer subscript identifier integer else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier except_clause block if_statement not_operator identifier block expression_statement call identifier argument_list string string_start string_content interpolation identifier string_content string_end | Return module from `mod_name`. |
def manifest(self):
if not self._manifest:
with open(self.manifest_path) as man:
self._manifest = json.load(man)
return self._manifest | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier as_pattern_target identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier return_statement attribute identifier identifier | The manifest definition of the stencilset as a dict. |
def initial_step(self, phase, x, y):
self.x[0] = x
self.y[0] = y
self.phase[0] = phase
if self.MODE == CordicMode.ROTATION:
if phase > 0.5:
self.x[0] = -x
self.phase[0] = phase - 1.0
elif phase < -0.5:
self.x[0] = -x
self.phase[0] = phase + 1.0
elif self.MODE == CordicMode.VECTORING:
if x < 0.0 and y > 0.0:
self.x[0] = -x
self.y[0] = -y
self.phase[0] = 1.0
elif x < 0.0 and y < 0.0:
self.x[0] = -x
self.y[0] = -y
self.phase[0] = -1.0 | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment subscript attribute identifier identifier integer identifier expression_statement assignment subscript attribute identifier identifier integer identifier expression_statement assignment subscript attribute identifier identifier integer identifier if_statement comparison_operator attribute identifier identifier attribute identifier identifier block if_statement comparison_operator identifier float block expression_statement assignment subscript attribute identifier identifier integer unary_operator identifier expression_statement assignment subscript attribute identifier identifier integer binary_operator identifier float elif_clause comparison_operator identifier unary_operator float block expression_statement assignment subscript attribute identifier identifier integer unary_operator identifier expression_statement assignment subscript attribute identifier identifier integer binary_operator identifier float elif_clause comparison_operator attribute identifier identifier attribute identifier identifier block if_statement boolean_operator comparison_operator identifier float comparison_operator identifier float block expression_statement assignment subscript attribute identifier identifier integer unary_operator identifier expression_statement assignment subscript attribute identifier identifier integer unary_operator identifier expression_statement assignment subscript attribute identifier identifier integer float elif_clause boolean_operator comparison_operator identifier float comparison_operator identifier float block expression_statement assignment subscript attribute identifier identifier integer unary_operator identifier expression_statement assignment subscript attribute identifier identifier integer unary_operator identifier expression_statement assignment subscript attribute identifier identifier integer unary_operator float | Transform input to the CORDIC working quadrants |
def start(self, request, application, extra_roles=None):
roles = self._get_roles_for_request(request, application)
if extra_roles is not None:
roles.update(extra_roles)
if 'is_authorised' not in roles:
return HttpResponseForbidden('<h1>Access Denied</h1>')
return self._next(request, application, roles, self._first_state) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end identifier block return_statement call identifier argument_list string string_start string_content string_end return_statement call attribute identifier identifier argument_list identifier identifier identifier attribute identifier identifier | Continue the state machine at first state. |
def add_legends(self, xhists=True, yhists=False, scatter=True, **kwargs):
axs = []
if xhists:
axs.extend(self.hxs)
if yhists:
axs.extend(self.hys)
if scatter:
axs.extend(self.ax)
for ax in axs:
ax.legend(**kwargs) | module function_definition identifier parameters identifier default_parameter identifier true default_parameter identifier false default_parameter identifier true dictionary_splat_pattern identifier block expression_statement assignment identifier list if_statement identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list dictionary_splat identifier | Add legends to axes. |
def _put_bucket_tagging(self):
all_tags = self.s3props['tagging']['tags']
all_tags.update({'app_group': self.group, 'app_name': self.app_name})
tag_set = generate_s3_tags.generated_tag_data(all_tags)
tagging_config = {'TagSet': tag_set}
self.s3client.put_bucket_tagging(Bucket=self.bucket, Tagging=tagging_config)
LOG.info("Adding tagging %s for Bucket", tag_set) | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier | Add bucket tags to bucket. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.