nwo stringlengths 5 106 | sha stringlengths 40 40 | path stringlengths 4 174 | language stringclasses 1
value | identifier stringlengths 1 140 | parameters stringlengths 0 87.7k | argument_list stringclasses 1
value | return_statement stringlengths 0 426k | docstring stringlengths 0 64.3k | docstring_summary stringlengths 0 26.3k | docstring_tokens list | function stringlengths 18 4.83M | function_tokens list | url stringlengths 83 304 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mit-han-lab/lite-transformer | 1df8001c779deb85819fc30d70349cc334c408ba | fairseq/optim/fairseq_optimizer.py | python | FairseqOptimizer.clip_grad_norm | (self, max_norm) | Clips gradient norm. | Clips gradient norm. | [
"Clips",
"gradient",
"norm",
"."
] | def clip_grad_norm(self, max_norm):
"""Clips gradient norm."""
if max_norm > 0:
return torch.nn.utils.clip_grad_norm_(self.params, max_norm)
else:
return math.sqrt(sum(p.grad.data.norm()**2 for p in self.params if p.grad is not None)) | [
"def",
"clip_grad_norm",
"(",
"self",
",",
"max_norm",
")",
":",
"if",
"max_norm",
">",
"0",
":",
"return",
"torch",
".",
"nn",
".",
"utils",
".",
"clip_grad_norm_",
"(",
"self",
".",
"params",
",",
"max_norm",
")",
"else",
":",
"return",
"math",
".",
... | https://github.com/mit-han-lab/lite-transformer/blob/1df8001c779deb85819fc30d70349cc334c408ba/fairseq/optim/fairseq_optimizer.py#L89-L94 | ||
tensorflow/ranking | 94cccec8b4e71d2cc4489c61e2623522738c2924 | tensorflow_ranking/extension/examples/pipeline_example.py | python | example_feature_columns | () | return feature_columns | Returns the example feature columns. | Returns the example feature columns. | [
"Returns",
"the",
"example",
"feature",
"columns",
"."
] | def example_feature_columns():
"""Returns the example feature columns."""
if FLAGS.vocab_path:
sparse_column = tf.feature_column.categorical_column_with_vocabulary_file(
key="document_tokens", vocabulary_file=FLAGS.vocab_path)
else:
sparse_column = tf.feature_column.categorical_column_with_hash_bucket(
key="document_tokens", hash_bucket_size=100)
document_embedding_column = tf.feature_column.embedding_column(
sparse_column, _EMBEDDING_DIMENSION)
feature_columns = {"document_tokens": document_embedding_column}
return feature_columns | [
"def",
"example_feature_columns",
"(",
")",
":",
"if",
"FLAGS",
".",
"vocab_path",
":",
"sparse_column",
"=",
"tf",
".",
"feature_column",
".",
"categorical_column_with_vocabulary_file",
"(",
"key",
"=",
"\"document_tokens\"",
",",
"vocabulary_file",
"=",
"FLAGS",
"... | https://github.com/tensorflow/ranking/blob/94cccec8b4e71d2cc4489c61e2623522738c2924/tensorflow_ranking/extension/examples/pipeline_example.py#L109-L120 | |
khanhnamle1994/natural-language-processing | 01d450d5ac002b0156ef4cf93a07cb508c1bcdc5 | assignment1/.env/lib/python2.7/site-packages/IPython/lib/pretty.py | python | PrettyPrinter.text | (self, obj) | Add literal text to the output. | Add literal text to the output. | [
"Add",
"literal",
"text",
"to",
"the",
"output",
"."
] | def text(self, obj):
"""Add literal text to the output."""
width = len(obj)
if self.buffer:
text = self.buffer[-1]
if not isinstance(text, Text):
text = Text()
self.buffer.append(text)
text.add(obj, width)
self.buffer_width += width
self._break_outer_groups()
else:
self.output.write(obj)
self.output_width += width | [
"def",
"text",
"(",
"self",
",",
"obj",
")",
":",
"width",
"=",
"len",
"(",
"obj",
")",
"if",
"self",
".",
"buffer",
":",
"text",
"=",
"self",
".",
"buffer",
"[",
"-",
"1",
"]",
"if",
"not",
"isinstance",
"(",
"text",
",",
"Text",
")",
":",
"... | https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/IPython/lib/pretty.py#L260-L273 | ||
fake-name/ReadableWebProxy | ed5c7abe38706acc2684a1e6cd80242a03c5f010 | WebMirror/management/rss_parser_funcs/feed_parse_extractAirfalltranslationsWordpressCom.py | python | extractAirfalltranslationsWordpressCom | (item) | return False | Parser for 'airfalltranslations.wordpress.com' | Parser for 'airfalltranslations.wordpress.com' | [
"Parser",
"for",
"airfalltranslations",
".",
"wordpress",
".",
"com"
] | def extractAirfalltranslationsWordpressCom(item):
'''
Parser for 'airfalltranslations.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False | [
"def",
"extractAirfalltranslationsWordpressCom",
"(",
"item",
")",
":",
"vol",
",",
"chp",
",",
"frag",
",",
"postfix",
"=",
"extractVolChapterFragmentPostfix",
"(",
"item",
"[",
"'title'",
"]",
")",
"if",
"not",
"(",
"chp",
"or",
"vol",
")",
"or",
"\"previe... | https://github.com/fake-name/ReadableWebProxy/blob/ed5c7abe38706acc2684a1e6cd80242a03c5f010/WebMirror/management/rss_parser_funcs/feed_parse_extractAirfalltranslationsWordpressCom.py#L2-L21 | |
cslarsen/wpm | 6e48d8b750c7828166b67a532ff03d62584fb953 | wpm/stats.py | python | Stats.average | (self, tag=None, last_n=None) | return self.results(tag, last_n).averages()[0] | Returns the average WPM. | Returns the average WPM. | [
"Returns",
"the",
"average",
"WPM",
"."
] | def average(self, tag=None, last_n=None):
"""Returns the average WPM."""
return self.results(tag, last_n).averages()[0] | [
"def",
"average",
"(",
"self",
",",
"tag",
"=",
"None",
",",
"last_n",
"=",
"None",
")",
":",
"return",
"self",
".",
"results",
"(",
"tag",
",",
"last_n",
")",
".",
"averages",
"(",
")",
"[",
"0",
"]"
] | https://github.com/cslarsen/wpm/blob/6e48d8b750c7828166b67a532ff03d62584fb953/wpm/stats.py#L176-L178 | |
openhatch/oh-mainline | ce29352a034e1223141dcc2f317030bbc3359a51 | vendor/packages/zope.interface/src/zope/interface/interfaces.py | python | IAdapterRegistry.subscriptions | (required, provided, name=u'') | Get a sequence of subscribers
Subscribers for a *sequence* of required interfaces, and a provided
interface are returned. | Get a sequence of subscribers | [
"Get",
"a",
"sequence",
"of",
"subscribers"
] | def subscriptions(required, provided, name=u''):
"""Get a sequence of subscribers
Subscribers for a *sequence* of required interfaces, and a provided
interface are returned.
""" | [
"def",
"subscriptions",
"(",
"required",
",",
"provided",
",",
"name",
"=",
"u''",
")",
":"
] | https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/zope.interface/src/zope/interface/interfaces.py#L738-L743 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Lib/argparse.py | python | _ArgumentGroup._remove_action | (self, action) | [] | def _remove_action(self, action):
super(_ArgumentGroup, self)._remove_action(action)
self._group_actions.remove(action) | [
"def",
"_remove_action",
"(",
"self",
",",
"action",
")",
":",
"super",
"(",
"_ArgumentGroup",
",",
"self",
")",
".",
"_remove_action",
"(",
"action",
")",
"self",
".",
"_group_actions",
".",
"remove",
"(",
"action",
")"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/argparse.py#L1513-L1515 | ||||
andreikop/enki | 3170059e5cb46dcc77d7fb1457c38a8a5f13af66 | enki/core/queued_msg_tool_bar.py | python | _QueuedMessageWidget.setDefaultTimeout | (self, timeout) | [] | def setDefaultTimeout(self, timeout):
self._defaultTimeout = timeout | [
"def",
"setDefaultTimeout",
"(",
"self",
",",
"timeout",
")",
":",
"self",
".",
"_defaultTimeout",
"=",
"timeout"
] | https://github.com/andreikop/enki/blob/3170059e5cb46dcc77d7fb1457c38a8a5f13af66/enki/core/queued_msg_tool_bar.py#L123-L124 | ||||
chribsen/simple-machine-learning-examples | dc94e52a4cebdc8bb959ff88b81ff8cfeca25022 | venv/lib/python2.7/site-packages/sklearn/utils/linear_assignment_.py | python | _step1 | (state) | return _step3 | Steps 1 and 2 in the Wikipedia page. | Steps 1 and 2 in the Wikipedia page. | [
"Steps",
"1",
"and",
"2",
"in",
"the",
"Wikipedia",
"page",
"."
] | def _step1(state):
"""Steps 1 and 2 in the Wikipedia page."""
# Step1: For each row of the matrix, find the smallest element and
# subtract it from every element in its row.
state.C -= state.C.min(axis=1)[:, np.newaxis]
# Step2: Find a zero (Z) in the resulting matrix. If there is no
# starred zero in its row or column, star Z. Repeat for each element
# in the matrix.
for i, j in zip(*np.where(state.C == 0)):
if state.col_uncovered[j] and state.row_uncovered[i]:
state.marked[i, j] = 1
state.col_uncovered[j] = False
state.row_uncovered[i] = False
state._clear_covers()
return _step3 | [
"def",
"_step1",
"(",
"state",
")",
":",
"# Step1: For each row of the matrix, find the smallest element and",
"# subtract it from every element in its row.",
"state",
".",
"C",
"-=",
"state",
".",
"C",
".",
"min",
"(",
"axis",
"=",
"1",
")",
"[",
":",
",",
"np",
... | https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/sklearn/utils/linear_assignment_.py#L153-L169 | |
akanazawa/human_dynamics | 0887f37464c9a079ad7d69c8358cecd0f43c4f2a | src/evaluation/eval_util.py | python | compute_error_kp | (kps_gt, kps_pred, alpha=0.05, min_visible=6) | return errors_kp, errors_kp_pa, errors_kp_pck | Compute the keypoint error (mean difference in pixels), keypoint error after
Procrustes Analysis, and percent correct keypoints.
Args:
kps_gt (Nx25x3).
kps_pred (Nx25x2).
alpha (float).
min_visible (int): Min threshold for deciding visibility.
Returns:
errors_kp, errors_kp_pa, errors_kp_pck | Compute the keypoint error (mean difference in pixels), keypoint error after
Procrustes Analysis, and percent correct keypoints. | [
"Compute",
"the",
"keypoint",
"error",
"(",
"mean",
"difference",
"in",
"pixels",
")",
"keypoint",
"error",
"after",
"Procrustes",
"Analysis",
"and",
"percent",
"correct",
"keypoints",
"."
] | def compute_error_kp(kps_gt, kps_pred, alpha=0.05, min_visible=6):
"""
Compute the keypoint error (mean difference in pixels), keypoint error after
Procrustes Analysis, and percent correct keypoints.
Args:
kps_gt (Nx25x3).
kps_pred (Nx25x2).
alpha (float).
min_visible (int): Min threshold for deciding visibility.
Returns:
errors_kp, errors_kp_pa, errors_kp_pck
"""
assert len(kps_gt) == len(kps_pred)
errors_kp, errors_kp_pa, errors_kp_pck = [], [], []
for kp_gt, kp_pred in zip(kps_gt, kps_pred):
vis = kp_gt[:, 2].astype(bool)
kp_gt = kp_gt[:, :2]
if np.all(vis == 0) or np.sum(vis == 1) < min_visible:
# Use nan to signify not visible.
error_kp = np.nan
error_pa_pck = np.nan
error_kp_pa = np.nan
else:
kp_diffs = np.linalg.norm(kp_gt[vis] - kp_pred[vis], axis=1)
kp_pred_pa, _ = compute_opt_cam_with_vis(
got=kp_pred,
want=kp_gt,
vis=vis,
)
kp_diffs_pa = np.linalg.norm(kp_gt[vis] - kp_pred_pa[vis], axis=1)
error_kp = np.mean(kp_diffs)
error_pa_pck = np.mean(kp_diffs_pa < alpha)
error_kp_pa = np.mean(kp_diffs_pa)
errors_kp.append(error_kp)
errors_kp_pa.append(error_kp_pa)
errors_kp_pck.append(error_pa_pck)
return errors_kp, errors_kp_pa, errors_kp_pck | [
"def",
"compute_error_kp",
"(",
"kps_gt",
",",
"kps_pred",
",",
"alpha",
"=",
"0.05",
",",
"min_visible",
"=",
"6",
")",
":",
"assert",
"len",
"(",
"kps_gt",
")",
"==",
"len",
"(",
"kps_pred",
")",
"errors_kp",
",",
"errors_kp_pa",
",",
"errors_kp_pck",
... | https://github.com/akanazawa/human_dynamics/blob/0887f37464c9a079ad7d69c8358cecd0f43c4f2a/src/evaluation/eval_util.py#L97-L137 | |
Netflix/vmaf | e768a2be57116c76bf33be7f8ee3566d8b774664 | python/vmaf/core/feature_assembler.py | python | FeatureAssembler.run | (self) | Do all the calculation here.
:return: | Do all the calculation here.
:return: | [
"Do",
"all",
"the",
"calculation",
"here",
".",
":",
"return",
":"
] | def run(self):
"""
Do all the calculation here.
:return:
"""
# for each FeatureExtractor_type key in feature_dict, find the subclass
# of FeatureExtractor, run, and put results in a dict
for fextractor_type in self.feature_dict:
runner = self._get_fextractor_instance(fextractor_type)
runner.run(parallelize=self.parallelize, processes=self.processes)
results = runner.results
self.type2results_dict[fextractor_type] = results
# assemble an output dict with demanded atom features
# atom_features_dict = self.fextractor_atom_features_dict
result_dicts = list(map(lambda x: dict(), self.assets))
for fextractor_type in self.feature_dict:
assert fextractor_type in self.type2results_dict
for atom_feature in self._get_atom_features(fextractor_type):
scores_key = self._get_scores_key(fextractor_type, atom_feature)
for result_index, result in enumerate(self.type2results_dict[fextractor_type]):
try:
result_dicts[result_index][scores_key] = result[scores_key]
except KeyError:
scores_key_alt = BasicResult.scores_key_wildcard_match(result.result_dict, scores_key)
result_dicts[result_index][scores_key] = result[scores_key_alt]
self.results = list(map(
lambda tasset: BasicResult(tasset[0], tasset[1]),
zip(self.assets, result_dicts)
)) | [
"def",
"run",
"(",
"self",
")",
":",
"# for each FeatureExtractor_type key in feature_dict, find the subclass",
"# of FeatureExtractor, run, and put results in a dict",
"for",
"fextractor_type",
"in",
"self",
".",
"feature_dict",
":",
"runner",
"=",
"self",
".",
"_get_fextracto... | https://github.com/Netflix/vmaf/blob/e768a2be57116c76bf33be7f8ee3566d8b774664/python/vmaf/core/feature_assembler.py#L60-L91 | ||
jython/jython3 | def4f8ec47cb7a9c799ea4c745f12badf92c5769 | lib-python/3.5.1/telnetlib.py | python | Telnet.read_all | (self) | return buf | Read all data until EOF; block until connection closed. | Read all data until EOF; block until connection closed. | [
"Read",
"all",
"data",
"until",
"EOF",
";",
"block",
"until",
"connection",
"closed",
"."
] | def read_all(self):
"""Read all data until EOF; block until connection closed."""
self.process_rawq()
while not self.eof:
self.fill_rawq()
self.process_rawq()
buf = self.cookedq
self.cookedq = b''
return buf | [
"def",
"read_all",
"(",
"self",
")",
":",
"self",
".",
"process_rawq",
"(",
")",
"while",
"not",
"self",
".",
"eof",
":",
"self",
".",
"fill_rawq",
"(",
")",
"self",
".",
"process_rawq",
"(",
")",
"buf",
"=",
"self",
".",
"cookedq",
"self",
".",
"c... | https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/telnetlib.py#L329-L337 | |
onnx/onnx-tensorflow | 6194294c9f2f1c9270a614f6ae5078f2095587b7 | onnx_tf/common/attr_converter.py | python | __convert_tf_list_value | (list_value) | convert Tensorflow ListValue object to Python object | convert Tensorflow ListValue object to Python object | [
"convert",
"Tensorflow",
"ListValue",
"object",
"to",
"Python",
"object"
] | def __convert_tf_list_value(list_value):
""" convert Tensorflow ListValue object to Python object
"""
if list_value.s:
return list_value.s
elif list_value.i:
return list_value.i
elif list_value.f:
return list_value.f
elif list_value.b:
return list_value.b
elif list_value.tensor:
return list_value.tensor
elif list_value.type:
return list_value.type
elif list_value.shape:
return list_value.shape
elif list_value.func:
return list_value.func
else:
raise ValueError("Unsupported Tensorflow attribute: {}".format(list_value)) | [
"def",
"__convert_tf_list_value",
"(",
"list_value",
")",
":",
"if",
"list_value",
".",
"s",
":",
"return",
"list_value",
".",
"s",
"elif",
"list_value",
".",
"i",
":",
"return",
"list_value",
".",
"i",
"elif",
"list_value",
".",
"f",
":",
"return",
"list_... | https://github.com/onnx/onnx-tensorflow/blob/6194294c9f2f1c9270a614f6ae5078f2095587b7/onnx_tf/common/attr_converter.py#L36-L56 | ||
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/apps/user_importer/importer.py | python | create_or_update_web_users | (upload_domain, user_specs, upload_user, upload_record_id, update_progress=None) | return ret | [] | def create_or_update_web_users(upload_domain, user_specs, upload_user, upload_record_id, update_progress=None):
from corehq.apps.user_importer.helpers import WebUserImporter
domain_info_by_domain = {}
ret = {"errors": [], "rows": []}
current = 0
for row in user_specs:
if update_progress:
update_progress(current)
current += 1
username = row.get('username')
domain = row.get('domain') or upload_domain
status_row = {
'username': username,
'row': row,
}
try:
domain_info = get_domain_info(domain, upload_domain, user_specs, domain_info_by_domain,
upload_user=upload_user, is_web_upload=True)
for validator in domain_info.validators:
validator(row)
except UserUploadError as e:
status_row['flag'] = str(e)
ret['rows'].append(status_row)
continue
role = row.get('role', None)
status = row.get('status')
location_codes = row.get('location_code', []) if 'location_code' in row else None
location_codes = format_location_codes(location_codes)
try:
remove = spec_value_to_boolean_or_none(row, 'remove')
check_user_role(username, role)
role_qualified_id = domain_info.roles_by_name[role]
check_can_upload_web_users(upload_user)
user = CouchUser.get_by_username(username, strict=True)
if user:
check_changing_username(user, username)
web_user_importer = WebUserImporter(upload_domain, domain, user, upload_user,
is_new_user=False,
via=USER_CHANGE_VIA_BULK_IMPORTER,
upload_record_id=upload_record_id)
user_change_logger = web_user_importer.logger
if remove:
remove_web_user_from_domain(domain, user, username, upload_user, user_change_logger,
is_web_upload=True)
else:
membership = user.get_domain_membership(domain)
if membership:
modify_existing_user_in_domain(upload_domain, domain, domain_info, location_codes,
membership, role_qualified_id, upload_user, user,
web_user_importer)
else:
create_or_update_web_user_invite(username, domain, role_qualified_id, upload_user,
user.location_id, user_change_logger)
web_user_importer.save_log()
status_row['flag'] = 'updated'
else:
if remove:
remove_invited_web_user(domain, username)
status_row['flag'] = 'updated'
else:
if status == "Invited":
try:
invitation = Invitation.objects.get(domain=domain, email=username, is_accepted=False)
except Invitation.DoesNotExist:
raise UserUploadError(_("You can only set 'Status' to 'Invited' on a pending Web "
"User. {web_user} has no invitations for this project "
"space.").format(web_user=username))
if invitation.email_status == InvitationStatus.BOUNCED and invitation.email == username:
raise UserUploadError(_("The email has bounced for this user's invite. Please try "
"again with a different username").format(web_user=username))
user_invite_loc_id = None
if domain_info.can_assign_locations and location_codes is not None:
# set invite location to first item in location_codes
if len(location_codes) > 0:
user_invite_loc = get_location_from_site_code(location_codes[0], domain_info.location_cache)
user_invite_loc_id = user_invite_loc.location_id
create_or_update_web_user_invite(username, domain, role_qualified_id, upload_user,
user_invite_loc_id)
status_row['flag'] = 'invited'
except (UserUploadError, CouchUser.Inconsistent) as e:
status_row['flag'] = str(e)
ret["rows"].append(status_row)
return ret | [
"def",
"create_or_update_web_users",
"(",
"upload_domain",
",",
"user_specs",
",",
"upload_user",
",",
"upload_record_id",
",",
"update_progress",
"=",
"None",
")",
":",
"from",
"corehq",
".",
"apps",
".",
"user_importer",
".",
"helpers",
"import",
"WebUserImporter"... | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/user_importer/importer.py#L652-L746 | |||
python-hyper/h2 | 53feb0e0d8ddd28fa2dbd534d519a8eefd441f14 | src/h2/stream.py | python | H2Stream.locally_pushed | (self) | return [] | Mark this stream as one that was pushed by this peer. Must be called
immediately after initialization. Sends no frames, simply updates the
state machine. | Mark this stream as one that was pushed by this peer. Must be called
immediately after initialization. Sends no frames, simply updates the
state machine. | [
"Mark",
"this",
"stream",
"as",
"one",
"that",
"was",
"pushed",
"by",
"this",
"peer",
".",
"Must",
"be",
"called",
"immediately",
"after",
"initialization",
".",
"Sends",
"no",
"frames",
"simply",
"updates",
"the",
"state",
"machine",
"."
] | def locally_pushed(self):
"""
Mark this stream as one that was pushed by this peer. Must be called
immediately after initialization. Sends no frames, simply updates the
state machine.
"""
# This does not trigger any events.
events = self.state_machine.process_input(
StreamInputs.SEND_PUSH_PROMISE
)
assert not events
return [] | [
"def",
"locally_pushed",
"(",
"self",
")",
":",
"# This does not trigger any events.",
"events",
"=",
"self",
".",
"state_machine",
".",
"process_input",
"(",
"StreamInputs",
".",
"SEND_PUSH_PROMISE",
")",
"assert",
"not",
"events",
"return",
"[",
"]"
] | https://github.com/python-hyper/h2/blob/53feb0e0d8ddd28fa2dbd534d519a8eefd441f14/src/h2/stream.py#L912-L923 | |
mrlesmithjr/Ansible | d44f0dc0d942bdf3bf7334b307e6048f0ee16e36 | roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py | python | remove_move | (name) | Remove item from six.moves. | Remove item from six.moves. | [
"Remove",
"item",
"from",
"six",
".",
"moves",
"."
] | def remove_move(name):
"""Remove item from six.moves."""
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,)) | [
"def",
"remove_move",
"(",
"name",
")",
":",
"try",
":",
"delattr",
"(",
"_MovedItems",
",",
"name",
")",
"except",
"AttributeError",
":",
"try",
":",
"del",
"moves",
".",
"__dict__",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"AttributeError",
... | https://github.com/mrlesmithjr/Ansible/blob/d44f0dc0d942bdf3bf7334b307e6048f0ee16e36/roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py#L491-L499 | ||
golismero/golismero | 7d605b937e241f51c1ca4f47b20f755eeefb9d76 | tools/sqlmap/thirdparty/bottle/bottle.py | python | BaseRequest.fullpath | (self) | return urljoin(self.script_name, self.path.lstrip('/')) | Request path including :attr:`script_name` (if present). | Request path including :attr:`script_name` (if present). | [
"Request",
"path",
"including",
":",
"attr",
":",
"script_name",
"(",
"if",
"present",
")",
"."
] | def fullpath(self):
""" Request path including :attr:`script_name` (if present). """
return urljoin(self.script_name, self.path.lstrip('/')) | [
"def",
"fullpath",
"(",
"self",
")",
":",
"return",
"urljoin",
"(",
"self",
".",
"script_name",
",",
"self",
".",
"path",
".",
"lstrip",
"(",
"'/'",
")",
")"
] | https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/tools/sqlmap/thirdparty/bottle/bottle.py#L1117-L1119 | |
datitran/object_detector_app | 44e8eddeb931cced5d8cf1e283383c720a5706bf | object_detection/utils/dataset_util.py | python | int64_list_feature | (value) | return tf.train.Feature(int64_list=tf.train.Int64List(value=value)) | [] | def int64_list_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=value)) | [
"def",
"int64_list_feature",
"(",
"value",
")",
":",
"return",
"tf",
".",
"train",
".",
"Feature",
"(",
"int64_list",
"=",
"tf",
".",
"train",
".",
"Int64List",
"(",
"value",
"=",
"value",
")",
")"
] | https://github.com/datitran/object_detector_app/blob/44e8eddeb931cced5d8cf1e283383c720a5706bf/object_detection/utils/dataset_util.py#L25-L26 | |||
caiiiac/Machine-Learning-with-Python | 1a26c4467da41ca4ebc3d5bd789ea942ef79422f | MachineLearning/venv/lib/python3.5/site-packages/numpy/ma/core.py | python | _DomainTan.__call__ | (self, x) | Executes the call behavior. | Executes the call behavior. | [
"Executes",
"the",
"call",
"behavior",
"."
] | def __call__(self, x):
"Executes the call behavior."
with np.errstate(invalid='ignore'):
return umath.less(umath.absolute(umath.cos(x)), self.eps) | [
"def",
"__call__",
"(",
"self",
",",
"x",
")",
":",
"with",
"np",
".",
"errstate",
"(",
"invalid",
"=",
"'ignore'",
")",
":",
"return",
"umath",
".",
"less",
"(",
"umath",
".",
"absolute",
"(",
"umath",
".",
"cos",
"(",
"x",
")",
")",
",",
"self"... | https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/numpy/ma/core.py#L833-L836 | ||
jchanvfx/NodeGraphQt | 8b810ef469f839176f9c26bdd6496ff34d9b64a2 | NodeGraphQt/base/node.py | python | BaseNode.update_model | (self) | Update the node model from view. | Update the node model from view. | [
"Update",
"the",
"node",
"model",
"from",
"view",
"."
] | def update_model(self):
"""
Update the node model from view.
"""
for name, val in self.view.properties.items():
if name in ['inputs', 'outputs']:
continue
self.model.set_property(name, val)
for name, widget in self.view.widgets.items():
self.model.set_property(name, widget.value) | [
"def",
"update_model",
"(",
"self",
")",
":",
"for",
"name",
",",
"val",
"in",
"self",
".",
"view",
".",
"properties",
".",
"items",
"(",
")",
":",
"if",
"name",
"in",
"[",
"'inputs'",
",",
"'outputs'",
"]",
":",
"continue",
"self",
".",
"model",
"... | https://github.com/jchanvfx/NodeGraphQt/blob/8b810ef469f839176f9c26bdd6496ff34d9b64a2/NodeGraphQt/base/node.py#L575-L585 | ||
golismero/golismero | 7d605b937e241f51c1ca4f47b20f755eeefb9d76 | thirdparty_libs/openvas_lib/common.py | python | get_connector | (host, username, password, port=9390, timeout=None, ssl_verify=False) | Get concrete connector version for server.
:param host: string with host where OpenVAS manager are running.
:type host: str
:param username: user name in the OpenVAS manager.
:type username: str
:param password: user password.
:type password: str
:param port: port of the OpenVAS Manager
:type port: int
:param timeout: timeout for connection, in seconds.
:type timeout: int
:param ssl_verify: Whether or not to verify SSL certificates from the server
:type ssl_verify: bool
:return: OMP subtype.
:rtype: OMP
:raises: RemoteVersionError, ServerError, AuthFailedError, TypeError | Get concrete connector version for server. | [
"Get",
"concrete",
"connector",
"version",
"for",
"server",
"."
] | def get_connector(host, username, password, port=9390, timeout=None, ssl_verify=False):
"""
Get concrete connector version for server.
:param host: string with host where OpenVAS manager are running.
:type host: str
:param username: user name in the OpenVAS manager.
:type username: str
:param password: user password.
:type password: str
:param port: port of the OpenVAS Manager
:type port: int
:param timeout: timeout for connection, in seconds.
:type timeout: int
:param ssl_verify: Whether or not to verify SSL certificates from the server
:type ssl_verify: bool
:return: OMP subtype.
:rtype: OMP
:raises: RemoteVersionError, ServerError, AuthFailedError, TypeError
"""
manager = ConnectionManager(host, username, password, port, timeout, ssl_verify)
# Make concrete connector from version
if manager.protocol_version in ("4.0", "5.0", "6.0"):
from openvas_lib.ompv4 import OMPv4
return OMPv4(manager)
else:
raise RemoteVersionError("Unknown OpenVAS version for remote host.") | [
"def",
"get_connector",
"(",
"host",
",",
"username",
",",
"password",
",",
"port",
"=",
"9390",
",",
"timeout",
"=",
"None",
",",
"ssl_verify",
"=",
"False",
")",
":",
"manager",
"=",
"ConnectionManager",
"(",
"host",
",",
"username",
",",
"password",
"... | https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/thirdparty_libs/openvas_lib/common.py#L45-L80 | ||
omz/PythonistaAppTemplate | f560f93f8876d82a21d108977f90583df08d55af | PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/reportlab/platypus/doctemplate.py | python | BaseDocTemplate.setPageCallBack | (self, func) | Simple progress monitor - func(pageNo) called on each new page | Simple progress monitor - func(pageNo) called on each new page | [
"Simple",
"progress",
"monitor",
"-",
"func",
"(",
"pageNo",
")",
"called",
"on",
"each",
"new",
"page"
] | def setPageCallBack(self, func):
'Simple progress monitor - func(pageNo) called on each new page'
self._onPage = func | [
"def",
"setPageCallBack",
"(",
"self",
",",
"func",
")",
":",
"self",
".",
"_onPage",
"=",
"func"
] | https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/reportlab/platypus/doctemplate.py#L501-L503 | ||
SteveDoyle2/pyNastran | eda651ac2d4883d95a34951f8a002ff94f642a1a | pyNastran/bdf/cards/material_deps.py | python | MATT1.add_card | (cls, card, comment='') | return MATT1(mid, e_table, g_table, nu_table, rho_table, a_table,
ge_table, st_table, sc_table, ss_table, comment=comment) | Adds a MATT1 card from ``BDF.add_card(...)``
Parameters
----------
card : BDFCard()
a BDFCard object
comment : str; default=''
a comment for the card | Adds a MATT1 card from ``BDF.add_card(...)`` | [
"Adds",
"a",
"MATT1",
"card",
"from",
"BDF",
".",
"add_card",
"(",
"...",
")"
] | def add_card(cls, card, comment=''):
"""
Adds a MATT1 card from ``BDF.add_card(...)``
Parameters
----------
card : BDFCard()
a BDFCard object
comment : str; default=''
a comment for the card
"""
mid = integer(card, 1, 'mid')
e_table = integer_or_blank(card, 2, 'T(E)')
g_table = integer_or_blank(card, 3, 'T(G)')
nu_table = integer_or_blank(card, 4, 'T(nu)')
rho_table = integer_or_blank(card, 5, 'T(rho)')
a_table = integer_or_blank(card, 6, 'T(A)')
ge_table = integer_or_blank(card, 8, 'T(ge)')
st_table = integer_or_blank(card, 9, 'T(st)')
sc_table = integer_or_blank(card, 10, 'T(sc)')
ss_table = integer_or_blank(card, 11, 'T(ss)')
assert len(card) <= 12, f'len(MATT1 card) = {len(card):d}\ncard={card}'
return MATT1(mid, e_table, g_table, nu_table, rho_table, a_table,
ge_table, st_table, sc_table, ss_table, comment=comment) | [
"def",
"add_card",
"(",
"cls",
",",
"card",
",",
"comment",
"=",
"''",
")",
":",
"mid",
"=",
"integer",
"(",
"card",
",",
"1",
",",
"'mid'",
")",
"e_table",
"=",
"integer_or_blank",
"(",
"card",
",",
"2",
",",
"'T(E)'",
")",
"g_table",
"=",
"intege... | https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/bdf/cards/material_deps.py#L335-L360 | |
grnet/synnefo | d06ec8c7871092131cdaabf6b03ed0b504c93e43 | snf-astakos-app/astakos/quotaholder_app/migrations/old/0012_project_holdings.py | python | Migration.backwards | (self, orm) | Write your backwards methods here. | Write your backwards methods here. | [
"Write",
"your",
"backwards",
"methods",
"here",
"."
] | def backwards(self, orm):
"Write your backwards methods here." | [
"def",
"backwards",
"(",
"self",
",",
"orm",
")",
":"
] | https://github.com/grnet/synnefo/blob/d06ec8c7871092131cdaabf6b03ed0b504c93e43/snf-astakos-app/astakos/quotaholder_app/migrations/old/0012_project_holdings.py#L110-L111 | ||
renerocksai/sublimeless_zk | 6738375c0e371f0c2fde0aa9e539242cfd2b4777 | src/libzk2setevi/convert.py | python | Zk2Setevi.cut_after_note_id | (text) | Tries to find the 12/14 digit note ID (at beginning) in text. | Tries to find the 12/14 digit note ID (at beginning) in text. | [
"Tries",
"to",
"find",
"the",
"12",
"/",
"14",
"digit",
"note",
"ID",
"(",
"at",
"beginning",
")",
"in",
"text",
"."
] | def cut_after_note_id(text):
"""
Tries to find the 12/14 digit note ID (at beginning) in text.
"""
note_ids = re.findall('[0-9.]{12,18}', text)
if note_ids:
return note_ids[0] | [
"def",
"cut_after_note_id",
"(",
"text",
")",
":",
"note_ids",
"=",
"re",
".",
"findall",
"(",
"'[0-9.]{12,18}'",
",",
"text",
")",
"if",
"note_ids",
":",
"return",
"note_ids",
"[",
"0",
"]"
] | https://github.com/renerocksai/sublimeless_zk/blob/6738375c0e371f0c2fde0aa9e539242cfd2b4777/src/libzk2setevi/convert.py#L233-L239 | ||
sympy/sympy | d822fcba181155b85ff2b29fe525adbafb22b448 | sympy/codegen/algorithms.py | python | newtons_method | (expr, wrt, atol=1e-12, delta=None, debug=False,
itermax=None, counter=None) | return Wrapper(CodeBlock(*blck)) | Generates an AST for Newton-Raphson method (a root-finding algorithm).
Explanation
===========
Returns an abstract syntax tree (AST) based on ``sympy.codegen.ast`` for Netwon's
method of root-finding.
Parameters
==========
expr : expression
wrt : Symbol
With respect to, i.e. what is the variable.
atol : number or expr
Absolute tolerance (stopping criterion)
delta : Symbol
Will be a ``Dummy`` if ``None``.
debug : bool
Whether to print convergence information during iterations
itermax : number or expr
Maximum number of iterations.
counter : Symbol
Will be a ``Dummy`` if ``None``.
Examples
========
>>> from sympy import symbols, cos
>>> from sympy.codegen.ast import Assignment
>>> from sympy.codegen.algorithms import newtons_method
>>> x, dx, atol = symbols('x dx atol')
>>> expr = cos(x) - x**3
>>> algo = newtons_method(expr, x, atol, dx)
>>> algo.has(Assignment(dx, -expr/expr.diff(x)))
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Newton%27s_method | Generates an AST for Newton-Raphson method (a root-finding algorithm). | [
"Generates",
"an",
"AST",
"for",
"Newton",
"-",
"Raphson",
"method",
"(",
"a",
"root",
"-",
"finding",
"algorithm",
")",
"."
] | def newtons_method(expr, wrt, atol=1e-12, delta=None, debug=False,
itermax=None, counter=None):
""" Generates an AST for Newton-Raphson method (a root-finding algorithm).
Explanation
===========
Returns an abstract syntax tree (AST) based on ``sympy.codegen.ast`` for Netwon's
method of root-finding.
Parameters
==========
expr : expression
wrt : Symbol
With respect to, i.e. what is the variable.
atol : number or expr
Absolute tolerance (stopping criterion)
delta : Symbol
Will be a ``Dummy`` if ``None``.
debug : bool
Whether to print convergence information during iterations
itermax : number or expr
Maximum number of iterations.
counter : Symbol
Will be a ``Dummy`` if ``None``.
Examples
========
>>> from sympy import symbols, cos
>>> from sympy.codegen.ast import Assignment
>>> from sympy.codegen.algorithms import newtons_method
>>> x, dx, atol = symbols('x dx atol')
>>> expr = cos(x) - x**3
>>> algo = newtons_method(expr, x, atol, dx)
>>> algo.has(Assignment(dx, -expr/expr.diff(x)))
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Newton%27s_method
"""
if delta is None:
delta = Dummy()
Wrapper = Scope
name_d = 'delta'
else:
Wrapper = lambda x: x
name_d = delta.name
delta_expr = -expr/expr.diff(wrt)
whl_bdy = [Assignment(delta, delta_expr), AddAugmentedAssignment(wrt, delta)]
if debug:
prnt = Print([wrt, delta], r"{}=%12.5g {}=%12.5g\n".format(wrt.name, name_d))
whl_bdy = [whl_bdy[0], prnt] + whl_bdy[1:]
req = Gt(Abs(delta), atol)
declars = [Declaration(Variable(delta, type=real, value=oo))]
if itermax is not None:
counter = counter or Dummy(integer=True)
v_counter = Variable.deduced(counter, 0)
declars.append(Declaration(v_counter))
whl_bdy.append(AddAugmentedAssignment(counter, 1))
req = And(req, Lt(counter, itermax))
whl = While(req, CodeBlock(*whl_bdy))
blck = declars + [whl]
return Wrapper(CodeBlock(*blck)) | [
"def",
"newtons_method",
"(",
"expr",
",",
"wrt",
",",
"atol",
"=",
"1e-12",
",",
"delta",
"=",
"None",
",",
"debug",
"=",
"False",
",",
"itermax",
"=",
"None",
",",
"counter",
"=",
"None",
")",
":",
"if",
"delta",
"is",
"None",
":",
"delta",
"=",
... | https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/codegen/algorithms.py#L14-L83 | |
ctxis/canape | 5f0e03424577296bcc60c2008a60a98ec5307e4b | CANAPE.Scripting/Lib/logging/__init__.py | python | _showwarning | (message, category, filename, lineno, file=None, line=None) | Implementation of showwarnings which redirects to logging, which will first
check to see if the file parameter is None. If a file is specified, it will
delegate to the original warnings implementation of showwarning. Otherwise,
it will call warnings.formatwarning and will log the resulting string to a
warnings logger named "py.warnings" with level logging.WARNING. | Implementation of showwarnings which redirects to logging, which will first
check to see if the file parameter is None. If a file is specified, it will
delegate to the original warnings implementation of showwarning. Otherwise,
it will call warnings.formatwarning and will log the resulting string to a
warnings logger named "py.warnings" with level logging.WARNING. | [
"Implementation",
"of",
"showwarnings",
"which",
"redirects",
"to",
"logging",
"which",
"will",
"first",
"check",
"to",
"see",
"if",
"the",
"file",
"parameter",
"is",
"None",
".",
"If",
"a",
"file",
"is",
"specified",
"it",
"will",
"delegate",
"to",
"the",
... | def _showwarning(message, category, filename, lineno, file=None, line=None):
"""
Implementation of showwarnings which redirects to logging, which will first
check to see if the file parameter is None. If a file is specified, it will
delegate to the original warnings implementation of showwarning. Otherwise,
it will call warnings.formatwarning and will log the resulting string to a
warnings logger named "py.warnings" with level logging.WARNING.
"""
if file is not None:
if _warnings_showwarning is not None:
_warnings_showwarning(message, category, filename, lineno, file, line)
else:
s = warnings.formatwarning(message, category, filename, lineno, line)
logger = getLogger("py.warnings")
if not logger.handlers:
logger.addHandler(NullHandler())
logger.warning("%s", s) | [
"def",
"_showwarning",
"(",
"message",
",",
"category",
",",
"filename",
",",
"lineno",
",",
"file",
"=",
"None",
",",
"line",
"=",
"None",
")",
":",
"if",
"file",
"is",
"not",
"None",
":",
"if",
"_warnings_showwarning",
"is",
"not",
"None",
":",
"_war... | https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/logging/__init__.py#L1675-L1691 | ||
ninthDevilHAUNSTER/ArknightsAutoHelper | a27a930502d6e432368d9f62595a1d69a992f4e6 | vendor/penguin_client/penguin_client/models/drop_info.py | python | DropInfo.accumulatable | (self) | return self._accumulatable | Gets the accumulatable of this DropInfo. # noqa: E501
If one dropInfo is accumulatable, it means the drop data (quantity and times) of this item in the stage can be accumulated with future time ranges.For example, item ap_supply_lt_010 in stage main_01-07 has several drop infos under 3 time ranges A, B and C.If `accumulatable` for A is false while for B and C are true, then we say the \"latest max accumulatable time ranges are B~C.\" # noqa: E501
:return: The accumulatable of this DropInfo. # noqa: E501
:rtype: bool | Gets the accumulatable of this DropInfo. # noqa: E501 | [
"Gets",
"the",
"accumulatable",
"of",
"this",
"DropInfo",
".",
"#",
"noqa",
":",
"E501"
] | def accumulatable(self):
"""Gets the accumulatable of this DropInfo. # noqa: E501
If one dropInfo is accumulatable, it means the drop data (quantity and times) of this item in the stage can be accumulated with future time ranges.For example, item ap_supply_lt_010 in stage main_01-07 has several drop infos under 3 time ranges A, B and C.If `accumulatable` for A is false while for B and C are true, then we say the \"latest max accumulatable time ranges are B~C.\" # noqa: E501
:return: The accumulatable of this DropInfo. # noqa: E501
:rtype: bool
"""
return self._accumulatable | [
"def",
"accumulatable",
"(",
"self",
")",
":",
"return",
"self",
".",
"_accumulatable"
] | https://github.com/ninthDevilHAUNSTER/ArknightsAutoHelper/blob/a27a930502d6e432368d9f62595a1d69a992f4e6/vendor/penguin_client/penguin_client/models/drop_info.py#L86-L94 | |
securityclippy/elasticintel | aa08d3e9f5ab1c000128e95161139ce97ff0e334 | ingest_feed_lambda/numpy/lib/index_tricks.py | python | ndindex.ndincr | (self) | Increment the multi-dimensional index by one.
This method is for backward compatibility only: do not use. | Increment the multi-dimensional index by one. | [
"Increment",
"the",
"multi",
"-",
"dimensional",
"index",
"by",
"one",
"."
] | def ndincr(self):
"""
Increment the multi-dimensional index by one.
This method is for backward compatibility only: do not use.
"""
next(self) | [
"def",
"ndincr",
"(",
"self",
")",
":",
"next",
"(",
"self",
")"
] | https://github.com/securityclippy/elasticintel/blob/aa08d3e9f5ab1c000128e95161139ce97ff0e334/ingest_feed_lambda/numpy/lib/index_tricks.py#L577-L583 | ||
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/min/_strptime.py | python | LocaleTime.__calc_timezone | (self) | [] | def __calc_timezone(self):
# Set self.timezone by using time.tzname.
# Do not worry about possibility of time.tzname[0] == time.tzname[1]
# and time.daylight; handle that in strptime.
try:
time.tzset()
except AttributeError:
pass
self.tzname = time.tzname
self.daylight = time.daylight
no_saving = frozenset({"utc", "gmt", self.tzname[0].lower()})
if self.daylight:
has_saving = frozenset({self.tzname[1].lower()})
else:
has_saving = frozenset()
self.timezone = (no_saving, has_saving) | [
"def",
"__calc_timezone",
"(",
"self",
")",
":",
"# Set self.timezone by using time.tzname.",
"# Do not worry about possibility of time.tzname[0] == time.tzname[1]",
"# and time.daylight; handle that in strptime.",
"try",
":",
"time",
".",
"tzset",
"(",
")",
"except",
"AttributeErr... | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/_strptime.py#L152-L167 | ||||
uber-research/CoordConv | 27fab8b86efac87c262c7c596a0c384b83c9d806 | general/stats_buddy.py | python | StatsBuddy.note | (self, **kwargs) | Main stat collection function. See below for methods providing various syntactic sugar. | Main stat collection function. See below for methods providing various syntactic sugar. | [
"Main",
"stat",
"collection",
"function",
".",
"See",
"below",
"for",
"methods",
"providing",
"various",
"syntactic",
"sugar",
"."
] | def note(self, **kwargs):
'''Main stat collection function. See below for methods providing various syntactic sugar.'''
weight = kwargs['_weight'] if '_weight' in kwargs else 1.0
for key in sorted(kwargs.keys()):
if key == '_weight':
continue
value = kwargs[key]
#print key, value
self.note_one(key, value, weight=weight) | [
"def",
"note",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"weight",
"=",
"kwargs",
"[",
"'_weight'",
"]",
"if",
"'_weight'",
"in",
"kwargs",
"else",
"1.0",
"for",
"key",
"in",
"sorted",
"(",
"kwargs",
".",
"keys",
"(",
")",
")",
":",
"if",
"... | https://github.com/uber-research/CoordConv/blob/27fab8b86efac87c262c7c596a0c384b83c9d806/general/stats_buddy.py#L90-L98 | ||
cloudant/python-cloudant | 5b1ecc215b2caea22ccc2d7310462df56be6e848 | src/cloudant/client.py | python | CouchDB.create_database | (self, dbname, partitioned=False, **kwargs) | return new_db | Creates a new database on the remote server with the name provided
and adds the new database object to the client's locally cached
dictionary before returning it to the caller. The method will
optionally throw a CloudantClientException if the database
exists remotely.
:param str dbname: Name used to create the database.
:param bool throw_on_exists: Boolean flag dictating whether or
not to throw a CloudantClientException when attempting to
create a database that already exists.
:param bool partitioned: Create as a partitioned database. Defaults to
``False``.
:returns: The newly created database object | Creates a new database on the remote server with the name provided
and adds the new database object to the client's locally cached
dictionary before returning it to the caller. The method will
optionally throw a CloudantClientException if the database
exists remotely. | [
"Creates",
"a",
"new",
"database",
"on",
"the",
"remote",
"server",
"with",
"the",
"name",
"provided",
"and",
"adds",
"the",
"new",
"database",
"object",
"to",
"the",
"client",
"s",
"locally",
"cached",
"dictionary",
"before",
"returning",
"it",
"to",
"the",... | def create_database(self, dbname, partitioned=False, **kwargs):
"""
Creates a new database on the remote server with the name provided
and adds the new database object to the client's locally cached
dictionary before returning it to the caller. The method will
optionally throw a CloudantClientException if the database
exists remotely.
:param str dbname: Name used to create the database.
:param bool throw_on_exists: Boolean flag dictating whether or
not to throw a CloudantClientException when attempting to
create a database that already exists.
:param bool partitioned: Create as a partitioned database. Defaults to
``False``.
:returns: The newly created database object
"""
new_db = self._DATABASE_CLASS(self, dbname, partitioned=partitioned)
try:
new_db.create(kwargs.get('throw_on_exists', False))
except CloudantDatabaseException as ex:
if ex.status_code == 412:
raise CloudantClientException(412, dbname)
raise ex
super(CouchDB, self).__setitem__(dbname, new_db)
return new_db | [
"def",
"create_database",
"(",
"self",
",",
"dbname",
",",
"partitioned",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"new_db",
"=",
"self",
".",
"_DATABASE_CLASS",
"(",
"self",
",",
"dbname",
",",
"partitioned",
"=",
"partitioned",
")",
"try",
":",... | https://github.com/cloudant/python-cloudant/blob/5b1ecc215b2caea22ccc2d7310462df56be6e848/src/cloudant/client.py#L270-L295 | |
tensorflow/tensor2tensor | 2a33b152d7835af66a6d20afe7961751047e28dd | tensor2tensor/utils/expert_utils.py | python | cv_squared | (x) | return variance / (tf.square(mean) + epsilon) | The squared coefficient of variation of a sample.
Useful as a loss to encourage a positive distribution to be more uniform.
Epsilons added for numerical stability.
Returns 0 for an empty Tensor.
Args:
x: a `Tensor`.
Returns:
a `Scalar`. | The squared coefficient of variation of a sample. | [
"The",
"squared",
"coefficient",
"of",
"variation",
"of",
"a",
"sample",
"."
] | def cv_squared(x):
"""The squared coefficient of variation of a sample.
Useful as a loss to encourage a positive distribution to be more uniform.
Epsilons added for numerical stability.
Returns 0 for an empty Tensor.
Args:
x: a `Tensor`.
Returns:
a `Scalar`.
"""
epsilon = 1e-10
float_size = tf.to_float(tf.size(x)) + epsilon
mean = tf.reduce_sum(x) / float_size
variance = tf.reduce_sum(tf.squared_difference(x, mean)) / float_size
return variance / (tf.square(mean) + epsilon) | [
"def",
"cv_squared",
"(",
"x",
")",
":",
"epsilon",
"=",
"1e-10",
"float_size",
"=",
"tf",
".",
"to_float",
"(",
"tf",
".",
"size",
"(",
"x",
")",
")",
"+",
"epsilon",
"mean",
"=",
"tf",
".",
"reduce_sum",
"(",
"x",
")",
"/",
"float_size",
"varianc... | https://github.com/tensorflow/tensor2tensor/blob/2a33b152d7835af66a6d20afe7961751047e28dd/tensor2tensor/utils/expert_utils.py#L351-L368 | |
CharlesShang/TFFRCNN | 27e4a78d4ed363c7dad42fd2c140746c7425cfc8 | lib/rpn_msr/generate_anchors.py | python | _whctrs | (anchor) | return w, h, x_ctr, y_ctr | Return width, height, x center, and y center for an anchor (window). | Return width, height, x center, and y center for an anchor (window). | [
"Return",
"width",
"height",
"x",
"center",
"and",
"y",
"center",
"for",
"an",
"anchor",
"(",
"window",
")",
"."
] | def _whctrs(anchor):
"""
Return width, height, x center, and y center for an anchor (window).
"""
w = anchor[2] - anchor[0] + 1
h = anchor[3] - anchor[1] + 1
x_ctr = anchor[0] + 0.5 * (w - 1)
y_ctr = anchor[1] + 0.5 * (h - 1)
return w, h, x_ctr, y_ctr | [
"def",
"_whctrs",
"(",
"anchor",
")",
":",
"w",
"=",
"anchor",
"[",
"2",
"]",
"-",
"anchor",
"[",
"0",
"]",
"+",
"1",
"h",
"=",
"anchor",
"[",
"3",
"]",
"-",
"anchor",
"[",
"1",
"]",
"+",
"1",
"x_ctr",
"=",
"anchor",
"[",
"0",
"]",
"+",
"... | https://github.com/CharlesShang/TFFRCNN/blob/27e4a78d4ed363c7dad42fd2c140746c7425cfc8/lib/rpn_msr/generate_anchors.py#L50-L59 | |
AutodeskRoboticsLab/Mimic | 85447f0d346be66988303a6a054473d92f1ed6f4 | mimic/scripts/postproc/postproc.py | python | PostProcessor.write | (self, content, output_filename=None, overwrite=True) | return output_path | Write content to a file in the same directory and with the same file
extension as the template file.
:param content: The content to write.
:param output_filename: Optional name of the output file.
:param overwrite: Optional bool to overwrite existing file. If False,
a number will be appended to the name of the output file.
:return: | Write content to a file in the same directory and with the same file
extension as the template file.
:param content: The content to write.
:param output_filename: Optional name of the output file.
:param overwrite: Optional bool to overwrite existing file. If False,
a number will be appended to the name of the output file.
:return: | [
"Write",
"content",
"to",
"a",
"file",
"in",
"the",
"same",
"directory",
"and",
"with",
"the",
"same",
"file",
"extension",
"as",
"the",
"template",
"file",
".",
":",
"param",
"content",
":",
"The",
"content",
"to",
"write",
".",
":",
"param",
"output_fi... | def write(self, content, output_filename=None, overwrite=True):
"""
Write content to a file in the same directory and with the same file
extension as the template file.
:param content: The content to write.
:param output_filename: Optional name of the output file.
:param overwrite: Optional bool to overwrite existing file. If False,
a number will be appended to the name of the output file.
:return:
"""
self.program_output_name = self._get_program_name(
output_filename, default=mimic_config.Prefs.get('DEFAULT_OUTPUT_NAME'))
output_path = self._adjust_program_output_path(output_filename, overwrite)
with open(output_path, 'w') as f:
f.write(content)
return output_path | [
"def",
"write",
"(",
"self",
",",
"content",
",",
"output_filename",
"=",
"None",
",",
"overwrite",
"=",
"True",
")",
":",
"self",
".",
"program_output_name",
"=",
"self",
".",
"_get_program_name",
"(",
"output_filename",
",",
"default",
"=",
"mimic_config",
... | https://github.com/AutodeskRoboticsLab/Mimic/blob/85447f0d346be66988303a6a054473d92f1ed6f4/mimic/scripts/postproc/postproc.py#L362-L377 | |
wannabeOG/Mask-RCNN | b6ce3d8795eeaccbbde6d91ec827a38df3a88a4c | visualize.py | python | apply_mask | (image, mask, color, alpha=0.5) | return image | Apply the given mask to the image. | Apply the given mask to the image. | [
"Apply",
"the",
"given",
"mask",
"to",
"the",
"image",
"."
] | def apply_mask(image, mask, color, alpha=0.5):
"""Apply the given mask to the image.
"""
for c in range(3):
image[:, :, c] = np.where(mask == 1,
image[:, :, c] *
(1 - alpha) + alpha * color[c] * 255,
image[:, :, c])
return image | [
"def",
"apply_mask",
"(",
"image",
",",
"mask",
",",
"color",
",",
"alpha",
"=",
"0.5",
")",
":",
"for",
"c",
"in",
"range",
"(",
"3",
")",
":",
"image",
"[",
":",
",",
":",
",",
"c",
"]",
"=",
"np",
".",
"where",
"(",
"mask",
"==",
"1",
",... | https://github.com/wannabeOG/Mask-RCNN/blob/b6ce3d8795eeaccbbde6d91ec827a38df3a88a4c/visualize.py#L67-L75 | |
hastagAB/Awesome-Python-Scripts | bba0512e1c580d605205744ece878da13f2c7661 | PyRecorder/py_recorder.py | python | WindowRecorder.create_context | (self) | Combo Box | Combo Box | [
"Combo",
"Box"
] | def create_context(self):
self.__btn_start_stop = Button(self.__app, text=btn_start_txt, width=btn_start_width, command=self.start_recording, bg='green', fg='white', bd=0)
self.__btn_start_stop.pack(pady=10)
self.__btn_exit=Button(self.__app, text=btn_exit_txt, width=btn_close_width, command=self.destroy, fg='white', bg='blue', bd=0)
self.__btn_exit.pack()
''' Combo Box '''
self.__cmb_box=Combobox(self.__app, values=fps_combo_box, width=5)
self.__cmb_box.pack(side='right', padx=5, pady=5)
cmb_label = Label(self.__app, text='fps')
cmb_label.pack(side='right')
self.__cmb_box.current(default_cmbox_value)
self.__cmb_box.bind('<<ComboboxSelected>>', self.on_select_listener)
''' Timer label '''
self.__timer=Label(text='00:00:00')
self.__timer.pack(side='left', padx=5)
''' Root Menu '''
self.__root_menu = Menu(master=self.__app)
self.__app.config(menu=self.__root_menu)
''' File Menu '''
self.__file_menu = Menu(self.__root_menu, tearoff=0)
self.__file_menu.add_command(label='About', command=self.about)
self.__file_menu.add_command(label='Contact us', command=self.contact_us)
self.__file_menu.add_separator()
self.__file_menu.add_command(label='Exit', command=self.destroy)
self.__root_menu.add_cascade(label='Menu', menu=self.__file_menu) | [
"def",
"create_context",
"(",
"self",
")",
":",
"self",
".",
"__btn_start_stop",
"=",
"Button",
"(",
"self",
".",
"__app",
",",
"text",
"=",
"btn_start_txt",
",",
"width",
"=",
"btn_start_width",
",",
"command",
"=",
"self",
".",
"start_recording",
",",
"b... | https://github.com/hastagAB/Awesome-Python-Scripts/blob/bba0512e1c580d605205744ece878da13f2c7661/PyRecorder/py_recorder.py#L86-L116 | ||
graphcore/examples | 46d2b7687b829778369fc6328170a7b14761e5c6 | applications/tensorflow/reinforcement_learning/rl_benchmark.py | python | create_policy | (*infeed_data) | return action_prob | Act according to current policy and generate action probability. | Act according to current policy and generate action probability. | [
"Act",
"according",
"to",
"current",
"policy",
"and",
"generate",
"action",
"probability",
"."
] | def create_policy(*infeed_data):
"""Act according to current policy and generate action probability. """
dis_obs = list(infeed_data[:4])
cont_obs = list(infeed_data[4:8])
state_in = infeed_data[-1]
# Look up embedding for all the discrete obs
emb_lookup = []
with tf.variable_scope("popnn_lookup"):
for index, obs in enumerate(dis_obs):
emb_matrix = tf.get_variable(f'emb_matrix{index}', [DIS_OBS_CARDINALITY[index], DIS_OBS_EMB_SIZE[index]],
DTYPE)
emb_lookup.append(embedding_ops.embedding_lookup(emb_matrix, obs, name=f'emb_lookup{index}'))
# Clip some continuous observations
cont_obs[-1] = tf.clip_by_value(cont_obs[-1], -5.0, 5.0, name="clip")
# Concat groups of observations
obs_concat = []
for d_obs, c_obs in zip(emb_lookup, cont_obs):
obs_concat.append(tf.concat([d_obs, c_obs], axis=3, name="concat_obs"))
# Fully connected transformations
num_output = 8
obs_concat[-1] = Dense(num_output, dtype=DTYPE)(obs_concat[-1])
# Reduce max
obs_concat = [tf.reduce_max(obs, axis=2) for obs in obs_concat]
# Final concat of all the observations
lstm_input = tf.concat(obs_concat, axis=2, name="concat_all")
# LSTM layer
lstm_input = tf.transpose(lstm_input, perm=[1, 0, 2],
name="pre_lstm_transpose") # PopnnLSTM uses time-major tensors
lstm_cell = rnn_ops.PopnnLSTM(num_units=LSTM_HIDDEN_SIZE, dtype=DTYPE, partials_dtype=DTYPE, name="lstm")
lstm_output, state_out = lstm_cell(lstm_input, training=True,
initial_state=tf.nn.rnn_cell.LSTMStateTuple(state_in[:, 0], state_in[:, 1]))
lstm_output = tf.transpose(lstm_output, perm=[1, 0, 2], name="post_lstm_transpose")
logits = Dense(NUM_ACTIONS, name="logits", dtype=DTYPE)(lstm_output)
log_prob = tf.nn.log_softmax(logits, name="prob")
# make action selection op (outputs int actions, sampled from policy)
actions = tf.random.categorical(logits=tf.reshape(
logits, (-1, NUM_ACTIONS)), num_samples=1)
actions = tf.reshape(actions, (args.batch_size, args.time_steps))
action_masks = tf.one_hot(actions, NUM_ACTIONS, dtype=DTYPE)
action_prob = tf.reduce_sum(action_masks * log_prob, axis=-1)
return action_prob | [
"def",
"create_policy",
"(",
"*",
"infeed_data",
")",
":",
"dis_obs",
"=",
"list",
"(",
"infeed_data",
"[",
":",
"4",
"]",
")",
"cont_obs",
"=",
"list",
"(",
"infeed_data",
"[",
"4",
":",
"8",
"]",
")",
"state_in",
"=",
"infeed_data",
"[",
"-",
"1",
... | https://github.com/graphcore/examples/blob/46d2b7687b829778369fc6328170a7b14761e5c6/applications/tensorflow/reinforcement_learning/rl_benchmark.py#L85-L135 | |
PennyLaneAI/pennylane | 1275736f790ced1d778858ed383448d4a43a4cdd | pennylane/optimize/adam.py | python | AdamOptimizer.sm | (self) | return self.accumulation["sm"] | Returns estimated second moments of gradient | Returns estimated second moments of gradient | [
"Returns",
"estimated",
"second",
"moments",
"of",
"gradient"
] | def sm(self):
"""Returns estimated second moments of gradient"""
if self.accumulation is None:
return None
return self.accumulation["sm"] | [
"def",
"sm",
"(",
"self",
")",
":",
"if",
"self",
".",
"accumulation",
"is",
"None",
":",
"return",
"None",
"return",
"self",
".",
"accumulation",
"[",
"\"sm\"",
"]"
] | https://github.com/PennyLaneAI/pennylane/blob/1275736f790ced1d778858ed383448d4a43a4cdd/pennylane/optimize/adam.py#L155-L160 | |
freedombox/FreedomBox | 335a7f92cc08f27981f838a7cddfc67740598e54 | plinth/app.py | python | _initialize_module | (module_name, module) | Perform initialization on all apps in a module. | Perform initialization on all apps in a module. | [
"Perform",
"initialization",
"on",
"all",
"apps",
"in",
"a",
"module",
"."
] | def _initialize_module(module_name, module):
"""Perform initialization on all apps in a module."""
# Perform setup related initialization on the module
from . import setup # noqa # Avoid circular import
setup.init(module_name, module)
try:
module_classes = inspect.getmembers(module, inspect.isclass)
app_classes = [
cls for _, cls in module_classes if issubclass(cls, App)
]
for app_class in app_classes:
module.app = app_class()
except Exception as exception:
logger.exception('Exception while running init for %s: %s', module,
exception)
if cfg.develop:
raise | [
"def",
"_initialize_module",
"(",
"module_name",
",",
"module",
")",
":",
"# Perform setup related initialization on the module",
"from",
".",
"import",
"setup",
"# noqa # Avoid circular import",
"setup",
".",
"init",
"(",
"module_name",
",",
"module",
")",
"try",
":",... | https://github.com/freedombox/FreedomBox/blob/335a7f92cc08f27981f838a7cddfc67740598e54/plinth/app.py#L524-L541 | ||
aboSamoor/polyglot | 9b93b2ecbb9ba1f638c56b92665336e93230646a | polyglot/downloader.py | python | Downloader.default_download_dir | (self) | return polyglot_path | Return the directory to which packages will be downloaded by
default. This value can be overridden using the constructor,
or on a case-by-case basis using the ``download_dir`` argument when
calling ``download()``.
On all other platforms, the default directory is ``~/polyglot_data``. | Return the directory to which packages will be downloaded by
default. This value can be overridden using the constructor,
or on a case-by-case basis using the ``download_dir`` argument when
calling ``download()``. | [
"Return",
"the",
"directory",
"to",
"which",
"packages",
"will",
"be",
"downloaded",
"by",
"default",
".",
"This",
"value",
"can",
"be",
"overridden",
"using",
"the",
"constructor",
"or",
"on",
"a",
"case",
"-",
"by",
"-",
"case",
"basis",
"using",
"the",
... | def default_download_dir(self):
"""
Return the directory to which packages will be downloaded by
default. This value can be overridden using the constructor,
or on a case-by-case basis using the ``download_dir`` argument when
calling ``download()``.
On all other platforms, the default directory is ``~/polyglot_data``.
"""
return polyglot_path | [
"def",
"default_download_dir",
"(",
"self",
")",
":",
"return",
"polyglot_path"
] | https://github.com/aboSamoor/polyglot/blob/9b93b2ecbb9ba1f638c56b92665336e93230646a/polyglot/downloader.py#L1026-L1035 | |
holoviz/datashader | 25578abde75c7fa28c6633b33cb8d8a1e433da67 | datashader/glyphs/line.py | python | LineAxis0Multi.compute_y_bounds | (self, df) | return self.maybe_expand_bounds((min(mins), max(maxes))) | [] | def compute_y_bounds(self, df):
bounds_list = [self._compute_bounds(df[y])
for y in self.y]
mins, maxes = zip(*bounds_list)
return self.maybe_expand_bounds((min(mins), max(maxes))) | [
"def",
"compute_y_bounds",
"(",
"self",
",",
"df",
")",
":",
"bounds_list",
"=",
"[",
"self",
".",
"_compute_bounds",
"(",
"df",
"[",
"y",
"]",
")",
"for",
"y",
"in",
"self",
".",
"y",
"]",
"mins",
",",
"maxes",
"=",
"zip",
"(",
"*",
"bounds_list",... | https://github.com/holoviz/datashader/blob/25578abde75c7fa28c6633b33cb8d8a1e433da67/datashader/glyphs/line.py#L106-L110 | |||
google/stereo-magnification | f2041f80ed8c340173a6048375ba900201c1f1e7 | stereomag/sequence_data_loader.py | python | SequenceDataLoader.__init__ | (self,
cameras_glob='train/????????????????.txt',
image_dir='images',
training=True,
num_source=2,
shuffle_seq_length=10,
random_seed=8964,
map_function=None) | [] | def __init__(self,
cameras_glob='train/????????????????.txt',
image_dir='images',
training=True,
num_source=2,
shuffle_seq_length=10,
random_seed=8964,
map_function=None):
self.num_source = num_source
self.random_seed = random_seed
self.shuffle_seq_length = shuffle_seq_length
self.batch_size = FLAGS.batch_size
self.image_height = FLAGS.image_height
self.image_width = FLAGS.image_width
self.datasets = loader.create_from_flags(
cameras_glob=cameras_glob,
image_dir=image_dir,
training=training,
map_function=map_function) | [
"def",
"__init__",
"(",
"self",
",",
"cameras_glob",
"=",
"'train/????????????????.txt'",
",",
"image_dir",
"=",
"'images'",
",",
"training",
"=",
"True",
",",
"num_source",
"=",
"2",
",",
"shuffle_seq_length",
"=",
"10",
",",
"random_seed",
"=",
"8964",
",",
... | https://github.com/google/stereo-magnification/blob/f2041f80ed8c340173a6048375ba900201c1f1e7/stereomag/sequence_data_loader.py#L32-L51 | ||||
jython/frozen-mirror | b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99 | lib-python/2.7/dummy_thread.py | python | start_new_thread | (function, args, kwargs={}) | Dummy implementation of thread.start_new_thread().
Compatibility is maintained by making sure that ``args`` is a
tuple and ``kwargs`` is a dictionary. If an exception is raised
and it is SystemExit (which can be done by thread.exit()) it is
caught and nothing is done; all other exceptions are printed out
by using traceback.print_exc().
If the executed function calls interrupt_main the KeyboardInterrupt will be
raised when the function returns. | Dummy implementation of thread.start_new_thread(). | [
"Dummy",
"implementation",
"of",
"thread",
".",
"start_new_thread",
"()",
"."
] | def start_new_thread(function, args, kwargs={}):
"""Dummy implementation of thread.start_new_thread().
Compatibility is maintained by making sure that ``args`` is a
tuple and ``kwargs`` is a dictionary. If an exception is raised
and it is SystemExit (which can be done by thread.exit()) it is
caught and nothing is done; all other exceptions are printed out
by using traceback.print_exc().
If the executed function calls interrupt_main the KeyboardInterrupt will be
raised when the function returns.
"""
if type(args) != type(tuple()):
raise TypeError("2nd arg must be a tuple")
if type(kwargs) != type(dict()):
raise TypeError("3rd arg must be a dict")
global _main
_main = False
try:
function(*args, **kwargs)
except SystemExit:
pass
except:
_traceback.print_exc()
_main = True
global _interrupt
if _interrupt:
_interrupt = False
raise KeyboardInterrupt | [
"def",
"start_new_thread",
"(",
"function",
",",
"args",
",",
"kwargs",
"=",
"{",
"}",
")",
":",
"if",
"type",
"(",
"args",
")",
"!=",
"type",
"(",
"tuple",
"(",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"2nd arg must be a tuple\"",
")",
"if",
"type"... | https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/lib-python/2.7/dummy_thread.py#L27-L56 | ||
beeware/ouroboros | a29123c6fab6a807caffbb7587cf548e0c370296 | ouroboros/pickletools.py | python | read_bytes1 | (f) | r"""
>>> import io
>>> read_bytes1(io.BytesIO(b"\x00"))
b''
>>> read_bytes1(io.BytesIO(b"\x03abcdef"))
b'abc' | r"""
>>> import io
>>> read_bytes1(io.BytesIO(b"\x00"))
b''
>>> read_bytes1(io.BytesIO(b"\x03abcdef"))
b'abc' | [
"r",
">>>",
"import",
"io",
">>>",
"read_bytes1",
"(",
"io",
".",
"BytesIO",
"(",
"b",
"\\",
"x00",
"))",
"b",
">>>",
"read_bytes1",
"(",
"io",
".",
"BytesIO",
"(",
"b",
"\\",
"x03abcdef",
"))",
"b",
"abc"
] | def read_bytes1(f):
r"""
>>> import io
>>> read_bytes1(io.BytesIO(b"\x00"))
b''
>>> read_bytes1(io.BytesIO(b"\x03abcdef"))
b'abc'
"""
n = read_uint1(f)
assert n >= 0
data = f.read(n)
if len(data) == n:
return data
raise ValueError("expected %d bytes in a bytes1, but only %d remain" %
(n, len(data))) | [
"def",
"read_bytes1",
"(",
"f",
")",
":",
"n",
"=",
"read_uint1",
"(",
"f",
")",
"assert",
"n",
">=",
"0",
"data",
"=",
"f",
".",
"read",
"(",
"n",
")",
"if",
"len",
"(",
"data",
")",
"==",
"n",
":",
"return",
"data",
"raise",
"ValueError",
"("... | https://github.com/beeware/ouroboros/blob/a29123c6fab6a807caffbb7587cf548e0c370296/ouroboros/pickletools.py#L472-L487 | ||
matrix-org/synapse | 8e57584a5859a9002759963eb546d523d2498a01 | synapse/handlers/directory.py | python | DirectoryHandler.edit_published_appservice_room_list | (
self, appservice_id: str, network_id: str, room_id: str, visibility: str
) | Add or remove a room from the appservice/network specific public
room list.
Args:
appservice_id: ID of the appservice that owns the list
network_id: The ID of the network the list is associated with
room_id
visibility: either "public" or "private" | Add or remove a room from the appservice/network specific public
room list. | [
"Add",
"or",
"remove",
"a",
"room",
"from",
"the",
"appservice",
"/",
"network",
"specific",
"public",
"room",
"list",
"."
] | async def edit_published_appservice_room_list(
self, appservice_id: str, network_id: str, room_id: str, visibility: str
) -> None:
"""Add or remove a room from the appservice/network specific public
room list.
Args:
appservice_id: ID of the appservice that owns the list
network_id: The ID of the network the list is associated with
room_id
visibility: either "public" or "private"
"""
if visibility not in ["public", "private"]:
raise SynapseError(400, "Invalid visibility setting")
await self.store.set_room_is_public_appservice(
room_id, appservice_id, network_id, visibility == "public"
) | [
"async",
"def",
"edit_published_appservice_room_list",
"(",
"self",
",",
"appservice_id",
":",
"str",
",",
"network_id",
":",
"str",
",",
"room_id",
":",
"str",
",",
"visibility",
":",
"str",
")",
"->",
"None",
":",
"if",
"visibility",
"not",
"in",
"[",
"\... | https://github.com/matrix-org/synapse/blob/8e57584a5859a9002759963eb546d523d2498a01/synapse/handlers/directory.py#L486-L503 | ||
nathanborror/django-basic-apps | 3a90090857549ea4198a72c44f45f6edb238e2a8 | basic/relationships/models.py | python | RelationshipManager.blocking | (self, from_user, to_user) | return False | Returns True if from_user is blocking to_user. | Returns True if from_user is blocking to_user. | [
"Returns",
"True",
"if",
"from_user",
"is",
"blocking",
"to_user",
"."
] | def blocking(self, from_user, to_user):
"""Returns True if from_user is blocking to_user."""
try:
relationship = self.get(from_user=from_user, to_user=to_user)
if relationship.is_blocked:
return True
except:
return False
return False | [
"def",
"blocking",
"(",
"self",
",",
"from_user",
",",
"to_user",
")",
":",
"try",
":",
"relationship",
"=",
"self",
".",
"get",
"(",
"from_user",
"=",
"from_user",
",",
"to_user",
"=",
"to_user",
")",
"if",
"relationship",
".",
"is_blocked",
":",
"retur... | https://github.com/nathanborror/django-basic-apps/blob/3a90090857549ea4198a72c44f45f6edb238e2a8/basic/relationships/models.py#L56-L64 | |
theotherp/nzbhydra | 4b03d7f769384b97dfc60dade4806c0fc987514e | libs/binhex.py | python | binhex | (inp, out) | (infilename, outfilename) - Create binhex-encoded copy of a file | (infilename, outfilename) - Create binhex-encoded copy of a file | [
"(",
"infilename",
"outfilename",
")",
"-",
"Create",
"binhex",
"-",
"encoded",
"copy",
"of",
"a",
"file"
] | def binhex(inp, out):
"""(infilename, outfilename) - Create binhex-encoded copy of a file"""
finfo = getfileinfo(inp)
ofp = BinHex(finfo, out)
ifp = open(inp, 'rb')
# XXXX Do textfile translation on non-mac systems
while 1:
d = ifp.read(128000)
if not d: break
ofp.write(d)
ofp.close_data()
ifp.close()
ifp = openrsrc(inp, 'rb')
while 1:
d = ifp.read(128000)
if not d: break
ofp.write_rsrc(d)
ofp.close()
ifp.close() | [
"def",
"binhex",
"(",
"inp",
",",
"out",
")",
":",
"finfo",
"=",
"getfileinfo",
"(",
"inp",
")",
"ofp",
"=",
"BinHex",
"(",
"finfo",
",",
"out",
")",
"ifp",
"=",
"open",
"(",
"inp",
",",
"'rb'",
")",
"# XXXX Do textfile translation on non-mac systems",
"... | https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/binhex.py#L256-L276 | ||
alephdata/memorious | 50e074748206f67cebb8a07e665a0a8993260e77 | memorious/logic/http.py | python | ContextHttpResponse.fetch | (self) | return self._file_path | Lazily trigger download of the data when requested. | Lazily trigger download of the data when requested. | [
"Lazily",
"trigger",
"download",
"of",
"the",
"data",
"when",
"requested",
"."
] | def fetch(self):
"""Lazily trigger download of the data when requested."""
if self._file_path is not None:
return self._file_path
temp_path = self.context.work_path
if self._content_hash is not None:
self._file_path = storage.load_file(self._content_hash, temp_path=temp_path)
return self._file_path
if self.response is not None:
self._file_path = random_filename(temp_path)
content_hash = sha1()
with open(self._file_path, "wb") as fh:
for chunk in self.response.iter_content(chunk_size=8192):
content_hash.update(chunk)
fh.write(chunk)
self._remove_file = True
chash = content_hash.hexdigest()
self._content_hash = storage.archive_file(
self._file_path, content_hash=chash
)
if self.http.cache and self.ok:
self.context.set_tag(self.request_id, self.serialize())
self.retrieved_at = datetime.utcnow().isoformat()
return self._file_path | [
"def",
"fetch",
"(",
"self",
")",
":",
"if",
"self",
".",
"_file_path",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_file_path",
"temp_path",
"=",
"self",
".",
"context",
".",
"work_path",
"if",
"self",
".",
"_content_hash",
"is",
"not",
"None",
... | https://github.com/alephdata/memorious/blob/50e074748206f67cebb8a07e665a0a8993260e77/memorious/logic/http.py#L180-L203 | |
HaoZhang95/Python24 | b897224b8a0e6a5734f408df8c24846a98c553bf | 00Python/venv/Lib/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/html5lib/_inputstream.py | python | HTMLBinaryInputStream.__init__ | (self, source, override_encoding=None, transport_encoding=None,
same_origin_parent_encoding=None, likely_encoding=None,
default_encoding="windows-1252", useChardet=True) | Initialises the HTMLInputStream.
HTMLInputStream(source, [encoding]) -> Normalized stream from source
for use by html5lib.
source can be either a file-object, local filename or a string.
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element) | Initialises the HTMLInputStream. | [
"Initialises",
"the",
"HTMLInputStream",
"."
] | def __init__(self, source, override_encoding=None, transport_encoding=None,
same_origin_parent_encoding=None, likely_encoding=None,
default_encoding="windows-1252", useChardet=True):
"""Initialises the HTMLInputStream.
HTMLInputStream(source, [encoding]) -> Normalized stream from source
for use by html5lib.
source can be either a file-object, local filename or a string.
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element)
"""
# Raw Stream - for unicode objects this will encode to utf-8 and set
# self.charEncoding as appropriate
self.rawStream = self.openStream(source)
HTMLUnicodeInputStream.__init__(self, self.rawStream)
# Encoding Information
# Number of bytes to use when looking for a meta element with
# encoding information
self.numBytesMeta = 1024
# Number of bytes to use when using detecting encoding using chardet
self.numBytesChardet = 100
# Things from args
self.override_encoding = override_encoding
self.transport_encoding = transport_encoding
self.same_origin_parent_encoding = same_origin_parent_encoding
self.likely_encoding = likely_encoding
self.default_encoding = default_encoding
# Determine encoding
self.charEncoding = self.determineEncoding(useChardet)
assert self.charEncoding[0] is not None
# Call superclass
self.reset() | [
"def",
"__init__",
"(",
"self",
",",
"source",
",",
"override_encoding",
"=",
"None",
",",
"transport_encoding",
"=",
"None",
",",
"same_origin_parent_encoding",
"=",
"None",
",",
"likely_encoding",
"=",
"None",
",",
"default_encoding",
"=",
"\"windows-1252\"",
",... | https://github.com/HaoZhang95/Python24/blob/b897224b8a0e6a5734f408df8c24846a98c553bf/00Python/venv/Lib/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/html5lib/_inputstream.py#L392-L432 | ||
soravux/scoop | 3c0357c32cec3169a19c822a3857c968a48775c5 | bench/process_debug.py | python | plotWorkerTask | (workertask, worker_names, filename) | [] | def plotWorkerTask(workertask, worker_names, filename):
fig = plt.figure()
ax = fig.add_subplot(111)
ind = range(len(workertask))
width = 1
rects = ax.bar(ind, workertask, width, edgecolor="black")
ax.set_ylabel('Tasks')
ax.set_title('Number of tasks executed by worker')
#ax.set_xticks([x+(width/2.0) for x in ind])
ax.set_xlabel('Worker')
#ax.tick_params(axis='x', which='major', labelsize=6)
ax.set_xticklabels([])
ax.set_xlim([-1, len(worker_names) + 1])
#ax.set_xticklabels(range(len(worker_names)))
fig.savefig(filename) | [
"def",
"plotWorkerTask",
"(",
"workertask",
",",
"worker_names",
",",
"filename",
")",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
")",
"ax",
"=",
"fig",
".",
"add_subplot",
"(",
"111",
")",
"ind",
"=",
"range",
"(",
"len",
"(",
"workertask",
")",
")... | https://github.com/soravux/scoop/blob/3c0357c32cec3169a19c822a3857c968a48775c5/bench/process_debug.py#L312-L328 | ||||
ipython/ipython | c0abea7a6dfe52c1f74c9d0387d4accadba7cc14 | IPython/core/inputtransformer2.py | python | _tr_help2 | (content) | return _make_help_call(content, '??') | Translate lines escaped with: ??
A naked help line should fire the intro help screen (shell.show_usage()) | Translate lines escaped with: ?? | [
"Translate",
"lines",
"escaped",
"with",
":",
"??"
] | def _tr_help2(content):
"""Translate lines escaped with: ??
A naked help line should fire the intro help screen (shell.show_usage())
"""
if not content:
return 'get_ipython().show_usage()'
return _make_help_call(content, '??') | [
"def",
"_tr_help2",
"(",
"content",
")",
":",
"if",
"not",
"content",
":",
"return",
"'get_ipython().show_usage()'",
"return",
"_make_help_call",
"(",
"content",
",",
"'??'",
")"
] | https://github.com/ipython/ipython/blob/c0abea7a6dfe52c1f74c9d0387d4accadba7cc14/IPython/core/inputtransformer2.py#L354-L362 | |
jina-ai/jina | c77a492fcd5adba0fc3de5347bea83dd4e7d8087 | daemon/api/endpoints/partial/pod.py | python | _delete | () | .. #noqa: DAR101
.. #noqa: DAR201 | [] | async def _delete():
"""
.. #noqa: DAR101
.. #noqa: DAR201"""
try:
store.delete()
except Exception as ex:
raise PartialDaemon400Exception from ex | [
"async",
"def",
"_delete",
"(",
")",
":",
"try",
":",
"store",
".",
"delete",
"(",
")",
"except",
"Exception",
"as",
"ex",
":",
"raise",
"PartialDaemon400Exception",
"from",
"ex"
] | https://github.com/jina-ai/jina/blob/c77a492fcd5adba0fc3de5347bea83dd4e7d8087/daemon/api/endpoints/partial/pod.py#L85-L93 | |||
psychopy/psychopy | 01b674094f38d0e0bd51c45a6f66f671d7041696 | psychopy/sound/backend_pyo.py | python | SoundPyo.__init__ | (self, value="C", secs=0.5, octave=4, stereo=True,
volume=1.0, loops=0, sampleRate=44100, bits=16,
hamming=True, start=0, stop=-1,
name='', autoLog=True) | value: can be a number, string or an array:
* If it's a number between 37 and 32767 then a tone will be
generated at that frequency in Hz.
* It could be a string for a note ('A', 'Bfl', 'B', 'C',
'Csh', ...). Then you may want to specify which octave as well
* Or a string could represent a filename in the current location,
or mediaLocation, or a full path combo
* Or by giving an Nx2 numpy array of floats (-1:1) you can
specify the sound yourself as a waveform
By default, a Hanning window (5ms duration) will be applied to a
generated tone, so that onset and offset are smoother (to avoid
clicking). To disable the Hanning window, set `hamming=False`.
secs:
Duration of a tone. Not used for sounds from a file.
start : float
Where to start playing a sound file;
default = 0s (start of the file).
stop : float
Where to stop playing a sound file; default = end of file.
octave: is only relevant if the value is a note name.
Middle octave of a piano is 4. Most computers won't
output sounds in the bottom octave (1) and the top
octave (8) is generally painful
stereo: True (= default, two channels left and right),
False (one channel)
volume: loudness to play the sound, from 0.0 (silent) to 1.0 (max).
Adjustments are not possible during playback, only before.
loops : int
How many times to repeat the sound after it plays once. If
`loops` == -1, the sound will repeat indefinitely until stopped.
sampleRate (= 44100): if the psychopy.sound.init() function has been
called or if another sound has already been created then this
argument will be ignored and the previous setting will be used
bits: has no effect for the pyo backend
hamming: boolean (default True) to indicate if the sound should
be apodized (i.e., the onset and offset smoothly ramped up from
down to zero). The function apodize uses a Hanning window, but
arguments named 'hamming' are preserved so that existing code
is not broken by the change from Hamming to Hanning internally.
Not applied to sounds from files. | value: can be a number, string or an array:
* If it's a number between 37 and 32767 then a tone will be
generated at that frequency in Hz.
* It could be a string for a note ('A', 'Bfl', 'B', 'C',
'Csh', ...). Then you may want to specify which octave as well
* Or a string could represent a filename in the current location,
or mediaLocation, or a full path combo
* Or by giving an Nx2 numpy array of floats (-1:1) you can
specify the sound yourself as a waveform | [
"value",
":",
"can",
"be",
"a",
"number",
"string",
"or",
"an",
"array",
":",
"*",
"If",
"it",
"s",
"a",
"number",
"between",
"37",
"and",
"32767",
"then",
"a",
"tone",
"will",
"be",
"generated",
"at",
"that",
"frequency",
"in",
"Hz",
".",
"*",
"It... | def __init__(self, value="C", secs=0.5, octave=4, stereo=True,
volume=1.0, loops=0, sampleRate=44100, bits=16,
hamming=True, start=0, stop=-1,
name='', autoLog=True):
"""
value: can be a number, string or an array:
* If it's a number between 37 and 32767 then a tone will be
generated at that frequency in Hz.
* It could be a string for a note ('A', 'Bfl', 'B', 'C',
'Csh', ...). Then you may want to specify which octave as well
* Or a string could represent a filename in the current location,
or mediaLocation, or a full path combo
* Or by giving an Nx2 numpy array of floats (-1:1) you can
specify the sound yourself as a waveform
By default, a Hanning window (5ms duration) will be applied to a
generated tone, so that onset and offset are smoother (to avoid
clicking). To disable the Hanning window, set `hamming=False`.
secs:
Duration of a tone. Not used for sounds from a file.
start : float
Where to start playing a sound file;
default = 0s (start of the file).
stop : float
Where to stop playing a sound file; default = end of file.
octave: is only relevant if the value is a note name.
Middle octave of a piano is 4. Most computers won't
output sounds in the bottom octave (1) and the top
octave (8) is generally painful
stereo: True (= default, two channels left and right),
False (one channel)
volume: loudness to play the sound, from 0.0 (silent) to 1.0 (max).
Adjustments are not possible during playback, only before.
loops : int
How many times to repeat the sound after it plays once. If
`loops` == -1, the sound will repeat indefinitely until stopped.
sampleRate (= 44100): if the psychopy.sound.init() function has been
called or if another sound has already been created then this
argument will be ignored and the previous setting will be used
bits: has no effect for the pyo backend
hamming: boolean (default True) to indicate if the sound should
be apodized (i.e., the onset and offset smoothly ramped up from
down to zero). The function apodize uses a Hanning window, but
arguments named 'hamming' are preserved so that existing code
is not broken by the change from Hamming to Hanning internally.
Not applied to sounds from files.
"""
global pyoSndServer
if pyoSndServer is None or pyoSndServer.getIsBooted() == 0:
init(rate=sampleRate)
self.sampleRate = pyoSndServer.getSamplingRate()
self.format = bits
self.isStereo = stereo
self.channels = 1 + int(stereo)
self.secs = secs
self.startTime = start
self.stopTime = stop
self.autoLog = autoLog
self.name = name
# try to create sound; set volume and loop before setSound (else
# needsUpdate=True)
self._snd = None
self.volume = min(1.0, max(0.0, volume))
# distinguish the loops requested from loops actual because of
# infinite tones (which have many loops but none requested)
# -1 for infinite or a number of loops
self.requestedLoops = self.loops = int(loops)
self.setSound(value=value, secs=secs, octave=octave, hamming=hamming)
self.needsUpdate = False | [
"def",
"__init__",
"(",
"self",
",",
"value",
"=",
"\"C\"",
",",
"secs",
"=",
"0.5",
",",
"octave",
"=",
"4",
",",
"stereo",
"=",
"True",
",",
"volume",
"=",
"1.0",
",",
"loops",
"=",
"0",
",",
"sampleRate",
"=",
"44100",
",",
"bits",
"=",
"16",
... | https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/sound/backend_pyo.py#L283-L364 | ||
openstack/swift | b8d7c3dcb817504dcc0959ba52cc4ed2cf66c100 | swift/obj/reconstructor.py | python | ObjectReconstructor._get_suffixes_to_sync | (self, job, node) | return suffixes, node | For SYNC jobs we need to make a remote REPLICATE request to get
the remote node's current suffix's hashes and then compare to our
local suffix's hashes to decide which suffixes (if any) are out
of sync.
:param job: the job dict, with the keys defined in ``_get_part_jobs``
:param node: the remote node dict
:returns: a (possibly empty) list of strings, the suffixes to be
synced and the remote node. | For SYNC jobs we need to make a remote REPLICATE request to get
the remote node's current suffix's hashes and then compare to our
local suffix's hashes to decide which suffixes (if any) are out
of sync. | [
"For",
"SYNC",
"jobs",
"we",
"need",
"to",
"make",
"a",
"remote",
"REPLICATE",
"request",
"to",
"get",
"the",
"remote",
"node",
"s",
"current",
"suffix",
"s",
"hashes",
"and",
"then",
"compare",
"to",
"our",
"local",
"suffix",
"s",
"hashes",
"to",
"decid... | def _get_suffixes_to_sync(self, job, node):
"""
For SYNC jobs we need to make a remote REPLICATE request to get
the remote node's current suffix's hashes and then compare to our
local suffix's hashes to decide which suffixes (if any) are out
of sync.
:param job: the job dict, with the keys defined in ``_get_part_jobs``
:param node: the remote node dict
:returns: a (possibly empty) list of strings, the suffixes to be
synced and the remote node.
"""
# get hashes from the remote node
remote_suffixes = None
attempts_remaining = 1
headers = self.headers.copy()
headers['X-Backend-Storage-Policy-Index'] = int(job['policy'])
possible_nodes = self._iter_nodes_for_frag(
job['policy'], job['partition'], node)
while remote_suffixes is None and attempts_remaining:
try:
node = next(possible_nodes)
except StopIteration:
break
attempts_remaining -= 1
try:
with Timeout(self.http_timeout):
resp = http_connect(
node['replication_ip'], node['replication_port'],
node['device'], job['partition'], 'REPLICATE',
'', headers=headers).getresponse()
if resp.status == HTTP_INSUFFICIENT_STORAGE:
self.logger.error(
'%s responded as unmounted',
_full_path(node, job['partition'], '',
job['policy']))
attempts_remaining += 1
elif resp.status != HTTP_OK:
full_path = _full_path(node, job['partition'], '',
job['policy'])
self.logger.error(
"Invalid response %(resp)s from %(full_path)s",
{'resp': resp.status, 'full_path': full_path})
else:
remote_suffixes = pickle.loads(resp.read())
except (Exception, Timeout):
# all exceptions are logged here so that our caller can
# safely catch our exception and continue to the next node
# without logging
self.logger.exception('Unable to get remote suffix hashes '
'from %r' % _full_path(
node, job['partition'], '',
job['policy']))
if remote_suffixes is None:
raise SuffixSyncError('Unable to get remote suffix hashes')
suffixes = self.get_suffix_delta(job['hashes'],
job['frag_index'],
remote_suffixes,
node['backend_index'])
# now recalculate local hashes for suffixes that don't
# match so we're comparing the latest
local_suff = self._get_hashes(job['local_dev']['device'],
job['partition'],
job['policy'], recalculate=suffixes)
suffixes = self.get_suffix_delta(local_suff,
job['frag_index'],
remote_suffixes,
node['backend_index'])
self.suffix_count += len(suffixes)
return suffixes, node | [
"def",
"_get_suffixes_to_sync",
"(",
"self",
",",
"job",
",",
"node",
")",
":",
"# get hashes from the remote node",
"remote_suffixes",
"=",
"None",
"attempts_remaining",
"=",
"1",
"headers",
"=",
"self",
".",
"headers",
".",
"copy",
"(",
")",
"headers",
"[",
... | https://github.com/openstack/swift/blob/b8d7c3dcb817504dcc0959ba52cc4ed2cf66c100/swift/obj/reconstructor.py#L890-L962 | |
i-pan/kaggle-rsna18 | 2db498fe99615d935aa676f04847d0c562fd8e46 | models/DeformableConvNets/faster_rcnn/core/module.py | python | Module.update | (self) | Update parameters according to the installed optimizer and the gradients computed
in the previous forward-backward batch. | Update parameters according to the installed optimizer and the gradients computed
in the previous forward-backward batch. | [
"Update",
"parameters",
"according",
"to",
"the",
"installed",
"optimizer",
"and",
"the",
"gradients",
"computed",
"in",
"the",
"previous",
"forward",
"-",
"backward",
"batch",
"."
] | def update(self):
"""Update parameters according to the installed optimizer and the gradients computed
in the previous forward-backward batch.
"""
assert self.binded and self.params_initialized and self.optimizer_initialized
self._params_dirty = True
if self._update_on_kvstore:
try:
_update_params_on_kvstore(self._exec_group.param_arrays,
self._exec_group.grad_arrays,
self._kvstore)
except:
_update_params_on_kvstore(self._exec_group.param_arrays,
self._exec_group.grad_arrays,
self._kvstore, param_names=self._exec_group.param_names)
else:
_update_params(self._exec_group.param_arrays,
self._exec_group.grad_arrays,
updater=self._updater,
num_device=len(self._context),
kvstore=self._kvstore) | [
"def",
"update",
"(",
"self",
")",
":",
"assert",
"self",
".",
"binded",
"and",
"self",
".",
"params_initialized",
"and",
"self",
".",
"optimizer_initialized",
"self",
".",
"_params_dirty",
"=",
"True",
"if",
"self",
".",
"_update_on_kvstore",
":",
"try",
":... | https://github.com/i-pan/kaggle-rsna18/blob/2db498fe99615d935aa676f04847d0c562fd8e46/models/DeformableConvNets/faster_rcnn/core/module.py#L566-L587 | ||
grow/grow | 97fc21730b6a674d5d33948d94968e79447ce433 | grow/rendering/render_batch.py | python | RenderBatchResult.__init__ | (self) | [] | def __init__(self):
self.render_errors = []
self.rendered_docs = [] | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"render_errors",
"=",
"[",
"]",
"self",
".",
"rendered_docs",
"=",
"[",
"]"
] | https://github.com/grow/grow/blob/97fc21730b6a674d5d33948d94968e79447ce433/grow/rendering/render_batch.py#L291-L293 | ||||
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/apps/users/models.py | python | CouchUser.username_in_report | (self) | return user_display_string(self.username, self.first_name, self.last_name) | [] | def username_in_report(self):
return user_display_string(self.username, self.first_name, self.last_name) | [
"def",
"username_in_report",
"(",
"self",
")",
":",
"return",
"user_display_string",
"(",
"self",
".",
"username",
",",
"self",
".",
"first_name",
",",
"self",
".",
"last_name",
")"
] | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/users/models.py#L1012-L1013 | |||
opendatacube/datacube-core | b062184be61c140a168de94510bc3661748f112e | datacube/index/_datasets.py | python | DatasetResource.search_returning_datasets_light | (self, field_names: tuple, custom_offsets=None, limit=None, **query) | This is a dataset search function that returns the results as objects of a dynamically
generated Dataset class that is a subclass of tuple.
Only the requested fields will be returned together with related derived attributes as property functions
similer to the datacube.model.Dataset class. For example, if 'extent'is requested all of
'crs', 'extent', 'transform', and 'bounds' are available as property functions.
The field_names can be custom fields in addition to those specified in metadata_type, fixed fields, or
native fields. The field_names can also be derived fields like 'extent', 'crs', 'transform',
and 'bounds'. The custom fields require custom offsets of the metadata doc be provided.
The datasets can be selected based on values of custom fields as long as relevant custom
offsets are provided. However custom field values are not transformed so must match what is
stored in the database.
:param field_names: A tuple of field names that would be returned including derived fields
such as extent, crs
:param custom_offsets: A dictionary of offsets in the metadata doc for custom fields
:param limit: Number of datasets returned per product.
:param query: key, value mappings of query that will be processed against metadata_types,
product definitions and/or dataset table.
:return: A Dynamically generated DatasetLight (a subclass of namedtuple and possibly with
property functions). | This is a dataset search function that returns the results as objects of a dynamically
generated Dataset class that is a subclass of tuple. | [
"This",
"is",
"a",
"dataset",
"search",
"function",
"that",
"returns",
"the",
"results",
"as",
"objects",
"of",
"a",
"dynamically",
"generated",
"Dataset",
"class",
"that",
"is",
"a",
"subclass",
"of",
"tuple",
"."
] | def search_returning_datasets_light(self, field_names: tuple, custom_offsets=None, limit=None, **query):
"""
This is a dataset search function that returns the results as objects of a dynamically
generated Dataset class that is a subclass of tuple.
Only the requested fields will be returned together with related derived attributes as property functions
similer to the datacube.model.Dataset class. For example, if 'extent'is requested all of
'crs', 'extent', 'transform', and 'bounds' are available as property functions.
The field_names can be custom fields in addition to those specified in metadata_type, fixed fields, or
native fields. The field_names can also be derived fields like 'extent', 'crs', 'transform',
and 'bounds'. The custom fields require custom offsets of the metadata doc be provided.
The datasets can be selected based on values of custom fields as long as relevant custom
offsets are provided. However custom field values are not transformed so must match what is
stored in the database.
:param field_names: A tuple of field names that would be returned including derived fields
such as extent, crs
:param custom_offsets: A dictionary of offsets in the metadata doc for custom fields
:param limit: Number of datasets returned per product.
:param query: key, value mappings of query that will be processed against metadata_types,
product definitions and/or dataset table.
:return: A Dynamically generated DatasetLight (a subclass of namedtuple and possibly with
property functions).
"""
assert field_names
for product, query_exprs in self.make_query_expr(query, custom_offsets):
select_fields = self.make_select_fields(product, field_names, custom_offsets)
select_field_names = tuple(field.name for field in select_fields)
result_type = namedtuple('DatasetLight', select_field_names) # type: ignore
if 'grid_spatial' in select_field_names:
class DatasetLight(result_type, DatasetSpatialMixin):
pass
else:
class DatasetLight(result_type): # type: ignore
__slots__ = ()
with self._db.connect() as connection:
results = connection.search_unique_datasets(
query_exprs,
select_fields=select_fields,
limit=limit
)
for result in results:
field_values = dict()
for i_, field in enumerate(select_fields):
# We need to load the simple doc fields
if isinstance(field, SimpleDocField):
field_values[field.name] = json.loads(result[i_])
else:
field_values[field.name] = result[i_]
yield DatasetLight(**field_values) | [
"def",
"search_returning_datasets_light",
"(",
"self",
",",
"field_names",
":",
"tuple",
",",
"custom_offsets",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"*",
"*",
"query",
")",
":",
"assert",
"field_names",
"for",
"product",
",",
"query_exprs",
"in",
"se... | https://github.com/opendatacube/datacube-core/blob/b062184be61c140a168de94510bc3661748f112e/datacube/index/_datasets.py#L788-L846 | ||
clinton-hall/nzbToMedia | 27669389216902d1085660167e7bda0bd8527ecf | libs/common/beets/importer.py | python | ImportSession.already_merged | (self, paths) | return True | Returns true if all the paths being imported were part of a merge
during previous tasks. | Returns true if all the paths being imported were part of a merge
during previous tasks. | [
"Returns",
"true",
"if",
"all",
"the",
"paths",
"being",
"imported",
"were",
"part",
"of",
"a",
"merge",
"during",
"previous",
"tasks",
"."
] | def already_merged(self, paths):
"""Returns true if all the paths being imported were part of a merge
during previous tasks.
"""
for path in paths:
if path not in self._merged_items \
and path not in self._merged_dirs:
return False
return True | [
"def",
"already_merged",
"(",
"self",
",",
"paths",
")",
":",
"for",
"path",
"in",
"paths",
":",
"if",
"path",
"not",
"in",
"self",
".",
"_merged_items",
"and",
"path",
"not",
"in",
"self",
".",
"_merged_dirs",
":",
"return",
"False",
"return",
"True"
] | https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/beets/importer.py#L357-L365 | |
aio-libs/janus | 2b632eb4007e706ff120853f402fb9c33b227e1c | janus/__init__.py | python | _AsyncQueueProxy.maxsize | (self) | return self._parent._maxsize | Number of items allowed in the queue. | Number of items allowed in the queue. | [
"Number",
"of",
"items",
"allowed",
"in",
"the",
"queue",
"."
] | def maxsize(self) -> int:
"""Number of items allowed in the queue."""
return self._parent._maxsize | [
"def",
"maxsize",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"_parent",
".",
"_maxsize"
] | https://github.com/aio-libs/janus/blob/2b632eb4007e706ff120853f402fb9c33b227e1c/janus/__init__.py#L468-L470 | |
SteveDoyle2/pyNastran | eda651ac2d4883d95a34951f8a002ff94f642a1a | pyNastran/bdf/cards/materials.py | python | MAT3D.add_card | (cls, card, comment='') | return MAT3D(mid, e1, e2, e3, nu12, nu13, nu23, g12, g13, g23, rho, comment=comment) | Adds a MAT3D card from ``BDF.add_card(...)``
Parameters
----------
card : BDFCard()
a BDFCard object
comment : str; default=''
a comment for the card | Adds a MAT3D card from ``BDF.add_card(...)`` | [
"Adds",
"a",
"MAT3D",
"card",
"from",
"BDF",
".",
"add_card",
"(",
"...",
")"
] | def add_card(cls, card, comment=''):
"""
Adds a MAT3D card from ``BDF.add_card(...)``
Parameters
----------
card : BDFCard()
a BDFCard object
comment : str; default=''
a comment for the card
"""
mid = integer(card, 1, 'mid')
e1 = double(card, 2, 'E1')
e2 = double(card, 3, 'E2')
e3 = double(card, 4, 'E3')
nu12 = double(card, 5, 'nu12')
nu13 = double(card, 6, 'nu13')
nu23 = double(card, 7, 'nu23')
g12 = double(card, 8, 'g12')
g13 = double(card, 9, 'g13')
g23 = double(card, 10, 'g23')
rho = double_or_blank(card, 11, 'rho', 0.0)
assert len(card) <= 17, f'len(MAT3D card) = {len(card):d}\ncard={card}'
return MAT3D(mid, e1, e2, e3, nu12, nu13, nu23, g12, g13, g23, rho, comment=comment) | [
"def",
"add_card",
"(",
"cls",
",",
"card",
",",
"comment",
"=",
"''",
")",
":",
"mid",
"=",
"integer",
"(",
"card",
",",
"1",
",",
"'mid'",
")",
"e1",
"=",
"double",
"(",
"card",
",",
"2",
",",
"'E1'",
")",
"e2",
"=",
"double",
"(",
"card",
... | https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/bdf/cards/materials.py#L3105-L3129 | |
basho/riak-python-client | 91de13a16607cdf553d1a194e762734e3bec4231 | riak/bucket.py | python | RiakBucket.enable_search | (self) | return True | Enable search indexing for this bucket.
.. deprecated:: 2.1.0 (Riak 2.0)
Use :ref:`Riak Search 2.0 <yz-label>` instead. | Enable search indexing for this bucket. | [
"Enable",
"search",
"indexing",
"for",
"this",
"bucket",
"."
] | def enable_search(self):
"""
Enable search indexing for this bucket.
.. deprecated:: 2.1.0 (Riak 2.0)
Use :ref:`Riak Search 2.0 <yz-label>` instead.
"""
if not self.search_enabled():
self.set_property('search', True)
return True | [
"def",
"enable_search",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"search_enabled",
"(",
")",
":",
"self",
".",
"set_property",
"(",
"'search'",
",",
"True",
")",
"return",
"True"
] | https://github.com/basho/riak-python-client/blob/91de13a16607cdf553d1a194e762734e3bec4231/riak/bucket.py#L447-L456 | |
zopefoundation/Zope | ea04dd670d1a48d4d5c879d3db38fc2e9b4330bb | src/webdav/PropertySheets.py | python | xml_escape | (value) | return xmltools_escape(value) | [] | def xml_escape(value):
if not isinstance(value, (str, bytes)):
value = str(value)
if not isinstance(value, str):
value = value.decode('utf-8')
return xmltools_escape(value) | [
"def",
"xml_escape",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"str",
",",
"bytes",
")",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=... | https://github.com/zopefoundation/Zope/blob/ea04dd670d1a48d4d5c879d3db38fc2e9b4330bb/src/webdav/PropertySheets.py#L30-L35 | |||
TencentCloud/tencentcloud-sdk-python | 3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2 | tencentcloud/vod/v20180717/models.py | python | ModifyVodDomainConfigResponse.__init__ | (self) | r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str | r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str | [
"r",
":",
"param",
"RequestId",
":",
"唯一请求",
"ID,每次请求都会返回。定位问题时需要提供该次请求的",
"RequestId。",
":",
"type",
"RequestId",
":",
"str"
] | def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"RequestId",
"=",
"None"
] | https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/vod/v20180717/models.py#L16609-L16614 | ||
Source-Python-Dev-Team/Source.Python | d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb | addons/source-python/Python3/xml/etree/ElementTree.py | python | Element.makeelement | (self, tag, attrib) | return self.__class__(tag, attrib) | Create a new element with the same type.
*tag* is a string containing the element name.
*attrib* is a dictionary containing the element attributes.
Do not call this method, use the SubElement factory function instead. | Create a new element with the same type. | [
"Create",
"a",
"new",
"element",
"with",
"the",
"same",
"type",
"."
] | def makeelement(self, tag, attrib):
"""Create a new element with the same type.
*tag* is a string containing the element name.
*attrib* is a dictionary containing the element attributes.
Do not call this method, use the SubElement factory function instead.
"""
return self.__class__(tag, attrib) | [
"def",
"makeelement",
"(",
"self",
",",
"tag",
",",
"attrib",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"tag",
",",
"attrib",
")"
] | https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/xml/etree/ElementTree.py#L180-L189 | |
plotly/plotly.py | cfad7862594b35965c0e000813bd7805e8494a5b | packages/python/plotly/plotly/graph_objs/_heatmap.py | python | Heatmap.zhoverformat | (self) | return self["zhoverformat"] | Sets the hover text formatting rulefor `z` using d3 formatting
mini-languages which are very similar to those in Python. For
numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.By
default the values are formatted using generic number format.
The 'zhoverformat' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str | Sets the hover text formatting rulefor `z` using d3 formatting
mini-languages which are very similar to those in Python. For
numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.By
default the values are formatted using generic number format.
The 'zhoverformat' property is a string and must be specified as:
- A string
- A number that will be converted to a string | [
"Sets",
"the",
"hover",
"text",
"formatting",
"rulefor",
"z",
"using",
"d3",
"formatting",
"mini",
"-",
"languages",
"which",
"are",
"very",
"similar",
"to",
"those",
"in",
"Python",
".",
"For",
"numbers",
"see",
":",
"https",
":",
"//",
"github",
".",
"... | def zhoverformat(self):
"""
Sets the hover text formatting rulefor `z` using d3 formatting
mini-languages which are very similar to those in Python. For
numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.By
default the values are formatted using generic number format.
The 'zhoverformat' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["zhoverformat"] | [
"def",
"zhoverformat",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"zhoverformat\"",
"]"
] | https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/_heatmap.py#L1859-L1875 | |
microsoft/azure-devops-python-api | 451cade4c475482792cbe9e522c1fee32393139e | azure-devops/azure/devops/v5_1/graph/graph_client.py | python | GraphClient.get_user | (self, user_descriptor) | return self._deserialize('GraphUser', response) | GetUser.
[Preview API] Get a user by its descriptor.
:param str user_descriptor: The descriptor of the desired user.
:rtype: :class:`<GraphUser> <azure.devops.v5_1.graph.models.GraphUser>` | GetUser.
[Preview API] Get a user by its descriptor.
:param str user_descriptor: The descriptor of the desired user.
:rtype: :class:`<GraphUser> <azure.devops.v5_1.graph.models.GraphUser>` | [
"GetUser",
".",
"[",
"Preview",
"API",
"]",
"Get",
"a",
"user",
"by",
"its",
"descriptor",
".",
":",
"param",
"str",
"user_descriptor",
":",
"The",
"descriptor",
"of",
"the",
"desired",
"user",
".",
":",
"rtype",
":",
":",
"class",
":",
"<GraphUser",
"... | def get_user(self, user_descriptor):
"""GetUser.
[Preview API] Get a user by its descriptor.
:param str user_descriptor: The descriptor of the desired user.
:rtype: :class:`<GraphUser> <azure.devops.v5_1.graph.models.GraphUser>`
"""
route_values = {}
if user_descriptor is not None:
route_values['userDescriptor'] = self._serialize.url('user_descriptor', user_descriptor, 'str')
response = self._send(http_method='GET',
location_id='005e26ec-6b77-4e4f-a986-b3827bf241f5',
version='5.1-preview.1',
route_values=route_values)
return self._deserialize('GraphUser', response) | [
"def",
"get_user",
"(",
"self",
",",
"user_descriptor",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"user_descriptor",
"is",
"not",
"None",
":",
"route_values",
"[",
"'userDescriptor'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'user_descript... | https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/v5_1/graph/graph_client.py#L381-L394 | |
Tautulli/Tautulli | 2410eb33805aaac4bd1c5dad0f71e4f15afaf742 | lib/cherrypy/process/win32.py | python | Win32Bus.state | (self, value) | [] | def state(self, value):
self._state = value
event = self._get_state_event(value)
win32event.PulseEvent(event) | [
"def",
"state",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_state",
"=",
"value",
"event",
"=",
"self",
".",
"_get_state_event",
"(",
"value",
")",
"win32event",
".",
"PulseEvent",
"(",
"event",
")"
] | https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/cherrypy/process/win32.py#L98-L101 | ||||
rocky/python-decompile3 | 0229c442a707b2ee82e13486290111342873dc6e | decompyle3/semantics/fragments.py | python | FragmentsWalker.listcomprehension_walk2 | (self, node) | List comprehensions the way they are done in Python 2 (and
some Python 3?).
They're more other comprehensions, e.g. set comprehensions
See if we can combine code. | List comprehensions the way they are done in Python 2 (and
some Python 3?).
They're more other comprehensions, e.g. set comprehensions
See if we can combine code. | [
"List",
"comprehensions",
"the",
"way",
"they",
"are",
"done",
"in",
"Python",
"2",
"(",
"and",
"some",
"Python",
"3?",
")",
".",
"They",
"re",
"more",
"other",
"comprehensions",
"e",
".",
"g",
".",
"set",
"comprehensions",
"See",
"if",
"we",
"can",
"c... | def listcomprehension_walk2(self, node):
"""List comprehensions the way they are done in Python 2 (and
some Python 3?).
They're more other comprehensions, e.g. set comprehensions
See if we can combine code.
"""
p = self.prec
self.prec = 27
code = Code(node[1].attr, self.scanner, self.currentclass)
ast = self.build_ast(code._tokens, code._customize, code)
self.customize(code._customize)
if node == "set_comp":
ast = ast[0][0][0]
else:
ast = ast[0][0][0][0][0]
if ast == "expr":
ast = ast[0]
n = ast[1]
collection = node[-3]
list_if = None
assert n == "list_iter"
# Find the list comprehension body. It is the inner-most
# node that is not list_.. .
while n == "list_iter":
n = n[0] # recurse one step
if n == "list_for":
store = n[2]
n = n[3]
elif n in ("list_if", "list_if_not"):
# FIXME: just a guess
if n[0].kind == "expr":
list_if = n
else:
list_if = n[1]
n = n[2]
pass
pass
assert n == "lc_body", ast
self.preorder(n[0])
self.write(" for ")
start = len(self.f.getvalue())
self.preorder(store)
self.set_pos_info(store, start, len(self.f.getvalue()))
self.write(" in ")
start = len(self.f.getvalue())
node[-3].parent = node
self.preorder(collection)
self.set_pos_info(collection, start, len(self.f.getvalue()))
if list_if:
start = len(self.f.getvalue())
self.preorder(list_if)
self.set_pos_info(list_if, start, len(self.f.getvalue()))
self.prec = p | [
"def",
"listcomprehension_walk2",
"(",
"self",
",",
"node",
")",
":",
"p",
"=",
"self",
".",
"prec",
"self",
".",
"prec",
"=",
"27",
"code",
"=",
"Code",
"(",
"node",
"[",
"1",
"]",
".",
"attr",
",",
"self",
".",
"scanner",
",",
"self",
".",
"cur... | https://github.com/rocky/python-decompile3/blob/0229c442a707b2ee82e13486290111342873dc6e/decompyle3/semantics/fragments.py#L831-L890 | ||
aloyschen/tensorflow-yolo3 | 646f4532487ff728695c55fb3b9a29fcd631e68d | model/yolo3_model.py | python | yolo._yolo_block | (self, inputs, filters_num, out_filters, conv_index, training = True, norm_decay = 0.99, norm_epsilon = 1e-3) | return route, conv, conv_index | Introduction
------------
yolo3在Darknet53提取的特征层基础上,又加了针对3种不同比例的feature map的block,这样来提高对小物体的检测率
Parameters
----------
inputs: 输入特征
filters_num: 卷积核数量
out_filters: 最后输出层的卷积核数量
conv_index: 卷积层数序号,方便根据名字加载预训练权重
training: 是否为训练
norm_decay: 在预测时计算moving average时的衰减率
norm_epsilon: 方差加上极小的数,防止除以0的情况
Returns
-------
route: 返回最后一层卷积的前一层结果
conv: 返回最后一层卷积的结果
conv_index: conv层计数 | Introduction
------------
yolo3在Darknet53提取的特征层基础上,又加了针对3种不同比例的feature map的block,这样来提高对小物体的检测率
Parameters
----------
inputs: 输入特征
filters_num: 卷积核数量
out_filters: 最后输出层的卷积核数量
conv_index: 卷积层数序号,方便根据名字加载预训练权重
training: 是否为训练
norm_decay: 在预测时计算moving average时的衰减率
norm_epsilon: 方差加上极小的数,防止除以0的情况
Returns
-------
route: 返回最后一层卷积的前一层结果
conv: 返回最后一层卷积的结果
conv_index: conv层计数 | [
"Introduction",
"------------",
"yolo3在Darknet53提取的特征层基础上,又加了针对3种不同比例的feature",
"map的block,这样来提高对小物体的检测率",
"Parameters",
"----------",
"inputs",
":",
"输入特征",
"filters_num",
":",
"卷积核数量",
"out_filters",
":",
"最后输出层的卷积核数量",
"conv_index",
":",
"卷积层数序号,方便根据名字加载预训练权重",
"training",
"... | def _yolo_block(self, inputs, filters_num, out_filters, conv_index, training = True, norm_decay = 0.99, norm_epsilon = 1e-3):
"""
Introduction
------------
yolo3在Darknet53提取的特征层基础上,又加了针对3种不同比例的feature map的block,这样来提高对小物体的检测率
Parameters
----------
inputs: 输入特征
filters_num: 卷积核数量
out_filters: 最后输出层的卷积核数量
conv_index: 卷积层数序号,方便根据名字加载预训练权重
training: 是否为训练
norm_decay: 在预测时计算moving average时的衰减率
norm_epsilon: 方差加上极小的数,防止除以0的情况
Returns
-------
route: 返回最后一层卷积的前一层结果
conv: 返回最后一层卷积的结果
conv_index: conv层计数
"""
conv = self._conv2d_layer(inputs, filters_num = filters_num, kernel_size = 1, strides = 1, name = "conv2d_" + str(conv_index))
conv = self._batch_normalization_layer(conv, name = "batch_normalization_" + str(conv_index), training = training, norm_decay = norm_decay, norm_epsilon = norm_epsilon)
conv_index += 1
conv = self._conv2d_layer(conv, filters_num = filters_num * 2, kernel_size = 3, strides = 1, name = "conv2d_" + str(conv_index))
conv = self._batch_normalization_layer(conv, name = "batch_normalization_" + str(conv_index), training = training, norm_decay = norm_decay, norm_epsilon = norm_epsilon)
conv_index += 1
conv = self._conv2d_layer(conv, filters_num = filters_num, kernel_size = 1, strides = 1, name = "conv2d_" + str(conv_index))
conv = self._batch_normalization_layer(conv, name = "batch_normalization_" + str(conv_index), training = training, norm_decay = norm_decay, norm_epsilon = norm_epsilon)
conv_index += 1
conv = self._conv2d_layer(conv, filters_num = filters_num * 2, kernel_size = 3, strides = 1, name = "conv2d_" + str(conv_index))
conv = self._batch_normalization_layer(conv, name = "batch_normalization_" + str(conv_index), training = training, norm_decay = norm_decay, norm_epsilon = norm_epsilon)
conv_index += 1
conv = self._conv2d_layer(conv, filters_num = filters_num, kernel_size = 1, strides = 1, name = "conv2d_" + str(conv_index))
conv = self._batch_normalization_layer(conv, name = "batch_normalization_" + str(conv_index), training = training, norm_decay = norm_decay, norm_epsilon = norm_epsilon)
conv_index += 1
route = conv
conv = self._conv2d_layer(conv, filters_num = filters_num * 2, kernel_size = 3, strides = 1, name = "conv2d_" + str(conv_index))
conv = self._batch_normalization_layer(conv, name = "batch_normalization_" + str(conv_index), training = training, norm_decay = norm_decay, norm_epsilon = norm_epsilon)
conv_index += 1
conv = self._conv2d_layer(conv, filters_num = out_filters, kernel_size = 1, strides = 1, name = "conv2d_" + str(conv_index), use_bias = True)
conv_index += 1
return route, conv, conv_index | [
"def",
"_yolo_block",
"(",
"self",
",",
"inputs",
",",
"filters_num",
",",
"out_filters",
",",
"conv_index",
",",
"training",
"=",
"True",
",",
"norm_decay",
"=",
"0.99",
",",
"norm_epsilon",
"=",
"1e-3",
")",
":",
"conv",
"=",
"self",
".",
"_conv2d_layer"... | https://github.com/aloyschen/tensorflow-yolo3/blob/646f4532487ff728695c55fb3b9a29fcd631e68d/model/yolo3_model.py#L183-L224 | |
dbt-labs/dbt-core | e943b9fc842535e958ef4fd0b8703adc91556bc6 | core/dbt/context/providers.py | python | TestContext.env_var | (self, var: str, default: Optional[str] = None) | [] | def env_var(self, var: str, default: Optional[str] = None) -> str:
return_value = None
if var.startswith(SECRET_ENV_PREFIX):
disallow_secret_env_var(var)
if var in os.environ:
return_value = os.environ[var]
elif default is not None:
return_value = default
if return_value is not None:
# Save the env_var value in the manifest and the var name in the source_file
if self.model:
self.manifest.env_vars[var] = return_value
# the "model" should only be test nodes, but just in case, check
if self.model.resource_type == NodeType.Test and self.model.file_key_name:
source_file = self.manifest.files[self.model.file_id]
(yaml_key, name) = self.model.file_key_name.split('.')
source_file.add_env_var(var, yaml_key, name)
return return_value
else:
msg = f"Env var required but not provided: '{var}'"
raise_parsing_error(msg) | [
"def",
"env_var",
"(",
"self",
",",
"var",
":",
"str",
",",
"default",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"str",
":",
"return_value",
"=",
"None",
"if",
"var",
".",
"startswith",
"(",
"SECRET_ENV_PREFIX",
")",
":",
"disallow_secr... | https://github.com/dbt-labs/dbt-core/blob/e943b9fc842535e958ef4fd0b8703adc91556bc6/core/dbt/context/providers.py#L1486-L1507 | ||||
trevp/tlslite | cd82fadb6bb958522b7457c5ed95890283437a4f | tlslite/tlsrecordlayer.py | python | TLSRecordLayer.getsockname | (self) | return self.sock.getsockname() | Return the socket's own address (socket emulation). | Return the socket's own address (socket emulation). | [
"Return",
"the",
"socket",
"s",
"own",
"address",
"(",
"socket",
"emulation",
")",
"."
] | def getsockname(self):
"""Return the socket's own address (socket emulation)."""
return self.sock.getsockname() | [
"def",
"getsockname",
"(",
"self",
")",
":",
"return",
"self",
".",
"sock",
".",
"getsockname",
"(",
")"
] | https://github.com/trevp/tlslite/blob/cd82fadb6bb958522b7457c5ed95890283437a4f/tlslite/tlsrecordlayer.py#L475-L477 | |
DebPanigrahi/Machine-Learning | 6456d752a4aeae2317eb4da0469f9266cf9e158b | ml_algo.py | python | Performance.__init__ | (self, classifier, **kwargs) | return | [] | def __init__(self, classifier, **kwargs):
self.confusion_matrix = {}
for lc in classifier.data.label_categories:
z = zeros((len(classifier.data.class_labels[lc]), len(classifier.data.class_labels[lc])), dtype=int)
self.confusion_matrix[lc] = pd.DataFrame(z, index=classifier.data.class_labels[lc], columns=classifier.data.class_labels[lc], dtype=int)
if 'data' in kwargs:
Xs = kwargs['data']
Ys = kwargs['Y']
else:
Xs = classifier.data.Xs
Ys = classifier.data.Ys
for i, X in Xs.iterrows():
if 'adaboost' in kwargs:
adaboost = kwargs['adaboost']
classified_label, probability = classifier.classify(X, adaboost=kwargs['adaboost'])
for lc in classifier.data.label_categories:
true_label = Ys[lc][i]
self.confusion_matrix[lc][classified_label[lc]][true_label] += 1
self.performance_matrix = {}
for lc in classifier.data.label_categories:
performance_matrix = pd.DataFrame(index=classifier.data.class_labels[lc],
columns=['ppv', 'accuracy', 'sensitivity', 'specificity'])
detected = self.confusion_matrix[lc].sum()
true = self.confusion_matrix[lc].sum(axis=1)
total = array(self.confusion_matrix[lc]).sum()
TP = correctly_detected = diagonal(self.confusion_matrix[lc])
TN = total - true - detected + correctly_detected
FP = detected - correctly_detected
FN = true - correctly_detected
performance_matrix['ppv'] = positive_predictive_value = TP/(TP+FP)
performance_matrix['accuracy'] = (TP+TN)/total
performance_matrix['sensitivity'] = TP/(TP+FN)
performance_matrix['specificity'] = TN/(TN+FP)
self.performance_matrix[lc] = performance_matrix
return | [
"def",
"__init__",
"(",
"self",
",",
"classifier",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"confusion_matrix",
"=",
"{",
"}",
"for",
"lc",
"in",
"classifier",
".",
"data",
".",
"label_categories",
":",
"z",
"=",
"zeros",
"(",
"(",
"len",
"(",... | https://github.com/DebPanigrahi/Machine-Learning/blob/6456d752a4aeae2317eb4da0469f9266cf9e158b/ml_algo.py#L507-L546 | |||
NervanaSystems/ngraph-python | ac032c83c7152b615a9ad129d54d350f9d6a2986 | ngraph/op_graph/op_graph.py | python | AssignableTensorOp.add_control_dep | (self, op) | Allocations happen before executed ops, so all_deps are ignored.
Args:
op:
Returns: | Allocations happen before executed ops, so all_deps are ignored. | [
"Allocations",
"happen",
"before",
"executed",
"ops",
"so",
"all_deps",
"are",
"ignored",
"."
] | def add_control_dep(self, op):
"""
Allocations happen before executed ops, so all_deps are ignored.
Args:
op:
Returns:
"""
pass | [
"def",
"add_control_dep",
"(",
"self",
",",
"op",
")",
":",
"pass"
] | https://github.com/NervanaSystems/ngraph-python/blob/ac032c83c7152b615a9ad129d54d350f9d6a2986/ngraph/op_graph/op_graph.py#L2399-L2409 | ||
michael-lazar/rtv | b3d5bf16a70dba685e05db35308cc8a6d2b7f7aa | rtv/packages/praw/__init__.py | python | BaseReddit.request | (self, url, params=None, data=None, retry_on_error=True,
method=None) | return self._request(url, params, data, raw_response=True,
retry_on_error=retry_on_error, method=method) | Make a HTTP request and return the response.
:param url: the url to grab content from.
:param params: a dictionary containing the GET data to put in the url
:param data: a dictionary containing the extra data to submit
:param retry_on_error: if True retry the request, if it fails, for up
to 3 attempts
:param method: The HTTP method to use in the request.
:returns: The HTTP response. | Make a HTTP request and return the response. | [
"Make",
"a",
"HTTP",
"request",
"and",
"return",
"the",
"response",
"."
] | def request(self, url, params=None, data=None, retry_on_error=True,
method=None):
"""Make a HTTP request and return the response.
:param url: the url to grab content from.
:param params: a dictionary containing the GET data to put in the url
:param data: a dictionary containing the extra data to submit
:param retry_on_error: if True retry the request, if it fails, for up
to 3 attempts
:param method: The HTTP method to use in the request.
:returns: The HTTP response.
"""
return self._request(url, params, data, raw_response=True,
retry_on_error=retry_on_error, method=method) | [
"def",
"request",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"retry_on_error",
"=",
"True",
",",
"method",
"=",
"None",
")",
":",
"return",
"self",
".",
"_request",
"(",
"url",
",",
"params",
",",
"data",
",... | https://github.com/michael-lazar/rtv/blob/b3d5bf16a70dba685e05db35308cc8a6d2b7f7aa/rtv/packages/praw/__init__.py#L588-L601 | |
kellyjonbrazil/jc | e6900e2000bf265dfcfc09ffbfda39e9238661af | jc/parsers/finger.py | python | parse | (data, raw=False, quiet=False) | Main text parsing function
Parameters:
data: (string) text data to parse
raw: (boolean) output preprocessed JSON if True
quiet: (boolean) suppress warning messages if True
Returns:
List of Dictionaries. Raw or processed structured data. | Main text parsing function | [
"Main",
"text",
"parsing",
"function"
] | def parse(data, raw=False, quiet=False):
"""
Main text parsing function
Parameters:
data: (string) text data to parse
raw: (boolean) output preprocessed JSON if True
quiet: (boolean) suppress warning messages if True
Returns:
List of Dictionaries. Raw or processed structured data.
"""
jc.utils.compatibility(__name__, info.compatible, quiet)
jc.utils.input_type_check(data)
raw_output = []
if jc.utils.has_data(data):
# Finger output is an abomination that is nearly unparsable. But there is a way:
# First find the location of the last character of 'Idle' in the table and cut
# all lines at that spot. Data before that spot can use the unviversal.sparse_table_parse function.
# All data after that spot can be run through regex to find the login datetime and possibly
# other fields.
data_lines = list(filter(None, data.splitlines()))
sep_col = data_lines[0].find('Idle') + 4
first_half = []
second_half = []
for line in data_lines:
first_half.append(line[:sep_col])
second_half.append(line[sep_col:])
first_half[0] = first_half[0].lower()
# parse the first half
raw_output = jc.parsers.universal.sparse_table_parse(first_half)
# use regex to get login datetime and 'other' data
pattern = re.compile(r'([A-Z][a-z]{2}\s+\d{1,2}\s+)(\d\d:\d\d|\d{4})(\s?.+)?$')
# remove header row from list
second_half.pop(0)
for index, line in enumerate(second_half):
dt = re.search(pattern, line)
if dt:
if dt.group(1) and dt.group(2):
raw_output[index]['login_time'] = dt.group(1).strip() + ' ' + dt.group(2).strip()
if dt.group(3):
raw_output[index]['details'] = dt.group(3).strip()
if raw:
return raw_output
else:
return _process(raw_output) | [
"def",
"parse",
"(",
"data",
",",
"raw",
"=",
"False",
",",
"quiet",
"=",
"False",
")",
":",
"jc",
".",
"utils",
".",
"compatibility",
"(",
"__name__",
",",
"info",
".",
"compatible",
",",
"quiet",
")",
"jc",
".",
"utils",
".",
"input_type_check",
"(... | https://github.com/kellyjonbrazil/jc/blob/e6900e2000bf265dfcfc09ffbfda39e9238661af/jc/parsers/finger.py#L157-L214 | ||
pytorch/fairseq | 1575f30dd0a9f7b3c499db0b4767aa4e9f79056c | fairseq/file_utils.py | python | url_to_filename | (url, etag=None) | return filename | Convert `url` into a hashed filename in a repeatable way.
If `etag` is specified, append its hash to the URL's, delimited
by a period. | Convert `url` into a hashed filename in a repeatable way.
If `etag` is specified, append its hash to the URL's, delimited
by a period. | [
"Convert",
"url",
"into",
"a",
"hashed",
"filename",
"in",
"a",
"repeatable",
"way",
".",
"If",
"etag",
"is",
"specified",
"append",
"its",
"hash",
"to",
"the",
"URL",
"s",
"delimited",
"by",
"a",
"period",
"."
] | def url_to_filename(url, etag=None):
"""
Convert `url` into a hashed filename in a repeatable way.
If `etag` is specified, append its hash to the URL's, delimited
by a period.
"""
url_bytes = url.encode("utf-8")
url_hash = sha256(url_bytes)
filename = url_hash.hexdigest()
if etag:
etag_bytes = etag.encode("utf-8")
etag_hash = sha256(etag_bytes)
filename += "." + etag_hash.hexdigest()
return filename | [
"def",
"url_to_filename",
"(",
"url",
",",
"etag",
"=",
"None",
")",
":",
"url_bytes",
"=",
"url",
".",
"encode",
"(",
"\"utf-8\"",
")",
"url_hash",
"=",
"sha256",
"(",
"url_bytes",
")",
"filename",
"=",
"url_hash",
".",
"hexdigest",
"(",
")",
"if",
"e... | https://github.com/pytorch/fairseq/blob/1575f30dd0a9f7b3c499db0b4767aa4e9f79056c/fairseq/file_utils.py#L98-L113 | |
jceb/vim-orgmode | 7882e202a3115a07be5300fd596194c94d622911 | ftplugin/orgmode/plugins/TagsProperties.py | python | TagsProperties.set_tags | (cls) | return u'OrgSetTags' | u""" Set tags for current heading | u""" Set tags for current heading | [
"u",
"Set",
"tags",
"for",
"current",
"heading"
] | def set_tags(cls):
u""" Set tags for current heading
"""
d = ORGMODE.get_document()
heading = d.current_heading()
if not heading:
return
# retrieve tags
res = None
if heading.tags:
res = vim.eval(u'input("Tags: ", ":%s:", "customlist,Org_complete_tags")' % u':'.join(heading.tags))
else:
res = vim.eval(u'input("Tags: ", "", "customlist,Org_complete_tags")')
if res is None:
# user pressed <Esc> abort any further processing
return
# remove empty tags
heading.tags = [x for x in u_decode(res).strip().strip(u':').split(u':') if x.strip() != u'']
d.write()
return u'OrgSetTags' | [
"def",
"set_tags",
"(",
"cls",
")",
":",
"d",
"=",
"ORGMODE",
".",
"get_document",
"(",
")",
"heading",
"=",
"d",
".",
"current_heading",
"(",
")",
"if",
"not",
"heading",
":",
"return",
"# retrieve tags",
"res",
"=",
"None",
"if",
"heading",
".",
"tag... | https://github.com/jceb/vim-orgmode/blob/7882e202a3115a07be5300fd596194c94d622911/ftplugin/orgmode/plugins/TagsProperties.py#L76-L100 | |
psychopy/psychopy | 01b674094f38d0e0bd51c45a6f66f671d7041696 | psychopy/app/plugin_manager/__init__.py | python | PluginManagerFrame.onItemSelected | (self, evt=None) | Event handler for when an item is selected. | Event handler for when an item is selected. | [
"Event",
"handler",
"for",
"when",
"an",
"item",
"is",
"selected",
"."
] | def onItemSelected(self, evt=None):
"""Event handler for when an item is selected."""
self.selectedItem = self.lstPlugins.GetFirstSelected()
if self.lstPlugins.selectedItem != -1:
self.cmdEntryPoints.Enable()
else:
self.cmdEntryPoints.Disable() | [
"def",
"onItemSelected",
"(",
"self",
",",
"evt",
"=",
"None",
")",
":",
"self",
".",
"selectedItem",
"=",
"self",
".",
"lstPlugins",
".",
"GetFirstSelected",
"(",
")",
"if",
"self",
".",
"lstPlugins",
".",
"selectedItem",
"!=",
"-",
"1",
":",
"self",
... | https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/app/plugin_manager/__init__.py#L461-L467 | ||
proofit404/dependencies | 204e0cfadca801d64857f24aa4c74e7939ed9af0 | src/_dependencies/injector.py | python | _check_inheritance | (bases) | [] | def _check_inheritance(bases):
for base in bases:
if not issubclass(base, Injector):
message = "Multiple inheritance is allowed for Injector subclasses only"
raise DependencyError(message) | [
"def",
"_check_inheritance",
"(",
"bases",
")",
":",
"for",
"base",
"in",
"bases",
":",
"if",
"not",
"issubclass",
"(",
"base",
",",
"Injector",
")",
":",
"message",
"=",
"\"Multiple inheritance is allowed for Injector subclasses only\"",
"raise",
"DependencyError",
... | https://github.com/proofit404/dependencies/blob/204e0cfadca801d64857f24aa4c74e7939ed9af0/src/_dependencies/injector.py#L64-L68 | ||||
openstack/magnum | fa298eeab19b1d87070d72c7c4fb26cd75b0781e | magnum/db/sqlalchemy/alembic/versions/2ace4006498_rename_bay_minions_address.py | python | upgrade | () | [] | def upgrade():
op.alter_column('bay', 'minions_address',
new_column_name='node_addresses',
existing_type=models.JSONEncodedList()) | [
"def",
"upgrade",
"(",
")",
":",
"op",
".",
"alter_column",
"(",
"'bay'",
",",
"'minions_address'",
",",
"new_column_name",
"=",
"'node_addresses'",
",",
"existing_type",
"=",
"models",
".",
"JSONEncodedList",
"(",
")",
")"
] | https://github.com/openstack/magnum/blob/fa298eeab19b1d87070d72c7c4fb26cd75b0781e/magnum/db/sqlalchemy/alembic/versions/2ace4006498_rename_bay_minions_address.py#L29-L32 | ||||
danecjensen/subscribely | 4d6ac60358b5fe26f0c01be68f1ba063df3b1ea0 | src/flask/wrappers.py | python | Request.on_json_loading_failed | (self, e) | Called if decoding of the JSON data failed. The return value of
this method is used by :attr:`json` when an error ocurred. The
default implementation raises a :class:`~werkzeug.exceptions.BadRequest`.
.. versionadded:: 0.8 | Called if decoding of the JSON data failed. The return value of
this method is used by :attr:`json` when an error ocurred. The
default implementation raises a :class:`~werkzeug.exceptions.BadRequest`. | [
"Called",
"if",
"decoding",
"of",
"the",
"JSON",
"data",
"failed",
".",
"The",
"return",
"value",
"of",
"this",
"method",
"is",
"used",
"by",
":",
"attr",
":",
"json",
"when",
"an",
"error",
"ocurred",
".",
"The",
"default",
"implementation",
"raises",
"... | def on_json_loading_failed(self, e):
"""Called if decoding of the JSON data failed. The return value of
this method is used by :attr:`json` when an error ocurred. The
default implementation raises a :class:`~werkzeug.exceptions.BadRequest`.
.. versionadded:: 0.8
"""
raise BadRequest() | [
"def",
"on_json_loading_failed",
"(",
"self",
",",
"e",
")",
":",
"raise",
"BadRequest",
"(",
")"
] | https://github.com/danecjensen/subscribely/blob/4d6ac60358b5fe26f0c01be68f1ba063df3b1ea0/src/flask/wrappers.py#L109-L116 | ||
html5lib/html5lib-python | f7cab6f019ce94a1ec0192b6ff29aaebaf10b50d | html5lib/html5parser.py | python | parse | (doc, treebuilder="etree", namespaceHTMLElements=True, **kwargs) | return p.parse(doc, **kwargs) | Parse an HTML document as a string or file-like object into a tree
:arg doc: the document to parse as a string or file-like object
:arg treebuilder: the treebuilder to use when parsing
:arg namespaceHTMLElements: whether or not to namespace HTML elements
:returns: parsed tree
Example:
>>> from html5lib.html5parser import parse
>>> parse('<html><body><p>This is a doc</p></body></html>')
<Element u'{http://www.w3.org/1999/xhtml}html' at 0x7feac4909db0> | Parse an HTML document as a string or file-like object into a tree | [
"Parse",
"an",
"HTML",
"document",
"as",
"a",
"string",
"or",
"file",
"-",
"like",
"object",
"into",
"a",
"tree"
] | def parse(doc, treebuilder="etree", namespaceHTMLElements=True, **kwargs):
"""Parse an HTML document as a string or file-like object into a tree
:arg doc: the document to parse as a string or file-like object
:arg treebuilder: the treebuilder to use when parsing
:arg namespaceHTMLElements: whether or not to namespace HTML elements
:returns: parsed tree
Example:
>>> from html5lib.html5parser import parse
>>> parse('<html><body><p>This is a doc</p></body></html>')
<Element u'{http://www.w3.org/1999/xhtml}html' at 0x7feac4909db0>
"""
tb = treebuilders.getTreeBuilder(treebuilder)
p = HTMLParser(tb, namespaceHTMLElements=namespaceHTMLElements)
return p.parse(doc, **kwargs) | [
"def",
"parse",
"(",
"doc",
",",
"treebuilder",
"=",
"\"etree\"",
",",
"namespaceHTMLElements",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"tb",
"=",
"treebuilders",
".",
"getTreeBuilder",
"(",
"treebuilder",
")",
"p",
"=",
"HTMLParser",
"(",
"tb",
... | https://github.com/html5lib/html5lib-python/blob/f7cab6f019ce94a1ec0192b6ff29aaebaf10b50d/html5lib/html5parser.py#L26-L46 | |
TengXiaoDai/DistributedCrawling | f5c2439e6ce68dd9b49bde084d76473ff9ed4963 | Lib/site-packages/pip/_vendor/distro.py | python | distro_release_attr | (attribute) | return _distro.distro_release_attr(attribute) | Return a single named information item from the distro release file
data source of the current Linux distribution.
Parameters:
* ``attribute`` (string): Key of the information item.
Returns:
* (string): Value of the information item, if the item exists.
The empty string, if the item does not exist.
See `distro release file`_ for details about these information items. | Return a single named information item from the distro release file
data source of the current Linux distribution. | [
"Return",
"a",
"single",
"named",
"information",
"item",
"from",
"the",
"distro",
"release",
"file",
"data",
"source",
"of",
"the",
"current",
"Linux",
"distribution",
"."
] | def distro_release_attr(attribute):
"""
Return a single named information item from the distro release file
data source of the current Linux distribution.
Parameters:
* ``attribute`` (string): Key of the information item.
Returns:
* (string): Value of the information item, if the item exists.
The empty string, if the item does not exist.
See `distro release file`_ for details about these information items.
"""
return _distro.distro_release_attr(attribute) | [
"def",
"distro_release_attr",
"(",
"attribute",
")",
":",
"return",
"_distro",
".",
"distro_release_attr",
"(",
"attribute",
")"
] | https://github.com/TengXiaoDai/DistributedCrawling/blob/f5c2439e6ce68dd9b49bde084d76473ff9ed4963/Lib/site-packages/pip/_vendor/distro.py#L493-L509 | |
materialsproject/pymatgen | 8128f3062a334a2edd240e4062b5b9bdd1ae6f58 | pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py | python | AbstractChemenvAlgorithm.as_dict | (self) | A JSON serializable dict representation of the algorithm | A JSON serializable dict representation of the algorithm | [
"A",
"JSON",
"serializable",
"dict",
"representation",
"of",
"the",
"algorithm"
] | def as_dict(self):
"""
A JSON serializable dict representation of the algorithm
"""
pass | [
"def",
"as_dict",
"(",
"self",
")",
":",
"pass"
] | https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py#L55-L59 | ||
mozillazg/pypy | 2ff5cd960c075c991389f842c6d59e71cf0cb7d0 | lib-python/2.7/pipes.py | python | Template.open | (self, file, rw) | t.open(file, rw) returns a pipe or file object open for
reading or writing; the file is the other end of the pipeline. | t.open(file, rw) returns a pipe or file object open for
reading or writing; the file is the other end of the pipeline. | [
"t",
".",
"open",
"(",
"file",
"rw",
")",
"returns",
"a",
"pipe",
"or",
"file",
"object",
"open",
"for",
"reading",
"or",
"writing",
";",
"the",
"file",
"is",
"the",
"other",
"end",
"of",
"the",
"pipeline",
"."
] | def open(self, file, rw):
"""t.open(file, rw) returns a pipe or file object open for
reading or writing; the file is the other end of the pipeline."""
if rw == 'r':
return self.open_r(file)
if rw == 'w':
return self.open_w(file)
raise ValueError, \
'Template.open: rw must be \'r\' or \'w\', not %r' % (rw,) | [
"def",
"open",
"(",
"self",
",",
"file",
",",
"rw",
")",
":",
"if",
"rw",
"==",
"'r'",
":",
"return",
"self",
".",
"open_r",
"(",
"file",
")",
"if",
"rw",
"==",
"'w'",
":",
"return",
"self",
".",
"open_w",
"(",
"file",
")",
"raise",
"ValueError",... | https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/pipes.py#L152-L160 | ||
makerbot/ReplicatorG | d6f2b07785a5a5f1e172fb87cb4303b17c575d5d | skein_engines/skeinforge-50/skeinforge_application/skeinforge_plugins/craft_plugins/chamber.py | python | ChamberRepository.execute | (self) | Chamber button has been clicked. | Chamber button has been clicked. | [
"Chamber",
"button",
"has",
"been",
"clicked",
"."
] | def execute(self):
"Chamber button has been clicked."
fileNames = skeinforge_polyfile.getFileOrDirectoryTypesUnmodifiedGcode(self.fileNameInput.value, fabmetheus_interpret.getImportPluginFileNames(), self.fileNameInput.wasCancelled)
for fileName in fileNames:
writeOutput(fileName) | [
"def",
"execute",
"(",
"self",
")",
":",
"fileNames",
"=",
"skeinforge_polyfile",
".",
"getFileOrDirectoryTypesUnmodifiedGcode",
"(",
"self",
".",
"fileNameInput",
".",
"value",
",",
"fabmetheus_interpret",
".",
"getImportPluginFileNames",
"(",
")",
",",
"self",
"."... | https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-50/skeinforge_application/skeinforge_plugins/craft_plugins/chamber.py#L223-L227 | ||
Cimbali/pympress | d376c92ede603a305738bd38f0c50b2f68c58fcf | pympress/talk_time.py | python | TimeCounter.reset_timer | (self, *args) | Reset the timer. | Reset the timer. | [
"Reset",
"the",
"timer",
"."
] | def reset_timer(self, *args):
""" Reset the timer.
"""
self.timing_tracker.reset(self.current_time())
self.restart_time = time.time()
self.elapsed_time = 0
if self.autoplay.is_looping():
self.autoplay.start_looping()
self.update_time() | [
"def",
"reset_timer",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"timing_tracker",
".",
"reset",
"(",
"self",
".",
"current_time",
"(",
")",
")",
"self",
".",
"restart_time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"elapsed_time",
... | https://github.com/Cimbali/pympress/blob/d376c92ede603a305738bd38f0c50b2f68c58fcf/pympress/talk_time.py#L250-L259 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_hxb2/lib/python3.5/site-packages/rest_framework/serializers.py | python | ListSerializer.data | (self) | return ReturnList(ret, serializer=self) | [] | def data(self):
ret = super(ListSerializer, self).data
return ReturnList(ret, serializer=self) | [
"def",
"data",
"(",
"self",
")",
":",
"ret",
"=",
"super",
"(",
"ListSerializer",
",",
"self",
")",
".",
"data",
"return",
"ReturnList",
"(",
"ret",
",",
"serializer",
"=",
"self",
")"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/rest_framework/serializers.py#L738-L740 | |||
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/full/lib2to3/fixer_util.py | python | is_import | (node) | return node.type in (syms.import_name, syms.import_from) | Returns true if the node is an import statement. | Returns true if the node is an import statement. | [
"Returns",
"true",
"if",
"the",
"node",
"is",
"an",
"import",
"statement",
"."
] | def is_import(node):
"""Returns true if the node is an import statement."""
return node.type in (syms.import_name, syms.import_from) | [
"def",
"is_import",
"(",
"node",
")",
":",
"return",
"node",
".",
"type",
"in",
"(",
"syms",
".",
"import_name",
",",
"syms",
".",
"import_from",
")"
] | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/lib2to3/fixer_util.py#L311-L313 | |
docker/docker-py | a48a5a9647761406d66e8271f19fab7fa0c5f582 | docker/models/plugins.py | python | PluginCollection.get | (self, name) | return self.prepare_model(self.client.api.inspect_plugin(name)) | Gets a plugin.
Args:
name (str): The name of the plugin.
Returns:
(:py:class:`Plugin`): The plugin.
Raises:
:py:class:`docker.errors.NotFound` If the plugin does not
exist.
:py:class:`docker.errors.APIError`
If the server returns an error. | Gets a plugin. | [
"Gets",
"a",
"plugin",
"."
] | def get(self, name):
"""
Gets a plugin.
Args:
name (str): The name of the plugin.
Returns:
(:py:class:`Plugin`): The plugin.
Raises:
:py:class:`docker.errors.NotFound` If the plugin does not
exist.
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
return self.prepare_model(self.client.api.inspect_plugin(name)) | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"prepare_model",
"(",
"self",
".",
"client",
".",
"api",
".",
"inspect_plugin",
"(",
"name",
")",
")"
] | https://github.com/docker/docker-py/blob/a48a5a9647761406d66e8271f19fab7fa0c5f582/docker/models/plugins.py#L145-L161 | |
blampe/IbPy | cba912d2ecc669b0bf2980357ea7942e49c0825e | ib/ext/EReader.py | python | EReader.parent | (self) | return self.m_parent | generated source for method parent | generated source for method parent | [
"generated",
"source",
"for",
"method",
"parent"
] | def parent(self):
""" generated source for method parent """
return self.m_parent | [
"def",
"parent",
"(",
"self",
")",
":",
"return",
"self",
".",
"m_parent"
] | https://github.com/blampe/IbPy/blob/cba912d2ecc669b0bf2980357ea7942e49c0825e/ib/ext/EReader.py#L82-L84 | |
Esri/ArcREST | ab240fde2b0200f61d4a5f6df033516e53f2f416 | src/arcrest/manageags/_clusters.py | python | Cluster.machineNames | (self) | return self._machineNames | returns a list of machines in cluster | returns a list of machines in cluster | [
"returns",
"a",
"list",
"of",
"machines",
"in",
"cluster"
] | def machineNames(self):
"""returns a list of machines in cluster"""
if self._machineNames is None:
self.__init()
return self._machineNames | [
"def",
"machineNames",
"(",
"self",
")",
":",
"if",
"self",
".",
"_machineNames",
"is",
"None",
":",
"self",
".",
"__init",
"(",
")",
"return",
"self",
".",
"_machineNames"
] | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageags/_clusters.py#L225-L229 | |
ionelmc/python-hunter | 4e4064bf5bf30ecd1fa69abb1b6b5df8b8b66b45 | src/hunter/predicates.py | python | Query.__and__ | (self, other) | return And(self, other) | Convenience API so you can do ``Query(...) & Query(...)``. It converts that to ``And(Query(...), Query(...))``. | Convenience API so you can do ``Query(...) & Query(...)``. It converts that to ``And(Query(...), Query(...))``. | [
"Convenience",
"API",
"so",
"you",
"can",
"do",
"Query",
"(",
"...",
")",
"&",
"Query",
"(",
"...",
")",
".",
"It",
"converts",
"that",
"to",
"And",
"(",
"Query",
"(",
"...",
")",
"Query",
"(",
"...",
"))",
"."
] | def __and__(self, other):
"""
Convenience API so you can do ``Query(...) & Query(...)``. It converts that to ``And(Query(...), Query(...))``.
"""
return And(self, other) | [
"def",
"__and__",
"(",
"self",
",",
"other",
")",
":",
"return",
"And",
"(",
"self",
",",
"other",
")"
] | https://github.com/ionelmc/python-hunter/blob/4e4064bf5bf30ecd1fa69abb1b6b5df8b8b66b45/src/hunter/predicates.py#L240-L244 | |
celery/py-amqp | 557d98a7d27e171ce7b22e2e3a56baf805ad8e52 | amqp/utils.py | python | str_to_bytes | (s) | return s | Convert str to bytes. | Convert str to bytes. | [
"Convert",
"str",
"to",
"bytes",
"."
] | def str_to_bytes(s):
"""Convert str to bytes."""
if isinstance(s, str):
return s.encode('utf-8', 'surrogatepass')
return s | [
"def",
"str_to_bytes",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"return",
"s",
".",
"encode",
"(",
"'utf-8'",
",",
"'surrogatepass'",
")",
"return",
"s"
] | https://github.com/celery/py-amqp/blob/557d98a7d27e171ce7b22e2e3a56baf805ad8e52/amqp/utils.py#L44-L48 | |
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/apps/accounting/invoice_pdf.py | python | InvoiceTemplate.draw_statement_period | (self) | [] | def draw_statement_period(self):
origin_x = inches(0.5)
origin_y = inches(7.15)
self.canvas.translate(origin_x, origin_y)
self.canvas.drawString(
0, 0, "Statement period from {} to {}.".format(
self.date_start.strftime(USER_DATE_FORMAT)
if self.date_start is not None else "",
self.date_end.strftime(USER_DATE_FORMAT)
if self.date_end is not None else ""
)
)
self.canvas.translate(-origin_x, -origin_y) | [
"def",
"draw_statement_period",
"(",
"self",
")",
":",
"origin_x",
"=",
"inches",
"(",
"0.5",
")",
"origin_y",
"=",
"inches",
"(",
"7.15",
")",
"self",
".",
"canvas",
".",
"translate",
"(",
"origin_x",
",",
"origin_y",
")",
"self",
".",
"canvas",
".",
... | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/accounting/invoice_pdf.py#L308-L322 | ||||
getting-things-gnome/gtg | 4b02c43744b32a00facb98174f04ec5953bd055d | GTG/gtk/application.py | python | Application.open_tags_popup_in_editor | (self, action, params) | Callback to open the tags popup in the focused task editor. | Callback to open the tags popup in the focused task editor. | [
"Callback",
"to",
"open",
"the",
"tags",
"popup",
"in",
"the",
"focused",
"task",
"editor",
"."
] | def open_tags_popup_in_editor(self, action, params):
"""Callback to open the tags popup in the focused task editor."""
editor = self.get_active_editor()
editor.open_tags_popover() | [
"def",
"open_tags_popup_in_editor",
"(",
"self",
",",
"action",
",",
"params",
")",
":",
"editor",
"=",
"self",
".",
"get_active_editor",
"(",
")",
"editor",
".",
"open_tags_popover",
"(",
")"
] | https://github.com/getting-things-gnome/gtg/blob/4b02c43744b32a00facb98174f04ec5953bd055d/GTG/gtk/application.py#L436-L440 | ||
blankwall/MacHeap | cb8f0ab8f9531186856e2d241e30de5285c29569 | lib/ptypes/pbinary.py | python | terminatedarray.isTerminator | (self, v) | Intended to be overloaded. Should return True if value ``v`` represents the end of the array. | Intended to be overloaded. Should return True if value ``v`` represents the end of the array. | [
"Intended",
"to",
"be",
"overloaded",
".",
"Should",
"return",
"True",
"if",
"value",
"v",
"represents",
"the",
"end",
"of",
"the",
"array",
"."
] | def isTerminator(self, v):
'''Intended to be overloaded. Should return True if value ``v`` represents the end of the array.'''
raise error.ImplementationError(self, 'terminatedarray.isTerminator') | [
"def",
"isTerminator",
"(",
"self",
",",
"v",
")",
":",
"raise",
"error",
".",
"ImplementationError",
"(",
"self",
",",
"'terminatedarray.isTerminator'",
")"
] | https://github.com/blankwall/MacHeap/blob/cb8f0ab8f9531186856e2d241e30de5285c29569/lib/ptypes/pbinary.py#L888-L890 | ||
mesalock-linux/mesapy | ed546d59a21b36feb93e2309d5c6b75aa0ad95c9 | lib_pypy/pyrepl/reader.py | python | Reader.refresh | (self) | Recalculate and refresh the screen. | Recalculate and refresh the screen. | [
"Recalculate",
"and",
"refresh",
"the",
"screen",
"."
] | def refresh(self):
"""Recalculate and refresh the screen."""
# this call sets up self.cxy, so call it first.
screen = self.calc_screen()
self.console.refresh(screen, self.cxy)
self.dirty = 0 | [
"def",
"refresh",
"(",
"self",
")",
":",
"# this call sets up self.cxy, so call it first.",
"screen",
"=",
"self",
".",
"calc_screen",
"(",
")",
"self",
".",
"console",
".",
"refresh",
"(",
"screen",
",",
"self",
".",
"cxy",
")",
"self",
".",
"dirty",
"=",
... | https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib_pypy/pyrepl/reader.py#L519-L524 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.