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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
SheffieldML/GPy | bb1bc5088671f9316bc92a46d356734e34c2d5c0 | GPy/likelihoods/mixed_noise.py | python | MixedNoise.__init__ | (self, likelihoods_list, name='mixed_noise') | [] | def __init__(self, likelihoods_list, name='mixed_noise'):
#NOTE at the moment this likelihood only works for using a list of gaussians
super(Likelihood, self).__init__(name=name)
self.link_parameters(*likelihoods_list)
self.likelihoods_list = likelihoods_list
self.log_concave = False | [
"def",
"__init__",
"(",
"self",
",",
"likelihoods_list",
",",
"name",
"=",
"'mixed_noise'",
")",
":",
"#NOTE at the moment this likelihood only works for using a list of gaussians",
"super",
"(",
"Likelihood",
",",
"self",
")",
".",
"__init__",
"(",
"name",
"=",
"name... | https://github.com/SheffieldML/GPy/blob/bb1bc5088671f9316bc92a46d356734e34c2d5c0/GPy/likelihoods/mixed_noise.py#L15-L21 | ||||
sabri-zaki/EasY_HaCk | 2a39ac384dd0d6fc51c0dd22e8d38cece683fdb9 | .modules/.theHarvester/discovery/shodan/cli/worldmap.py | python | AsciiMap.set_data | (self, data) | Set / convert internal data.
For now it just selects a random set to show. | Set / convert internal data.
For now it just selects a random set to show. | [
"Set",
"/",
"convert",
"internal",
"data",
".",
"For",
"now",
"it",
"just",
"selects",
"a",
"random",
"set",
"to",
"show",
"."
] | def set_data(self, data):
"""
Set / convert internal data.
For now it just selects a random set to show.
"""
entries = []
# Grab 5 random banners to display
for banner in random.sample(data, min(len(data), 5)):
desc = '{} -> {} / {}'.format(get_ip(banner), banner['port'], banner['location']['country_code'])
if banner['location']['city']:
desc += ' {}'.format(banner['location']['city'])
if 'tags' in banner and banner['tags']:
desc += ' / {}'.format(','.join(banner['tags']))
entry = (
float(banner['location']['latitude']),
float(banner['location']['longitude']),
'*',
desc,
curses.A_BOLD,
'red',
)
entries.append(entry)
self.data = entries | [
"def",
"set_data",
"(",
"self",
",",
"data",
")",
":",
"entries",
"=",
"[",
"]",
"# Grab 5 random banners to display",
"for",
"banner",
"in",
"random",
".",
"sample",
"(",
"data",
",",
"min",
"(",
"len",
"(",
"data",
")",
",",
"5",
")",
")",
":",
"de... | https://github.com/sabri-zaki/EasY_HaCk/blob/2a39ac384dd0d6fc51c0dd22e8d38cece683fdb9/.modules/.theHarvester/discovery/shodan/cli/worldmap.py#L117-L142 | ||
owid/covid-19-data | 936aeae6cfbdc0163939ed7bd8ecdbb2582c0a92 | scripts/src/cowidev/vax/incremental/south_africa.py | python | main | () | [] | def main():
SouthAfrica().export() | [
"def",
"main",
"(",
")",
":",
"SouthAfrica",
"(",
")",
".",
"export",
"(",
")"
] | https://github.com/owid/covid-19-data/blob/936aeae6cfbdc0163939ed7bd8ecdbb2582c0a92/scripts/src/cowidev/vax/incremental/south_africa.py#L59-L60 | ||||
xgi/castero | 766965fb1d3586d62ab6fd6dd144fa510c1e0ecb | castero/display.py | python | Display.refresh | (self) | Refresh the screen and all windows in all perspectives. | Refresh the screen and all windows in all perspectives. | [
"Refresh",
"the",
"screen",
"and",
"all",
"windows",
"in",
"all",
"perspectives",
"."
] | def refresh(self) -> None:
"""Refresh the screen and all windows in all perspectives."""
self._stdscr.refresh()
for perspective_id in self._perspectives:
self._perspectives[perspective_id].refresh()
self._header_window.refresh()
self._footer_window.refresh() | [
"def",
"refresh",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_stdscr",
".",
"refresh",
"(",
")",
"for",
"perspective_id",
"in",
"self",
".",
"_perspectives",
":",
"self",
".",
"_perspectives",
"[",
"perspective_id",
"]",
".",
"refresh",
"(",
")",... | https://github.com/xgi/castero/blob/766965fb1d3586d62ab6fd6dd144fa510c1e0ecb/castero/display.py#L634-L642 | ||
Alex-Fabbri/Multi-News | f6476d1f114662eb93db32e9b704b7c4fe047217 | code/Hi_MAP/onmt/decoders/transformer.py | python | TransformerDecoderState._all | (self) | Contains attributes that need to be updated in self.beam_update(). | Contains attributes that need to be updated in self.beam_update(). | [
"Contains",
"attributes",
"that",
"need",
"to",
"be",
"updated",
"in",
"self",
".",
"beam_update",
"()",
"."
] | def _all(self):
"""
Contains attributes that need to be updated in self.beam_update().
"""
if (self.previous_input is not None
and self.previous_layer_inputs is not None):
return (self.previous_input,
self.previous_layer_inputs,
self.src)
else:
return (self.src,) | [
"def",
"_all",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"previous_input",
"is",
"not",
"None",
"and",
"self",
".",
"previous_layer_inputs",
"is",
"not",
"None",
")",
":",
"return",
"(",
"self",
".",
"previous_input",
",",
"self",
".",
"previous_lay... | https://github.com/Alex-Fabbri/Multi-News/blob/f6476d1f114662eb93db32e9b704b7c4fe047217/code/Hi_MAP/onmt/decoders/transformer.py#L264-L274 | ||
huawei-noah/vega | d9f13deede7f2b584e4b1d32ffdb833856129989 | vega/trainer/modules/conf/lr_scheduler.py | python | LrSchedulerConfig.rules | (cls) | return rules | Return rules for checking. | Return rules for checking. | [
"Return",
"rules",
"for",
"checking",
"."
] | def rules(cls):
"""Return rules for checking."""
rules = {"type": {"type": str},
"params": {"type": dict}}
return rules | [
"def",
"rules",
"(",
"cls",
")",
":",
"rules",
"=",
"{",
"\"type\"",
":",
"{",
"\"type\"",
":",
"str",
"}",
",",
"\"params\"",
":",
"{",
"\"type\"",
":",
"dict",
"}",
"}",
"return",
"rules"
] | https://github.com/huawei-noah/vega/blob/d9f13deede7f2b584e4b1d32ffdb833856129989/vega/trainer/modules/conf/lr_scheduler.py#L38-L42 | |
UKPLab/coling2018-graph-neural-networks-question-answering | 389558d6570195debea570834944507de4f21d65 | questionanswering/datasets/webquestions_io.py | python | WebQuestions._instance_with_negative | (self, graph_list, negative_pool, negative_pool_scores) | return instance, target | [] | def _instance_with_negative(self, graph_list, negative_pool, negative_pool_scores):
assert self._p.get("max.silver.samples", 15) < self._p.get("max.negative.samples", 30) or self._p.get("max.negative.samples", 30) == -1
negative_pool_size = self._p.get("max.negative.samples", 30) - len(graph_list)
instance = graph_list[:]
if len(negative_pool) > 0:
if len(negative_pool_scores) > 0:
negative_pool_indices = np.argsort(negative_pool_scores)[::-1][:negative_pool_size]
negative_pool = [negative_pool[id] for id in negative_pool_indices]
else:
if len(negative_pool) > negative_pool_size:
negative_pool = np.random.choice(negative_pool,
negative_pool_size,
replace=False)
instance += [(n_g,) for n_g in negative_pool]
# This is to make sure the zero element is never the target. It is needed for some of the PyTorch losses and shouldn't affect others
one_negative = instance[-1]
instance = instance[:-1]
np.random.shuffle(instance)
instance = [one_negative] + instance
target_value_index = 2 if self._p.get("target.value", "f1") else 1 if self._p.get("target.value", "rec") else 0
target = [g[1][target_value_index] * self._p.get("mult.f1.by", 1.0) if len(g) == 3 else 0.0 for g in instance] \
+ [0.0] * (self._p.get("max.negative.samples", 30) - len(instance))
instance = [el[0] for el in instance]
return instance, target | [
"def",
"_instance_with_negative",
"(",
"self",
",",
"graph_list",
",",
"negative_pool",
",",
"negative_pool_scores",
")",
":",
"assert",
"self",
".",
"_p",
".",
"get",
"(",
"\"max.silver.samples\"",
",",
"15",
")",
"<",
"self",
".",
"_p",
".",
"get",
"(",
... | https://github.com/UKPLab/coling2018-graph-neural-networks-question-answering/blob/389558d6570195debea570834944507de4f21d65/questionanswering/datasets/webquestions_io.py#L244-L268 | |||
NVIDIA/NeMo | 5b0c0b4dec12d87d3cd960846de4105309ce938e | nemo/collections/asr/parts/preprocessing/segment.py | python | AudioSegment.pad | (self, pad_size, symmetric=False) | Add zero padding to the sample. The pad size is given in number
of samples.
If symmetric=True, `pad_size` will be added to both sides. If false,
`pad_size`
zeros will be added only to the end. | Add zero padding to the sample. The pad size is given in number
of samples.
If symmetric=True, `pad_size` will be added to both sides. If false,
`pad_size`
zeros will be added only to the end. | [
"Add",
"zero",
"padding",
"to",
"the",
"sample",
".",
"The",
"pad",
"size",
"is",
"given",
"in",
"number",
"of",
"samples",
".",
"If",
"symmetric",
"=",
"True",
"pad_size",
"will",
"be",
"added",
"to",
"both",
"sides",
".",
"If",
"false",
"pad_size",
"... | def pad(self, pad_size, symmetric=False):
"""Add zero padding to the sample. The pad size is given in number
of samples.
If symmetric=True, `pad_size` will be added to both sides. If false,
`pad_size`
zeros will be added only to the end.
"""
self._samples = np.pad(self._samples, (pad_size if symmetric else 0, pad_size), mode='constant',) | [
"def",
"pad",
"(",
"self",
",",
"pad_size",
",",
"symmetric",
"=",
"False",
")",
":",
"self",
".",
"_samples",
"=",
"np",
".",
"pad",
"(",
"self",
".",
"_samples",
",",
"(",
"pad_size",
"if",
"symmetric",
"else",
"0",
",",
"pad_size",
")",
",",
"mo... | https://github.com/NVIDIA/NeMo/blob/5b0c0b4dec12d87d3cd960846de4105309ce938e/nemo/collections/asr/parts/preprocessing/segment.py#L243-L250 | ||
PacktPublishing/Hands-On-Intelligent-Agents-with-OpenAI-Gym | 14ab6fc82018e48de130e87671cca6c57456d1a5 | ch7/custom-environments/custom_environments/envs/custom_env_template.py | python | CustomEnv.reset | (self) | Reset the environment state and returns an initial observation
Returns
-------
observation (object): The initial observation for the new episode after reset
:return: | Reset the environment state and returns an initial observation | [
"Reset",
"the",
"environment",
"state",
"and",
"returns",
"an",
"initial",
"observation"
] | def reset(self):
"""
Reset the environment state and returns an initial observation
Returns
-------
observation (object): The initial observation for the new episode after reset
:return:
""" | [
"def",
"reset",
"(",
"self",
")",
":"
] | https://github.com/PacktPublishing/Hands-On-Intelligent-Agents-with-OpenAI-Gym/blob/14ab6fc82018e48de130e87671cca6c57456d1a5/ch7/custom-environments/custom_environments/envs/custom_env_template.py#L34-L42 | ||
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | core/state.py | python | ctx_Registers.__init__ | (self, mem) | [] | def __init__(self, mem):
# type: (Mem) -> None
# Because some prompts rely on the status leaking. See issue #853.
# PS1 also does.
last = mem.last_status[-1]
mem.last_status.append(last)
# TODO: We should also copy these values! Turn the whole thing into a
# frame.
mem.pipe_status.append([])
mem.process_sub_status.append([])
mem.regex_matches.append([])
self.mem = mem | [
"def",
"__init__",
"(",
"self",
",",
"mem",
")",
":",
"# type: (Mem) -> None",
"# Because some prompts rely on the status leaking. See issue #853.",
"# PS1 also does.",
"last",
"=",
"mem",
".",
"last_status",
"[",
"-",
"1",
"]",
"mem",
".",
"last_status",
".",
"appen... | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/core/state.py#L932-L946 | ||||
peplin/pygatt | 70c68684ca5a2c5cbd8c4f6f039503fe9b848d24 | pygatt/backends/gatttool/device.py | python | GATTToolBLEDevice.remove_disconnect_callback | (self, callback) | [] | def remove_disconnect_callback(self, callback):
self._backend._receiver.remove_callback("disconnected", callback) | [
"def",
"remove_disconnect_callback",
"(",
"self",
",",
"callback",
")",
":",
"self",
".",
"_backend",
".",
"_receiver",
".",
"remove_callback",
"(",
"\"disconnected\"",
",",
"callback",
")"
] | https://github.com/peplin/pygatt/blob/70c68684ca5a2c5cbd8c4f6f039503fe9b848d24/pygatt/backends/gatttool/device.py#L68-L69 | ||||
limodou/uliweb | 8bc827fa6bf7bf58aa8136b6c920fe2650c52422 | uliweb/core/commands.py | python | Command.handle | (self, options, global_options, *args) | The actual logic of the command. Subclasses must implement
this method. | The actual logic of the command. Subclasses must implement
this method. | [
"The",
"actual",
"logic",
"of",
"the",
"command",
".",
"Subclasses",
"must",
"implement",
"this",
"method",
"."
] | def handle(self, options, global_options, *args):
"""
The actual logic of the command. Subclasses must implement
this method.
"""
raise NotImplementedError() | [
"def",
"handle",
"(",
"self",
",",
"options",
",",
"global_options",
",",
"*",
"args",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/limodou/uliweb/blob/8bc827fa6bf7bf58aa8136b6c920fe2650c52422/uliweb/core/commands.py#L212-L218 | ||
apache/libcloud | 90971e17bfd7b6bb97b2489986472c531cc8e140 | libcloud/compute/drivers/cloudsigma.py | python | CloudSigma_2_0_NodeDriver._parse_ips_from_nic | (self, nic) | return public_ips, private_ips | Parse private and public IP addresses from the provided network
interface object.
:param nic: NIC object.
:type nic: ``dict``
:return: (public_ips, private_ips) tuple.
:rtype: ``tuple`` | Parse private and public IP addresses from the provided network
interface object. | [
"Parse",
"private",
"and",
"public",
"IP",
"addresses",
"from",
"the",
"provided",
"network",
"interface",
"object",
"."
] | def _parse_ips_from_nic(self, nic):
"""
Parse private and public IP addresses from the provided network
interface object.
:param nic: NIC object.
:type nic: ``dict``
:return: (public_ips, private_ips) tuple.
:rtype: ``tuple``
"""
public_ips, private_ips = [], []
ipv4_conf = nic["ip_v4_conf"]
ipv6_conf = nic["ip_v6_conf"]
ip_v4 = ipv4_conf["ip"] if ipv4_conf else None
ip_v6 = ipv6_conf["ip"] if ipv6_conf else None
ipv4 = ip_v4["uuid"] if ip_v4 else None
ipv6 = ip_v4["uuid"] if ip_v6 else None
ips = []
if ipv4:
ips.append(ipv4)
if ipv6:
ips.append(ipv6)
runtime = nic["runtime"]
ip_v4 = runtime["ip_v4"] if nic["runtime"] else None
ip_v6 = runtime["ip_v6"] if nic["runtime"] else None
ipv4 = ip_v4["uuid"] if ip_v4 else None
ipv6 = ip_v4["uuid"] if ip_v6 else None
if ipv4:
ips.append(ipv4)
if ipv6:
ips.append(ipv6)
ips = set(ips)
for ip in ips:
if is_private_subnet(ip):
private_ips.append(ip)
else:
public_ips.append(ip)
return public_ips, private_ips | [
"def",
"_parse_ips_from_nic",
"(",
"self",
",",
"nic",
")",
":",
"public_ips",
",",
"private_ips",
"=",
"[",
"]",
",",
"[",
"]",
"ipv4_conf",
"=",
"nic",
"[",
"\"ip_v4_conf\"",
"]",
"ipv6_conf",
"=",
"nic",
"[",
"\"ip_v6_conf\"",
"]",
"ip_v4",
"=",
"ipv4... | https://github.com/apache/libcloud/blob/90971e17bfd7b6bb97b2489986472c531cc8e140/libcloud/compute/drivers/cloudsigma.py#L2190-L2242 | |
oaubert/python-vlc | 908ffdbd0844dc1849728c456e147788798c99da | generated/3.0/vlc.py | python | libvlc_media_list_player_play_item_at_index | (p_mlp, i_index) | return f(p_mlp, i_index) | Play media list item at position index.
@param p_mlp: media list player instance.
@param i_index: index in media list to play.
@return: 0 upon success -1 if the item wasn't found. | Play media list item at position index. | [
"Play",
"media",
"list",
"item",
"at",
"position",
"index",
"."
] | def libvlc_media_list_player_play_item_at_index(p_mlp, i_index):
'''Play media list item at position index.
@param p_mlp: media list player instance.
@param i_index: index in media list to play.
@return: 0 upon success -1 if the item wasn't found.
'''
f = _Cfunctions.get('libvlc_media_list_player_play_item_at_index', None) or \
_Cfunction('libvlc_media_list_player_play_item_at_index', ((1,), (1,),), None,
ctypes.c_int, MediaListPlayer, ctypes.c_int)
return f(p_mlp, i_index) | [
"def",
"libvlc_media_list_player_play_item_at_index",
"(",
"p_mlp",
",",
"i_index",
")",
":",
"f",
"=",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_media_list_player_play_item_at_index'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_media_list_player_play_item_at_index'... | https://github.com/oaubert/python-vlc/blob/908ffdbd0844dc1849728c456e147788798c99da/generated/3.0/vlc.py#L6163-L6172 | |
glutanimate/review-heatmap | c758478125b60a81c66c87c35b12b7968ec0a348 | src/review_heatmap/libaddon/_vendor/logging/__init__.py | python | _addHandlerRef | (handler) | Add a handler to the internal cleanup list using a weak reference. | Add a handler to the internal cleanup list using a weak reference. | [
"Add",
"a",
"handler",
"to",
"the",
"internal",
"cleanup",
"list",
"using",
"a",
"weak",
"reference",
"."
] | def _addHandlerRef(handler):
"""
Add a handler to the internal cleanup list using a weak reference.
"""
_acquireLock()
try:
_handlerList.append(weakref.ref(handler, _removeHandlerRef))
finally:
_releaseLock() | [
"def",
"_addHandlerRef",
"(",
"handler",
")",
":",
"_acquireLock",
"(",
")",
"try",
":",
"_handlerList",
".",
"append",
"(",
"weakref",
".",
"ref",
"(",
"handler",
",",
"_removeHandlerRef",
")",
")",
"finally",
":",
"_releaseLock",
"(",
")"
] | https://github.com/glutanimate/review-heatmap/blob/c758478125b60a81c66c87c35b12b7968ec0a348/src/review_heatmap/libaddon/_vendor/logging/__init__.py#L752-L760 | ||
matrix-org/synapse | 8e57584a5859a9002759963eb546d523d2498a01 | synapse/util/wheel_timer.py | python | WheelTimer.__init__ | (self, bucket_size: int = 5000) | Args:
bucket_size: Size of buckets in ms. Corresponds roughly to the
accuracy of the timer. | Args:
bucket_size: Size of buckets in ms. Corresponds roughly to the
accuracy of the timer. | [
"Args",
":",
"bucket_size",
":",
"Size",
"of",
"buckets",
"in",
"ms",
".",
"Corresponds",
"roughly",
"to",
"the",
"accuracy",
"of",
"the",
"timer",
"."
] | def __init__(self, bucket_size: int = 5000) -> None:
"""
Args:
bucket_size: Size of buckets in ms. Corresponds roughly to the
accuracy of the timer.
"""
self.bucket_size: int = bucket_size
self.entries: List[_Entry[T]] = []
self.current_tick: int = 0 | [
"def",
"__init__",
"(",
"self",
",",
"bucket_size",
":",
"int",
"=",
"5000",
")",
"->",
"None",
":",
"self",
".",
"bucket_size",
":",
"int",
"=",
"bucket_size",
"self",
".",
"entries",
":",
"List",
"[",
"_Entry",
"[",
"T",
"]",
"]",
"=",
"[",
"]",
... | https://github.com/matrix-org/synapse/blob/8e57584a5859a9002759963eb546d523d2498a01/synapse/util/wheel_timer.py#L32-L40 | ||
eternnoir/pyTelegramBotAPI | fdbc0e6a619f671c2ac97afa2f694c17c6dce7d9 | telebot/asyncio_handler_backends.py | python | StateFile.finish | (self, chat_id) | Finish(delete) state of a user.
:param chat_id: | Finish(delete) state of a user.
:param chat_id: | [
"Finish",
"(",
"delete",
")",
"state",
"of",
"a",
"user",
".",
":",
"param",
"chat_id",
":"
] | async def finish(self, chat_id):
"""
Finish(delete) state of a user.
:param chat_id:
"""
await self.delete_state(chat_id) | [
"async",
"def",
"finish",
"(",
"self",
",",
"chat_id",
")",
":",
"await",
"self",
".",
"delete_state",
"(",
"chat_id",
")"
] | https://github.com/eternnoir/pyTelegramBotAPI/blob/fdbc0e6a619f671c2ac97afa2f694c17c6dce7d9/telebot/asyncio_handler_backends.py#L148-L153 | ||
Kinto/kinto | a9e46e57de8f33c7be098c6f583de18df03b2824 | kinto/plugins/accounts/utils.py | python | is_validated | (user) | return user.get("validated", True) | Is this user record validated? | Is this user record validated? | [
"Is",
"this",
"user",
"record",
"validated?"
] | def is_validated(user):
"""Is this user record validated?"""
# An account is "validated" if it has the `validated` field set to True, or
# no `validated` field at all (for accounts created before the "account
# validation option" was enabled).
return user.get("validated", True) | [
"def",
"is_validated",
"(",
"user",
")",
":",
"# An account is \"validated\" if it has the `validated` field set to True, or",
"# no `validated` field at all (for accounts created before the \"account",
"# validation option\" was enabled).",
"return",
"user",
".",
"get",
"(",
"\"validate... | https://github.com/Kinto/kinto/blob/a9e46e57de8f33c7be098c6f583de18df03b2824/kinto/plugins/accounts/utils.py#L21-L26 | |
happinesslz/TANet | 2d4b2ab99b8e57c03671b0f1531eab7dca8f3c1f | pointpillars_with_TANet/torchplus/nn/modules/normalization.py | python | GroupNorm.__init__ | (self, num_channels, num_groups, eps=1e-5, affine=True) | [] | def __init__(self, num_channels, num_groups, eps=1e-5, affine=True):
super().__init__(
num_groups=num_groups,
num_channels=num_channels,
eps=eps,
affine=affine) | [
"def",
"__init__",
"(",
"self",
",",
"num_channels",
",",
"num_groups",
",",
"eps",
"=",
"1e-5",
",",
"affine",
"=",
"True",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"num_groups",
"=",
"num_groups",
",",
"num_channels",
"=",
"num_channels",
","... | https://github.com/happinesslz/TANet/blob/2d4b2ab99b8e57c03671b0f1531eab7dca8f3c1f/pointpillars_with_TANet/torchplus/nn/modules/normalization.py#L5-L10 | ||||
securityclippy/elasticintel | aa08d3e9f5ab1c000128e95161139ce97ff0e334 | ingest_feed_lambda/pandas/core/indexes/interval.py | python | IntervalIndex.__array__ | (self, result=None) | return self.values | the array interface, return my values | the array interface, return my values | [
"the",
"array",
"interface",
"return",
"my",
"values"
] | def __array__(self, result=None):
""" the array interface, return my values """
return self.values | [
"def",
"__array__",
"(",
"self",
",",
"result",
"=",
"None",
")",
":",
"return",
"self",
".",
"values"
] | https://github.com/securityclippy/elasticintel/blob/aa08d3e9f5ab1c000128e95161139ce97ff0e334/ingest_feed_lambda/pandas/core/indexes/interval.py#L550-L552 | |
microsoft/ptvsd | 99c8513921021d2cc7cd82e132b65c644c256768 | src/ptvsd/_vendored/pydevd/stubs/_django_manager_body.py | python | reverse | (self, *args, **kwargs) | Reverses the ordering of the QuerySet.
@rtype: django.db.models.query.QuerySet | Reverses the ordering of the QuerySet. | [
"Reverses",
"the",
"ordering",
"of",
"the",
"QuerySet",
"."
] | def reverse(self, *args, **kwargs):
"""
Reverses the ordering of the QuerySet.
@rtype: django.db.models.query.QuerySet
""" | [
"def",
"reverse",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":"
] | https://github.com/microsoft/ptvsd/blob/99c8513921021d2cc7cd82e132b65c644c256768/src/ptvsd/_vendored/pydevd/stubs/_django_manager_body.py#L350-L355 | ||
thiagopena/djangoSIGE | e32186b27bfd8acf21b0fa400e699cb5c73e5433 | djangosige/apps/fiscal/views/nota_fiscal.py | python | ValidarNotaView.get | (self, request, *args, **kwargs) | return redirect(reverse_lazy('fiscal:editarnotafiscalsaidaview', kwargs={'pk': nfe_id})) | [] | def get(self, request, *args, **kwargs):
processador_nota = ProcessadorNotaFiscal()
nfe_id = kwargs.get('pk', None)
nota_obj = NotaFiscalSaida.objects.get(id=nfe_id)
processador_nota.validar_nota(nota_obj)
if processador_nota.erro:
messages.error(self.request, processador_nota.message)
else:
messages.success(self.request, processador_nota.message)
return redirect(reverse_lazy('fiscal:editarnotafiscalsaidaview', kwargs={'pk': nfe_id})) | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"processador_nota",
"=",
"ProcessadorNotaFiscal",
"(",
")",
"nfe_id",
"=",
"kwargs",
".",
"get",
"(",
"'pk'",
",",
"None",
")",
"nota_obj",
"=",
"NotaFiscal... | https://github.com/thiagopena/djangoSIGE/blob/e32186b27bfd8acf21b0fa400e699cb5c73e5433/djangosige/apps/fiscal/views/nota_fiscal.py#L413-L424 | |||
qilingframework/qiling | 32cc674f2f6fa4b4c9d64a35a1a57853fe1e4142 | qiling/arch/evm/abc.py | python | GasMeterAPI.refund_gas | (self, amount: int) | Refund ``amount`` of gas. | Refund ``amount`` of gas. | [
"Refund",
"amount",
"of",
"gas",
"."
] | def refund_gas(self, amount: int) -> None:
"""
Refund ``amount`` of gas.
"""
... | [
"def",
"refund_gas",
"(",
"self",
",",
"amount",
":",
"int",
")",
"->",
"None",
":",
"..."
] | https://github.com/qilingframework/qiling/blob/32cc674f2f6fa4b4c9d64a35a1a57853fe1e4142/qiling/arch/evm/abc.py#L144-L148 | ||
mozillazg/pypy | 2ff5cd960c075c991389f842c6d59e71cf0cb7d0 | rpython/rlib/objectmodel.py | python | _untranslated_move_to_end | (d, key, last) | NOT_RPYTHON | NOT_RPYTHON | [
"NOT_RPYTHON"
] | def _untranslated_move_to_end(d, key, last):
"NOT_RPYTHON"
value = d.pop(key)
if last:
d[key] = value
else:
items = d.items()
d.clear()
d[key] = value
# r_dict.update does not support list of tuples, do it manually
for key, value in items:
d[key] = value | [
"def",
"_untranslated_move_to_end",
"(",
"d",
",",
"key",
",",
"last",
")",
":",
"value",
"=",
"d",
".",
"pop",
"(",
"key",
")",
"if",
"last",
":",
"d",
"[",
"key",
"]",
"=",
"value",
"else",
":",
"items",
"=",
"d",
".",
"items",
"(",
")",
"d",... | https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/rpython/rlib/objectmodel.py#L1029-L1040 | ||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_adm_policy_user.py | python | Utils.add_custom_versions | (versions) | return versions_dict | create custom versions strings | create custom versions strings | [
"create",
"custom",
"versions",
"strings"
] | def add_custom_versions(versions):
''' create custom versions strings '''
versions_dict = {}
for tech, version in versions.items():
# clean up "-" from version
if "-" in version:
version = version.split("-")[0]
if version.startswith('v'):
version = version[1:] # Remove the 'v' prefix
versions_dict[tech + '_numeric'] = version.split('+')[0]
# "3.3.0.33" is what we have, we want "3.3"
versions_dict[tech + '_short'] = "{}.{}".format(*version.split('.'))
return versions_dict | [
"def",
"add_custom_versions",
"(",
"versions",
")",
":",
"versions_dict",
"=",
"{",
"}",
"for",
"tech",
",",
"version",
"in",
"versions",
".",
"items",
"(",
")",
":",
"# clean up \"-\" from version",
"if",
"\"-\"",
"in",
"version",
":",
"version",
"=",
"vers... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_adm_policy_user.py#L1313-L1329 | |
Q2h1Cg/CMS-Exploit-Framework | 6bc54e33f316c81f97e16e10b12c7da589efbbd4 | lib/requests/utils.py | python | stream_decode_response_unicode | (iterator, r) | Stream decodes a iterator. | Stream decodes a iterator. | [
"Stream",
"decodes",
"a",
"iterator",
"."
] | def stream_decode_response_unicode(iterator, r):
"""Stream decodes a iterator."""
if r.encoding is None:
for item in iterator:
yield item
return
decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace')
for chunk in iterator:
rv = decoder.decode(chunk)
if rv:
yield rv
rv = decoder.decode(b'', final=True)
if rv:
yield rv | [
"def",
"stream_decode_response_unicode",
"(",
"iterator",
",",
"r",
")",
":",
"if",
"r",
".",
"encoding",
"is",
"None",
":",
"for",
"item",
"in",
"iterator",
":",
"yield",
"item",
"return",
"decoder",
"=",
"codecs",
".",
"getincrementaldecoder",
"(",
"r",
... | https://github.com/Q2h1Cg/CMS-Exploit-Framework/blob/6bc54e33f316c81f97e16e10b12c7da589efbbd4/lib/requests/utils.py#L320-L335 | ||
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/command_line/cover.py | python | CommandCover.__init__ | (
self,
hass,
name,
command_open,
command_close,
command_stop,
command_state,
value_template,
timeout,
unique_id,
) | Initialize the cover. | Initialize the cover. | [
"Initialize",
"the",
"cover",
"."
] | def __init__(
self,
hass,
name,
command_open,
command_close,
command_stop,
command_state,
value_template,
timeout,
unique_id,
):
"""Initialize the cover."""
self._hass = hass
self._name = name
self._state = None
self._command_open = command_open
self._command_close = command_close
self._command_stop = command_stop
self._command_state = command_state
self._value_template = value_template
self._timeout = timeout
self._attr_unique_id = unique_id | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"name",
",",
"command_open",
",",
"command_close",
",",
"command_stop",
",",
"command_state",
",",
"value_template",
",",
"timeout",
",",
"unique_id",
",",
")",
":",
"self",
".",
"_hass",
"=",
"hass",
"self... | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/command_line/cover.py#L90-L112 | ||
xonsh/xonsh | b76d6f994f22a4078f602f8b386f4ec280c8461f | xonsh/completers/tools.py | python | non_exclusive_completer | (func) | return func | Decorator for a non-exclusive completer
This is used to mark completers that will be collected with other completer's results. | Decorator for a non-exclusive completer | [
"Decorator",
"for",
"a",
"non",
"-",
"exclusive",
"completer"
] | def non_exclusive_completer(func):
"""Decorator for a non-exclusive completer
This is used to mark completers that will be collected with other completer's results.
"""
func.non_exclusive = True # type: ignore
return func | [
"def",
"non_exclusive_completer",
"(",
"func",
")",
":",
"func",
".",
"non_exclusive",
"=",
"True",
"# type: ignore",
"return",
"func"
] | https://github.com/xonsh/xonsh/blob/b76d6f994f22a4078f602f8b386f4ec280c8461f/xonsh/completers/tools.py#L180-L186 | |
kenfar/DataGristle | 248f255d69b41e0c306d0a893c917923f2cb39a3 | datagristle/csvhelper.py | python | Header.get_field_position_from_any | (self,
lookup: Union[str, int]) | Returns a field position given either a field name or position | Returns a field position given either a field name or position | [
"Returns",
"a",
"field",
"position",
"given",
"either",
"a",
"field",
"name",
"or",
"position"
] | def get_field_position_from_any(self,
lookup: Union[str, int]) -> int:
""" Returns a field position given either a field name or position
"""
if comm.isnumeric(lookup):
return int(lookup)
else:
return self.get_field_position(lookup) | [
"def",
"get_field_position_from_any",
"(",
"self",
",",
"lookup",
":",
"Union",
"[",
"str",
",",
"int",
"]",
")",
"->",
"int",
":",
"if",
"comm",
".",
"isnumeric",
"(",
"lookup",
")",
":",
"return",
"int",
"(",
"lookup",
")",
"else",
":",
"return",
"... | https://github.com/kenfar/DataGristle/blob/248f255d69b41e0c306d0a893c917923f2cb39a3/datagristle/csvhelper.py#L139-L146 | ||
thomaxxl/safrs | bc97c81f58bbcf6441797ea92f11ef855ca54e61 | safrs/_safrs_relationship.py | python | SAFRSRelationshipObject._s_type | (cls) | return cls._target._s_type | :return: JSON:API type | :return: JSON:API type | [
":",
"return",
":",
"JSON",
":",
"API",
"type"
] | def _s_type(cls):
"""
:return: JSON:API type
"""
return cls._target._s_type | [
"def",
"_s_type",
"(",
"cls",
")",
":",
"return",
"cls",
".",
"_target",
".",
"_s_type"
] | https://github.com/thomaxxl/safrs/blob/bc97c81f58bbcf6441797ea92f11ef855ca54e61/safrs/_safrs_relationship.py#L54-L58 | |
makerbot/ReplicatorG | d6f2b07785a5a5f1e172fb87cb4303b17c575d5d | skein_engines/skeinforge-35/skeinforge_application/skeinforge_plugins/craft_plugins/tower.py | python | TowerSkein.addThreadLayerIfNone | (self) | Add a thread layer if it is none. | Add a thread layer if it is none. | [
"Add",
"a",
"thread",
"layer",
"if",
"it",
"is",
"none",
"."
] | def addThreadLayerIfNone(self):
"Add a thread layer if it is none."
if self.threadLayer != None:
return
self.threadLayer = ThreadLayer()
self.threadLayers.append( self.threadLayer )
self.threadLayer.beforeExtrusionLines = self.beforeExtrusionLines
self.beforeExtrusionLines = [] | [
"def",
"addThreadLayerIfNone",
"(",
"self",
")",
":",
"if",
"self",
".",
"threadLayer",
"!=",
"None",
":",
"return",
"self",
".",
"threadLayer",
"=",
"ThreadLayer",
"(",
")",
"self",
".",
"threadLayers",
".",
"append",
"(",
"self",
".",
"threadLayer",
")",... | https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-35/skeinforge_application/skeinforge_plugins/craft_plugins/tower.py#L198-L205 | ||
meraki/dashboard-api-python | aef5e6fe5d23a40d435d5c64ff30580a28af07f1 | meraki_v0/aio/api/traffic_shaping.py | python | AsyncTrafficShaping.updateNetworkSsidTrafficShaping | (self, networkId: str, number: str, **kwargs) | return await self._session.put(metadata, resource, payload) | **Update the traffic shaping settings for an SSID on an MR network**
https://developer.cisco.com/meraki/api/#!update-network-ssid-traffic-shaping
- networkId (string)
- number (string)
- trafficShapingEnabled (boolean): Whether traffic shaping rules are applied to clients on your SSID.
- defaultRulesEnabled (boolean): Whether default traffic shaping rules are enabled (true) or disabled (false).
There are 4 default rules, which can
be seen on your network's traffic shaping page. Note that default rules
count against the rule limit of 8.
- rules (array): An array of traffic shaping rules. Rules are applied in the order that
they are specified in. An empty list (or null) means no rules. Note that
you are allowed a maximum of 8 rules. | **Update the traffic shaping settings for an SSID on an MR network**
https://developer.cisco.com/meraki/api/#!update-network-ssid-traffic-shaping
- networkId (string)
- number (string)
- trafficShapingEnabled (boolean): Whether traffic shaping rules are applied to clients on your SSID.
- defaultRulesEnabled (boolean): Whether default traffic shaping rules are enabled (true) or disabled (false).
There are 4 default rules, which can
be seen on your network's traffic shaping page. Note that default rules
count against the rule limit of 8. | [
"**",
"Update",
"the",
"traffic",
"shaping",
"settings",
"for",
"an",
"SSID",
"on",
"an",
"MR",
"network",
"**",
"https",
":",
"//",
"developer",
".",
"cisco",
".",
"com",
"/",
"meraki",
"/",
"api",
"/",
"#!update",
"-",
"network",
"-",
"ssid",
"-",
... | async def updateNetworkSsidTrafficShaping(self, networkId: str, number: str, **kwargs):
"""
**Update the traffic shaping settings for an SSID on an MR network**
https://developer.cisco.com/meraki/api/#!update-network-ssid-traffic-shaping
- networkId (string)
- number (string)
- trafficShapingEnabled (boolean): Whether traffic shaping rules are applied to clients on your SSID.
- defaultRulesEnabled (boolean): Whether default traffic shaping rules are enabled (true) or disabled (false).
There are 4 default rules, which can
be seen on your network's traffic shaping page. Note that default rules
count against the rule limit of 8.
- rules (array): An array of traffic shaping rules. Rules are applied in the order that
they are specified in. An empty list (or null) means no rules. Note that
you are allowed a maximum of 8 rules.
"""
kwargs.update(locals())
metadata = {
'tags': ['Traffic shaping'],
'operation': 'updateNetworkSsidTrafficShaping',
}
resource = f'/networks/{networkId}/ssids/{number}/trafficShaping'
body_params = ['trafficShapingEnabled', 'defaultRulesEnabled', 'rules']
payload = {k.strip(): v for (k, v) in kwargs.items() if k.strip() in body_params}
return await self._session.put(metadata, resource, payload) | [
"async",
"def",
"updateNetworkSsidTrafficShaping",
"(",
"self",
",",
"networkId",
":",
"str",
",",
"number",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"locals",
"(",
")",
")",
"metadata",
"=",
"{",
"'tags'",
":",
"[",... | https://github.com/meraki/dashboard-api-python/blob/aef5e6fe5d23a40d435d5c64ff30580a28af07f1/meraki_v0/aio/api/traffic_shaping.py#L6-L36 | |
4shadoww/hakkuframework | 409a11fc3819d251f86faa3473439f8c19066a21 | lib/rarfile.py | python | RarFile.read | (self, name, pwd=None) | Return uncompressed data for archive entry.
For longer files using :meth:`~RarFile.open` may be better idea.
Parameters:
name
filename or RarInfo instance
pwd
password to use for extracting. | Return uncompressed data for archive entry. | [
"Return",
"uncompressed",
"data",
"for",
"archive",
"entry",
"."
] | def read(self, name, pwd=None):
"""Return uncompressed data for archive entry.
For longer files using :meth:`~RarFile.open` may be better idea.
Parameters:
name
filename or RarInfo instance
pwd
password to use for extracting.
"""
with self.open(name, "r", pwd) as f:
return f.read() | [
"def",
"read",
"(",
"self",
",",
"name",
",",
"pwd",
"=",
"None",
")",
":",
"with",
"self",
".",
"open",
"(",
"name",
",",
"\"r\"",
",",
"pwd",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")"
] | https://github.com/4shadoww/hakkuframework/blob/409a11fc3819d251f86faa3473439f8c19066a21/lib/rarfile.py#L785-L799 | ||
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/apps/app_manager/detail_screen.py | python | FormattedDetailColumn.evaluate_template | (self, template) | [] | def evaluate_template(self, template):
if template:
return template.format(
xpath='$calculated_property' if self.column.useXpathExpression else self.xpath,
app=self.app,
module=self.module,
detail=self.detail,
column=self.column
) | [
"def",
"evaluate_template",
"(",
"self",
",",
"template",
")",
":",
"if",
"template",
":",
"return",
"template",
".",
"format",
"(",
"xpath",
"=",
"'$calculated_property'",
"if",
"self",
".",
"column",
".",
"useXpathExpression",
"else",
"self",
".",
"xpath",
... | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/app_manager/detail_screen.py#L244-L252 | ||||
kozec/syncthing-gtk | 01eeeb9ed485232e145bf39d90142832e1c9751e | syncthing_gtk/editordialog.py | python | EditorDialog.get_widget_id | (self, w) | return self.widget_to_id[w] | Returns glade file ID for specified widget or None, if widget
is not known. | Returns glade file ID for specified widget or None, if widget
is not known. | [
"Returns",
"glade",
"file",
"ID",
"for",
"specified",
"widget",
"or",
"None",
"if",
"widget",
"is",
"not",
"known",
"."
] | def get_widget_id(self, w):
"""
Returns glade file ID for specified widget or None, if widget
is not known.
"""
if not w in self.widget_to_id:
return None
return self.widget_to_id[w] | [
"def",
"get_widget_id",
"(",
"self",
",",
"w",
")",
":",
"if",
"not",
"w",
"in",
"self",
".",
"widget_to_id",
":",
"return",
"None",
"return",
"self",
".",
"widget_to_id",
"[",
"w",
"]"
] | https://github.com/kozec/syncthing-gtk/blob/01eeeb9ed485232e145bf39d90142832e1c9751e/syncthing_gtk/editordialog.py#L84-L91 | |
Makeblock-official/mDrawBot | b6456ac35c7eefb55ecf2c34b4c9dad6340d497d | mDrawGui/SerialCom.py | python | serialList | () | return result | Lists serial ports
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of available serial ports | Lists serial ports | [
"Lists",
"serial",
"ports"
] | def serialList():
"""Lists serial ports
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of available serial ports
"""
if sys.platform.startswith('win'):
ports = ['COM' + str(i + 1) for i in range(256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
# this is to exclude your current terminal "/dev/tty"
ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob.glob('/dev/tty.*')
else:
raise EnvironmentError('Unsupported platform')
result = []
for port in ports:
try:
# s = serial.Serial(port)
# s.close()
result.append(port)
except (OSError, serial.SerialException):
pass
return result | [
"def",
"serialList",
"(",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'win'",
")",
":",
"ports",
"=",
"[",
"'COM'",
"+",
"str",
"(",
"i",
"+",
"1",
")",
"for",
"i",
"in",
"range",
"(",
"256",
")",
"]",
"elif",
"sys",
".",
... | https://github.com/Makeblock-official/mDrawBot/blob/b6456ac35c7eefb55ecf2c34b4c9dad6340d497d/mDrawGui/SerialCom.py#L9-L38 | |
ipython/ipyparallel | d35d4fb9501da5b3280b11e83ed633a95f17be1d | ipyparallel/client/view.py | python | DirectView.use_cloudpickle | (self) | return self.apply(serialize.use_cloudpickle) | Expand serialization support with cloudpickle.
This calls ipyparallel.serialize.use_cloudpickle() here and on each engine. | Expand serialization support with cloudpickle. | [
"Expand",
"serialization",
"support",
"with",
"cloudpickle",
"."
] | def use_cloudpickle(self):
"""Expand serialization support with cloudpickle.
This calls ipyparallel.serialize.use_cloudpickle() here and on each engine.
"""
serialize.use_cloudpickle()
return self.apply(serialize.use_cloudpickle) | [
"def",
"use_cloudpickle",
"(",
"self",
")",
":",
"serialize",
".",
"use_cloudpickle",
"(",
")",
"return",
"self",
".",
"apply",
"(",
"serialize",
".",
"use_cloudpickle",
")"
] | https://github.com/ipython/ipyparallel/blob/d35d4fb9501da5b3280b11e83ed633a95f17be1d/ipyparallel/client/view.py#L523-L529 | |
ultrabug/py3status | 80ec45a9db0712b0de55f83291c321f6fceb6a6d | py3status/modules/pomodoro.py | python | Py3status._setup_bar | (self) | return bar | Setup the process bar. | Setup the process bar. | [
"Setup",
"the",
"process",
"bar",
"."
] | def _setup_bar(self):
"""
Setup the process bar.
"""
bar = ""
items_cnt = len(PROGRESS_BAR_ITEMS)
bar_val = self._time_left / self._section_time * self.num_progress_bars
while bar_val > 0:
selector = min(int(bar_val * items_cnt), items_cnt - 1)
bar += PROGRESS_BAR_ITEMS[selector]
bar_val -= 1
bar = bar.ljust(self.num_progress_bars)
return bar | [
"def",
"_setup_bar",
"(",
"self",
")",
":",
"bar",
"=",
"\"\"",
"items_cnt",
"=",
"len",
"(",
"PROGRESS_BAR_ITEMS",
")",
"bar_val",
"=",
"self",
".",
"_time_left",
"/",
"self",
".",
"_section_time",
"*",
"self",
".",
"num_progress_bars",
"while",
"bar_val",
... | https://github.com/ultrabug/py3status/blob/80ec45a9db0712b0de55f83291c321f6fceb6a6d/py3status/modules/pomodoro.py#L189-L202 | |
EventGhost/EventGhost | 177be516849e74970d2e13cda82244be09f277ce | plugins/MceRemote_Vista/__init__.py | python | CheckForAlternateService | () | return True | Checks if the AlternateMceIrService is installed | Checks if the AlternateMceIrService is installed | [
"Checks",
"if",
"the",
"AlternateMceIrService",
"is",
"installed"
] | def CheckForAlternateService():
"""
Checks if the AlternateMceIrService is installed
"""
ServiceKey = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\AlternateMceIrService"
try:
key = reg.OpenKey(reg.HKEY_LOCAL_MACHINE, ServiceKey, 0, reg.KEY_READ)
except:
return False
return True | [
"def",
"CheckForAlternateService",
"(",
")",
":",
"ServiceKey",
"=",
"\"SYSTEM\\\\CurrentControlSet\\\\Services\\\\EventLog\\\\Application\\\\AlternateMceIrService\"",
"try",
":",
"key",
"=",
"reg",
".",
"OpenKey",
"(",
"reg",
".",
"HKEY_LOCAL_MACHINE",
",",
"ServiceKey",
"... | https://github.com/EventGhost/EventGhost/blob/177be516849e74970d2e13cda82244be09f277ce/plugins/MceRemote_Vista/__init__.py#L379-L388 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_hxb2/lib/python3.5/site-packages/treebeard/ns_tree.py | python | NS_Node.get_parent | (self, update=False) | return self._cached_parent_obj | :returns: the parent node of the current node object.
Caches the result in the object itself to help in loops. | :returns: the parent node of the current node object.
Caches the result in the object itself to help in loops. | [
":",
"returns",
":",
"the",
"parent",
"node",
"of",
"the",
"current",
"node",
"object",
".",
"Caches",
"the",
"result",
"in",
"the",
"object",
"itself",
"to",
"help",
"in",
"loops",
"."
] | def get_parent(self, update=False):
"""
:returns: the parent node of the current node object.
Caches the result in the object itself to help in loops.
"""
if self.is_root():
return
try:
if update:
del self._cached_parent_obj
else:
return self._cached_parent_obj
except AttributeError:
pass
# parent = our most direct ancestor
self._cached_parent_obj = self.get_ancestors().reverse()[0]
return self._cached_parent_obj | [
"def",
"get_parent",
"(",
"self",
",",
"update",
"=",
"False",
")",
":",
"if",
"self",
".",
"is_root",
"(",
")",
":",
"return",
"try",
":",
"if",
"update",
":",
"del",
"self",
".",
"_cached_parent_obj",
"else",
":",
"return",
"self",
".",
"_cached_pare... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/treebeard/ns_tree.py#L649-L665 | |
googleads/google-ads-python | 2a1d6062221f6aad1992a6bcca0e7e4a93d2db86 | google/ads/googleads/v9/services/services/batch_job_service/client.py | python | BatchJobServiceClient.parse_campaign_criterion_path | (path: str) | return m.groupdict() if m else {} | Parse a campaign_criterion path into its component segments. | Parse a campaign_criterion path into its component segments. | [
"Parse",
"a",
"campaign_criterion",
"path",
"into",
"its",
"component",
"segments",
"."
] | def parse_campaign_criterion_path(path: str) -> Dict[str, str]:
"""Parse a campaign_criterion path into its component segments."""
m = re.match(
r"^customers/(?P<customer_id>.+?)/campaignCriteria/(?P<campaign_id>.+?)~(?P<criterion_id>.+?)$",
path,
)
return m.groupdict() if m else {} | [
"def",
"parse_campaign_criterion_path",
"(",
"path",
":",
"str",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r\"^customers/(?P<customer_id>.+?)/campaignCriteria/(?P<campaign_id>.+?)~(?P<criterion_id>.+?)$\"",
",",
"path",
"... | https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/batch_job_service/client.py#L779-L785 | |
cassieeric/python_crawler | b50b5b55404e32164dc82ff0c23cdae0c4b168ae | weixin_crawler/project/tools/data_queue.py | python | DBQ.get_queue | (self) | return queue_data['queue'] | :return:获得queue list数据 | :return:获得queue list数据 | [
":",
"return",
":",
"获得queue",
"list数据"
] | def get_queue(self):
"""
:return:获得queue list数据
"""
queue_data = DBQ.col.find_one({'name':self.name, 'queue_type':self.queue_type})
return queue_data['queue'] | [
"def",
"get_queue",
"(",
"self",
")",
":",
"queue_data",
"=",
"DBQ",
".",
"col",
".",
"find_one",
"(",
"{",
"'name'",
":",
"self",
".",
"name",
",",
"'queue_type'",
":",
"self",
".",
"queue_type",
"}",
")",
"return",
"queue_data",
"[",
"'queue'",
"]"
] | https://github.com/cassieeric/python_crawler/blob/b50b5b55404e32164dc82ff0c23cdae0c4b168ae/weixin_crawler/project/tools/data_queue.py#L192-L197 | |
guillermooo/Vintageous | f958207009902052aed5fcac09745f1742648604 | state.py | python | State.last_buffer_search | (self, value) | [] | def last_buffer_search(self, value):
self.settings.window['_vintageous_last_buffer_search'] = value | [
"def",
"last_buffer_search",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"settings",
".",
"window",
"[",
"'_vintageous_last_buffer_search'",
"]",
"=",
"value"
] | https://github.com/guillermooo/Vintageous/blob/f958207009902052aed5fcac09745f1742648604/state.py#L301-L302 | ||||
treeio/treeio | bae3115f4015aad2cbc5ab45572232ceec990495 | treeio/projects/views.py | python | milestone_view | (request, milestone_id, response_format='html') | return render_to_response('projects/milestone_view', context,
context_instance=RequestContext(request), response_format=response_format) | Single milestone view page | Single milestone view page | [
"Single",
"milestone",
"view",
"page"
] | def milestone_view(request, milestone_id, response_format='html'):
"""Single milestone view page"""
milestone = get_object_or_404(Milestone, pk=milestone_id)
project = milestone.project
if not request.user.profile.has_permission(milestone):
return user_denied(request, message="You don't have access to this Milestone")
query = Q(milestone=milestone, parent__isnull=True)
if request.GET:
if 'status' in request.GET and request.GET['status']:
query = query & _get_filter_query(request.GET)
else:
query = query & Q(
status__hidden=False) & _get_filter_query(request.GET)
tasks = Object.filter_by_request(request, Task.objects.filter(query))
else:
tasks = Object.filter_by_request(request,
Task.objects.filter(query & Q(status__hidden=False)))
filters = FilterForm(request.user.profile, 'milestone', request.GET)
tasks_progress = float(0)
tasks_progress_query = Object.filter_by_request(
request, Task.objects.filter(Q(parent__isnull=True, milestone=milestone)))
if tasks_progress_query:
for task in tasks_progress_query:
if not task.status.active:
tasks_progress += 1
tasks_progress = (tasks_progress / len(tasks_progress_query)) * 100
tasks_progress = round(tasks_progress, ndigits=1)
context = _get_default_context(request)
context.update({'milestone': milestone,
'tasks': tasks,
'tasks_progress': tasks_progress,
'filters': filters,
'project': project})
return render_to_response('projects/milestone_view', context,
context_instance=RequestContext(request), response_format=response_format) | [
"def",
"milestone_view",
"(",
"request",
",",
"milestone_id",
",",
"response_format",
"=",
"'html'",
")",
":",
"milestone",
"=",
"get_object_or_404",
"(",
"Milestone",
",",
"pk",
"=",
"milestone_id",
")",
"project",
"=",
"milestone",
".",
"project",
"if",
"not... | https://github.com/treeio/treeio/blob/bae3115f4015aad2cbc5ab45572232ceec990495/treeio/projects/views.py#L490-L530 | |
makerbot/ReplicatorG | d6f2b07785a5a5f1e172fb87cb4303b17c575d5d | skein_engines/skeinforge-35/fabmetheus_utilities/geometry/solids/trianglemesh.py | python | getDoubledRoundZ | ( overhangingSegment, segmentRoundZ ) | return roundZ * roundZ / roundZLength | Get doubled plane angle around z of the overhanging segment. | Get doubled plane angle around z of the overhanging segment. | [
"Get",
"doubled",
"plane",
"angle",
"around",
"z",
"of",
"the",
"overhanging",
"segment",
"."
] | def getDoubledRoundZ( overhangingSegment, segmentRoundZ ):
"Get doubled plane angle around z of the overhanging segment."
endpoint = overhangingSegment[0]
roundZ = endpoint.point - endpoint.otherEndpoint.point
roundZ *= segmentRoundZ
if abs( roundZ ) == 0.0:
return complex()
if roundZ.real < 0.0:
roundZ *= - 1.0
roundZLength = abs( roundZ )
return roundZ * roundZ / roundZLength | [
"def",
"getDoubledRoundZ",
"(",
"overhangingSegment",
",",
"segmentRoundZ",
")",
":",
"endpoint",
"=",
"overhangingSegment",
"[",
"0",
"]",
"roundZ",
"=",
"endpoint",
".",
"point",
"-",
"endpoint",
".",
"otherEndpoint",
".",
"point",
"roundZ",
"*=",
"segmentRoun... | https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-35/fabmetheus_utilities/geometry/solids/trianglemesh.py#L299-L309 | |
SethMMorton/natsort | 9616d2909899e1a47735c6fcdb6fa84d08c03206 | natsort/natsort.py | python | decoder | (encoding: str) | return partial(utils.do_decoding, encoding=encoding) | Return a function that can be used to decode bytes to unicode.
Parameters
----------
encoding : str
The codec to use for decoding. This must be a valid unicode codec.
Returns
-------
decode_function
A function that takes a single argument and attempts to decode
it using the supplied codec. Any `UnicodeErrors` are raised.
If the argument was not of `bytes` type, it is simply returned
as-is.
See Also
--------
as_ascii
as_utf8
Examples
--------
>>> f = decoder('utf8')
>>> f(b'bytes') == 'bytes'
True
>>> f(12345) == 12345
True
>>> # On Python 3, without decoder this would return [b'a10', b'a2']
>>> natsorted([b'a10', b'a2'], key=decoder('utf8')) == [b'a2', b'a10']
True
>>> # On Python 3, without decoder this would raise a TypeError.
>>> natsorted([b'a10', 'a2'], key=decoder('utf8')) == ['a2', b'a10']
True | Return a function that can be used to decode bytes to unicode. | [
"Return",
"a",
"function",
"that",
"can",
"be",
"used",
"to",
"decode",
"bytes",
"to",
"unicode",
"."
] | def decoder(encoding: str) -> Callable[[NatsortInType], NatsortInType]:
"""
Return a function that can be used to decode bytes to unicode.
Parameters
----------
encoding : str
The codec to use for decoding. This must be a valid unicode codec.
Returns
-------
decode_function
A function that takes a single argument and attempts to decode
it using the supplied codec. Any `UnicodeErrors` are raised.
If the argument was not of `bytes` type, it is simply returned
as-is.
See Also
--------
as_ascii
as_utf8
Examples
--------
>>> f = decoder('utf8')
>>> f(b'bytes') == 'bytes'
True
>>> f(12345) == 12345
True
>>> # On Python 3, without decoder this would return [b'a10', b'a2']
>>> natsorted([b'a10', b'a2'], key=decoder('utf8')) == [b'a2', b'a10']
True
>>> # On Python 3, without decoder this would raise a TypeError.
>>> natsorted([b'a10', 'a2'], key=decoder('utf8')) == ['a2', b'a10']
True
"""
return partial(utils.do_decoding, encoding=encoding) | [
"def",
"decoder",
"(",
"encoding",
":",
"str",
")",
"->",
"Callable",
"[",
"[",
"NatsortInType",
"]",
",",
"NatsortInType",
"]",
":",
"return",
"partial",
"(",
"utils",
".",
"do_decoding",
",",
"encoding",
"=",
"encoding",
")"
] | https://github.com/SethMMorton/natsort/blob/9616d2909899e1a47735c6fcdb6fa84d08c03206/natsort/natsort.py#L56-L94 | |
kootenpv/yagmail | 8eb3a057fe284499efb8433880a4f5ffc1e168a9 | yagmail/message.py | python | dt_converter | (o) | [] | def dt_converter(o):
if isinstance(o, (datetime.date, datetime.datetime)):
return o.isoformat() | [
"def",
"dt_converter",
"(",
"o",
")",
":",
"if",
"isinstance",
"(",
"o",
",",
"(",
"datetime",
".",
"date",
",",
"datetime",
".",
"datetime",
")",
")",
":",
"return",
"o",
".",
"isoformat",
"(",
")"
] | https://github.com/kootenpv/yagmail/blob/8eb3a057fe284499efb8433880a4f5ffc1e168a9/yagmail/message.py#L21-L23 | ||||
ansible/ansible-container | d031c1a6133d5482a5d054fcbdbecafb923f8b4b | container/utils/_text.py | python | to_text | (obj, encoding='utf-8', errors=None, nonstring='simplerepr') | return to_text(value, encoding, errors) | Make sure that a string is a text string
:arg obj: An object to make sure is a text string. In most cases this
will be either a text string or a byte string. However, with
``nonstring='simplerepr'``, this can be used as a traceback-free
version of ``str(obj)``.
:kwarg encoding: The encoding to use to transform from a byte string to
a text string. Defaults to using 'utf-8'.
:kwarg errors: The error handler to use if the byte string is not
decodable using the specified encoding. Any valid `codecs error
handler <https://docs.python.org/2/library/codecs.html#codec-base-classes>`_
may be specified. We support three additional error strategies
specifically aimed at helping people to port code:
:surrogate_or_strict: Will use surrogateescape if it is a valid
handler, otherwise it will use strict
:surrogate_or_replace: Will use surrogateescape if it is a valid
handler, otherwise it will use replace.
:surrogate_then_replace: Does the same as surrogate_or_replace but
`was added for symmetry with the error handlers in
:func:`ansible.module_utils._text.to_bytes` (Added in Ansible 2.3)
Because surrogateescape was added in Python3 this usually means that
Python3 will use `surrogateescape` and Python2 will use the fallback
error handler. Note that the code checks for surrogateescape when the
module is imported. If you have a backport of `surrogateescape` for
python2, be sure to register the error handler prior to importing this
module.
The default until Ansible-2.2 was `surrogate_or_replace`
In Ansible-2.3 this defaults to `surrogate_then_replace` for symmetry
with :func:`ansible.module_utils._text.to_bytes` .
:kwarg nonstring: The strategy to use if a nonstring is specified in
``obj``. Default is 'simplerepr'. Valid values are:
:simplerepr: The default. This takes the ``str`` of the object and
then returns the text version of that string.
:empty: Return an empty text string
:passthru: Return the object passed in
:strict: Raise a :exc:`TypeError`
:returns: Typically this returns a text string. If a nonstring object is
passed in this may be a different type depending on the strategy
specified by nonstring. This will never return a byte string.
From Ansible-2.3 onwards, the default is `surrogate_then_replace`.
.. version_changed:: 2.3
Added the surrogate_then_replace error handler and made it the default error handler. | Make sure that a string is a text string | [
"Make",
"sure",
"that",
"a",
"string",
"is",
"a",
"text",
"string"
] | def to_text(obj, encoding='utf-8', errors=None, nonstring='simplerepr'):
"""Make sure that a string is a text string
:arg obj: An object to make sure is a text string. In most cases this
will be either a text string or a byte string. However, with
``nonstring='simplerepr'``, this can be used as a traceback-free
version of ``str(obj)``.
:kwarg encoding: The encoding to use to transform from a byte string to
a text string. Defaults to using 'utf-8'.
:kwarg errors: The error handler to use if the byte string is not
decodable using the specified encoding. Any valid `codecs error
handler <https://docs.python.org/2/library/codecs.html#codec-base-classes>`_
may be specified. We support three additional error strategies
specifically aimed at helping people to port code:
:surrogate_or_strict: Will use surrogateescape if it is a valid
handler, otherwise it will use strict
:surrogate_or_replace: Will use surrogateescape if it is a valid
handler, otherwise it will use replace.
:surrogate_then_replace: Does the same as surrogate_or_replace but
`was added for symmetry with the error handlers in
:func:`ansible.module_utils._text.to_bytes` (Added in Ansible 2.3)
Because surrogateescape was added in Python3 this usually means that
Python3 will use `surrogateescape` and Python2 will use the fallback
error handler. Note that the code checks for surrogateescape when the
module is imported. If you have a backport of `surrogateescape` for
python2, be sure to register the error handler prior to importing this
module.
The default until Ansible-2.2 was `surrogate_or_replace`
In Ansible-2.3 this defaults to `surrogate_then_replace` for symmetry
with :func:`ansible.module_utils._text.to_bytes` .
:kwarg nonstring: The strategy to use if a nonstring is specified in
``obj``. Default is 'simplerepr'. Valid values are:
:simplerepr: The default. This takes the ``str`` of the object and
then returns the text version of that string.
:empty: Return an empty text string
:passthru: Return the object passed in
:strict: Raise a :exc:`TypeError`
:returns: Typically this returns a text string. If a nonstring object is
passed in this may be a different type depending on the strategy
specified by nonstring. This will never return a byte string.
From Ansible-2.3 onwards, the default is `surrogate_then_replace`.
.. version_changed:: 2.3
Added the surrogate_then_replace error handler and made it the default error handler.
"""
if isinstance(obj, text_type):
return obj
if errors in _COMPOSED_ERROR_HANDLERS:
if HAS_SURROGATEESCAPE:
errors = 'surrogateescape'
elif errors == 'surrogate_or_strict':
errors = 'strict'
else:
errors = 'replace'
if isinstance(obj, binary_type):
# Note: We don't need special handling for surrogate_then_replace
# because all bytes will either be made into surrogates or are valid
# to decode.
return obj.decode(encoding, errors)
# Note: We do these last even though we have to call to_text again on the
# value because we're optimizing the common case
if nonstring == 'simplerepr':
try:
value = str(obj)
except UnicodeError:
try:
value = repr(obj)
except UnicodeError:
# Giving up
return u''
elif nonstring == 'passthru':
return obj
elif nonstring == 'empty':
return u''
elif nonstring == 'strict':
raise TypeError('obj must be a string type')
else:
raise TypeError('Invalid value %s for to_text\'s nonstring parameter' % nonstring)
return to_text(value, encoding, errors) | [
"def",
"to_text",
"(",
"obj",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"None",
",",
"nonstring",
"=",
"'simplerepr'",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"text_type",
")",
":",
"return",
"obj",
"if",
"errors",
"in",
"_COMPOSED_ERRO... | https://github.com/ansible/ansible-container/blob/d031c1a6133d5482a5d054fcbdbecafb923f8b4b/container/utils/_text.py#L166-L254 | |
QQuick/Transcrypt | 68b4b71d4ff3e4d58281b24e9e2dcc9fc766e822 | transcrypt/modules/datetime/__init__.py | python | date.__repr__ | (self) | return "datetime.date({}, {}, {})".format(
self._year,
self._month,
self._day) | Convert to formal string, for repr().
>>> dt = datetime(2010, 1, 1)
>>> repr(dt)
'datetime.datetime(2010, 1, 1, 0, 0)'
>>> dt = datetime(2010, 1, 1, tzinfo=timezone.utc)
>>> repr(dt)
'datetime.datetime(2010, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)' | Convert to formal string, for repr(). | [
"Convert",
"to",
"formal",
"string",
"for",
"repr",
"()",
"."
] | def __repr__(self):
"""Convert to formal string, for repr().
>>> dt = datetime(2010, 1, 1)
>>> repr(dt)
'datetime.datetime(2010, 1, 1, 0, 0)'
>>> dt = datetime(2010, 1, 1, tzinfo=timezone.utc)
>>> repr(dt)
'datetime.datetime(2010, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)'
"""
return "datetime.date({}, {}, {})".format(
self._year,
self._month,
self._day) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"\"datetime.date({}, {}, {})\"",
".",
"format",
"(",
"self",
".",
"_year",
",",
"self",
".",
"_month",
",",
"self",
".",
"_day",
")"
] | https://github.com/QQuick/Transcrypt/blob/68b4b71d4ff3e4d58281b24e9e2dcc9fc766e822/transcrypt/modules/datetime/__init__.py#L741-L755 | |
JaniceWuo/MovieRecommend | 4c86db64ca45598917d304f535413df3bc9fea65 | movierecommend/venv1/Lib/site-packages/django/contrib/auth/__init__.py | python | _get_backends | (return_tuples=False) | return backends | [] | def _get_backends(return_tuples=False):
backends = []
for backend_path in settings.AUTHENTICATION_BACKENDS:
backend = load_backend(backend_path)
backends.append((backend, backend_path) if return_tuples else backend)
if not backends:
raise ImproperlyConfigured(
'No authentication backends have been defined. Does '
'AUTHENTICATION_BACKENDS contain anything?'
)
return backends | [
"def",
"_get_backends",
"(",
"return_tuples",
"=",
"False",
")",
":",
"backends",
"=",
"[",
"]",
"for",
"backend_path",
"in",
"settings",
".",
"AUTHENTICATION_BACKENDS",
":",
"backend",
"=",
"load_backend",
"(",
"backend_path",
")",
"backends",
".",
"append",
... | https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/contrib/auth/__init__.py#L26-L36 | |||
deluge-torrent/deluge | 2316088f5c0dd6cb044d9d4832fa7d56dcc79cdc | deluge/common.py | python | is_process_running | (pid) | Verify if the supplied pid is a running process.
Args:
pid (int): The pid to check.
Returns:
bool: True if pid is a running process, False otherwise. | Verify if the supplied pid is a running process. | [
"Verify",
"if",
"the",
"supplied",
"pid",
"is",
"a",
"running",
"process",
"."
] | def is_process_running(pid):
"""
Verify if the supplied pid is a running process.
Args:
pid (int): The pid to check.
Returns:
bool: True if pid is a running process, False otherwise.
"""
if windows_check():
from win32process import EnumProcesses
return pid in EnumProcesses()
else:
try:
os.kill(pid, 0)
except OSError:
return False
else:
return True | [
"def",
"is_process_running",
"(",
"pid",
")",
":",
"if",
"windows_check",
"(",
")",
":",
"from",
"win32process",
"import",
"EnumProcesses",
"return",
"pid",
"in",
"EnumProcesses",
"(",
")",
"else",
":",
"try",
":",
"os",
".",
"kill",
"(",
"pid",
",",
"0"... | https://github.com/deluge-torrent/deluge/blob/2316088f5c0dd6cb044d9d4832fa7d56dcc79cdc/deluge/common.py#L1323-L1345 | ||
quic/aimet | dae9bae9a77ca719aa7553fefde4768270fc3518 | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/keras/batch_norm_fold.py | python | _fill_conv_linear_bn_dict | (cur_layer: tf.keras.layers.Layer, node_layer_ref: Dict,
layer_out_node_ref: Dict,
has_seen: List[Union[None, CONV_TYPE, BN_TYPE, FLATTEN_TYPE]],
visited_layer: Set[tf.keras.layers.Layer],
conv_linear_with_bn_dict: Dict[Union[CONV_TYPE, LINEAR_TYPE],
List[Union[None, BN_TYPE]]]) | fill conv_linear_bn_dict for the model
:param cur_layer: dictionary includes node_ref as a key, in_layers and out_layer as value
:param node_layer_ref: dictionary includes node_ref as a key, in_layers and out_layer as value
:param layer_out_node_ref: dictionary includes layer_ref as a key, outbound nodes as value
:paramm has_seen: for storing the layer which is useful for finding pattern in the next layers;
index 0 is for conv op, index 2 is for bn op and index 3 is for storing flatten/reshape op
:param visited_layer: to store all the layers that have been visited so far in the dictionary
:param conv_linear_with_bn_dict: dictionary of all possible conv_bn pairs,
key: Dense or Conv layer & Value: list of BNS;
first index in this list shows bn_in and the second index shows bn_out | fill conv_linear_bn_dict for the model | [
"fill",
"conv_linear_bn_dict",
"for",
"the",
"model"
] | def _fill_conv_linear_bn_dict(cur_layer: tf.keras.layers.Layer, node_layer_ref: Dict,
layer_out_node_ref: Dict,
has_seen: List[Union[None, CONV_TYPE, BN_TYPE, FLATTEN_TYPE]],
visited_layer: Set[tf.keras.layers.Layer],
conv_linear_with_bn_dict: Dict[Union[CONV_TYPE, LINEAR_TYPE],
List[Union[None, BN_TYPE]]]):
"""
fill conv_linear_bn_dict for the model
:param cur_layer: dictionary includes node_ref as a key, in_layers and out_layer as value
:param node_layer_ref: dictionary includes node_ref as a key, in_layers and out_layer as value
:param layer_out_node_ref: dictionary includes layer_ref as a key, outbound nodes as value
:paramm has_seen: for storing the layer which is useful for finding pattern in the next layers;
index 0 is for conv op, index 2 is for bn op and index 3 is for storing flatten/reshape op
:param visited_layer: to store all the layers that have been visited so far in the dictionary
:param conv_linear_with_bn_dict: dictionary of all possible conv_bn pairs,
key: Dense or Conv layer & Value: list of BNS;
first index in this list shows bn_in and the second index shows bn_out
"""
# Mark the current layer as visited to prevent passing from one layer more than once
visited_layer.add(cur_layer)
_check_layer_to_find_pattern(cur_layer, conv_linear_with_bn_dict, layer_out_node_ref, has_seen)
if cur_layer in layer_out_node_ref:
for next_node in layer_out_node_ref[cur_layer]:
next_layer = node_layer_ref[next_node][1]
if next_layer not in visited_layer:
_fill_conv_linear_bn_dict(next_layer, node_layer_ref, layer_out_node_ref, has_seen,
visited_layer, conv_linear_with_bn_dict)
else:
has_seen[0] = None
has_seen[1] = None
has_seen[2] = None | [
"def",
"_fill_conv_linear_bn_dict",
"(",
"cur_layer",
":",
"tf",
".",
"keras",
".",
"layers",
".",
"Layer",
",",
"node_layer_ref",
":",
"Dict",
",",
"layer_out_node_ref",
":",
"Dict",
",",
"has_seen",
":",
"List",
"[",
"Union",
"[",
"None",
",",
"CONV_TYPE",... | https://github.com/quic/aimet/blob/dae9bae9a77ca719aa7553fefde4768270fc3518/TrainingExtensions/tensorflow/src/python/aimet_tensorflow/keras/batch_norm_fold.py#L201-L235 | ||
XX-net/XX-Net | a9898cfcf0084195fb7e69b6bc834e59aecdf14f | python3.8.2/Lib/configparser.py | python | RawConfigParser.has_option | (self, section, option) | Check for the existence of a given option in a given section.
If the specified `section' is None or an empty string, DEFAULT is
assumed. If the specified `section' does not exist, returns False. | Check for the existence of a given option in a given section.
If the specified `section' is None or an empty string, DEFAULT is
assumed. If the specified `section' does not exist, returns False. | [
"Check",
"for",
"the",
"existence",
"of",
"a",
"given",
"option",
"in",
"a",
"given",
"section",
".",
"If",
"the",
"specified",
"section",
"is",
"None",
"or",
"an",
"empty",
"string",
"DEFAULT",
"is",
"assumed",
".",
"If",
"the",
"specified",
"section",
... | def has_option(self, section, option):
"""Check for the existence of a given option in a given section.
If the specified `section' is None or an empty string, DEFAULT is
assumed. If the specified `section' does not exist, returns False."""
if not section or section == self.default_section:
option = self.optionxform(option)
return option in self._defaults
elif section not in self._sections:
return False
else:
option = self.optionxform(option)
return (option in self._sections[section]
or option in self._defaults) | [
"def",
"has_option",
"(",
"self",
",",
"section",
",",
"option",
")",
":",
"if",
"not",
"section",
"or",
"section",
"==",
"self",
".",
"default_section",
":",
"option",
"=",
"self",
".",
"optionxform",
"(",
"option",
")",
"return",
"option",
"in",
"self"... | https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/configparser.py#L877-L889 | ||
plotly/plotly.py | cfad7862594b35965c0e000813bd7805e8494a5b | packages/python/plotly/plotly/graph_objs/scatterpolargl/_marker.py | python | Marker.showscale | (self) | return self["showscale"] | Determines whether or not a colorbar is displayed for this
trace. Has an effect only if in `marker.color`is set to a
numerical array.
The 'showscale' property must be specified as a bool
(either True, or False)
Returns
-------
bool | Determines whether or not a colorbar is displayed for this
trace. Has an effect only if in `marker.color`is set to a
numerical array.
The 'showscale' property must be specified as a bool
(either True, or False) | [
"Determines",
"whether",
"or",
"not",
"a",
"colorbar",
"is",
"displayed",
"for",
"this",
"trace",
".",
"Has",
"an",
"effect",
"only",
"if",
"in",
"marker",
".",
"color",
"is",
"set",
"to",
"a",
"numerical",
"array",
".",
"The",
"showscale",
"property",
"... | def showscale(self):
"""
Determines whether or not a colorbar is displayed for this
trace. Has an effect only if in `marker.color`is set to a
numerical array.
The 'showscale' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["showscale"] | [
"def",
"showscale",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"showscale\"",
"]"
] | https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/scatterpolargl/_marker.py#L762-L775 | |
google/grr | 8ad8a4d2c5a93c92729206b7771af19d92d4f915 | grr/server/grr_response_server/databases/mem_paths.py | python | _PathRecord.AddStatEntry | (self, stat_entry, timestamp) | Registers stat entry at a given timestamp. | Registers stat entry at a given timestamp. | [
"Registers",
"stat",
"entry",
"at",
"a",
"given",
"timestamp",
"."
] | def AddStatEntry(self, stat_entry, timestamp):
"""Registers stat entry at a given timestamp."""
if timestamp in self._stat_entries:
message = ("Duplicated stat entry write for path '%s' of type '%s' at "
"timestamp '%s'. Old: %s. New: %s.")
message %= ("/".join(self._components), self._path_type, timestamp,
self._stat_entries[timestamp], stat_entry)
raise db.Error(message)
if timestamp not in self._path_infos:
path_info = rdf_objects.PathInfo(
path_type=self._path_type,
components=self._components,
timestamp=timestamp,
stat_entry=stat_entry)
self.AddPathInfo(path_info)
else:
self._path_infos[timestamp].stat_entry = stat_entry | [
"def",
"AddStatEntry",
"(",
"self",
",",
"stat_entry",
",",
"timestamp",
")",
":",
"if",
"timestamp",
"in",
"self",
".",
"_stat_entries",
":",
"message",
"=",
"(",
"\"Duplicated stat entry write for path '%s' of type '%s' at \"",
"\"timestamp '%s'. Old: %s. New: %s.\"",
"... | https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/server/grr_response_server/databases/mem_paths.py#L48-L66 | ||
ronf/asyncssh | ee1714c598d8c2ea6f5484e465443f38b68714aa | asyncssh/misc.py | python | parse_time_interval | (value: str) | return _parse_units(value, _time_units, 'time interval') | Parse a time interval with optional s, m, h, d, or w suffixes | Parse a time interval with optional s, m, h, d, or w suffixes | [
"Parse",
"a",
"time",
"interval",
"with",
"optional",
"s",
"m",
"h",
"d",
"or",
"w",
"suffixes"
] | def parse_time_interval(value: str) -> float:
"""Parse a time interval with optional s, m, h, d, or w suffixes"""
return _parse_units(value, _time_units, 'time interval') | [
"def",
"parse_time_interval",
"(",
"value",
":",
"str",
")",
"->",
"float",
":",
"return",
"_parse_units",
"(",
"value",
",",
"_time_units",
",",
"'time interval'",
")"
] | https://github.com/ronf/asyncssh/blob/ee1714c598d8c2ea6f5484e465443f38b68714aa/asyncssh/misc.py#L255-L258 | |
F8LEFT/DecLLVM | d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c | python/idaapi.py | python | strvec_t.truncate | (self, *args) | return _idaapi.strvec_t_truncate(self, *args) | truncate(self) | truncate(self) | [
"truncate",
"(",
"self",
")"
] | def truncate(self, *args):
"""
truncate(self)
"""
return _idaapi.strvec_t_truncate(self, *args) | [
"def",
"truncate",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_idaapi",
".",
"strvec_t_truncate",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L2083-L2087 | |
sympy/sympy | d822fcba181155b85ff2b29fe525adbafb22b448 | sympy/functions/elementary/trigonometric.py | python | _peeloff_pi | (arg) | return arg, S.Zero | Split ARG into two parts, a "rest" and a multiple of pi.
This assumes ARG to be an Add.
The multiple of pi returned in the second position is always a Rational.
Examples
========
>>> from sympy.functions.elementary.trigonometric import _peeloff_pi as peel
>>> from sympy import pi
>>> from sympy.abc import x, y
>>> peel(x + pi/2)
(x, 1/2)
>>> peel(x + 2*pi/3 + pi*y)
(x + pi*y + pi/6, 1/2) | Split ARG into two parts, a "rest" and a multiple of pi.
This assumes ARG to be an Add.
The multiple of pi returned in the second position is always a Rational. | [
"Split",
"ARG",
"into",
"two",
"parts",
"a",
"rest",
"and",
"a",
"multiple",
"of",
"pi",
".",
"This",
"assumes",
"ARG",
"to",
"be",
"an",
"Add",
".",
"The",
"multiple",
"of",
"pi",
"returned",
"in",
"the",
"second",
"position",
"is",
"always",
"a",
"... | def _peeloff_pi(arg):
"""
Split ARG into two parts, a "rest" and a multiple of pi.
This assumes ARG to be an Add.
The multiple of pi returned in the second position is always a Rational.
Examples
========
>>> from sympy.functions.elementary.trigonometric import _peeloff_pi as peel
>>> from sympy import pi
>>> from sympy.abc import x, y
>>> peel(x + pi/2)
(x, 1/2)
>>> peel(x + 2*pi/3 + pi*y)
(x + pi*y + pi/6, 1/2)
"""
pi_coeff = S.Zero
rest_terms = []
for a in Add.make_args(arg):
K = a.coeff(S.Pi)
if K and K.is_rational:
pi_coeff += K
else:
rest_terms.append(a)
if pi_coeff is S.Zero:
return arg, S.Zero
m1 = (pi_coeff % S.Half)
m2 = pi_coeff - m1
if m2.is_integer or ((2*m2).is_integer and m2.is_even is False):
return Add(*(rest_terms + [m1*pi])), m2
return arg, S.Zero | [
"def",
"_peeloff_pi",
"(",
"arg",
")",
":",
"pi_coeff",
"=",
"S",
".",
"Zero",
"rest_terms",
"=",
"[",
"]",
"for",
"a",
"in",
"Add",
".",
"make_args",
"(",
"arg",
")",
":",
"K",
"=",
"a",
".",
"coeff",
"(",
"S",
".",
"Pi",
")",
"if",
"K",
"an... | https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/functions/elementary/trigonometric.py#L96-L130 | |
trezor/trezor-firmware | 5c4703c9bbfb962fbbe409c2e40030f30161e4f0 | core/src/apps/stellar/writers.py | python | write_string | (w: Writer, s: AnyStr) | Write XDR string padded to a multiple of 4 bytes. | Write XDR string padded to a multiple of 4 bytes. | [
"Write",
"XDR",
"string",
"padded",
"to",
"a",
"multiple",
"of",
"4",
"bytes",
"."
] | def write_string(w: Writer, s: AnyStr) -> None:
"""Write XDR string padded to a multiple of 4 bytes."""
if isinstance(s, str):
buf = s.encode()
else:
buf = s
write_uint32(w, len(buf))
write_bytes_unchecked(w, buf)
# if len isn't a multiple of 4, add padding bytes
remainder = len(buf) % 4
if remainder:
write_bytes_unchecked(w, bytes([0] * (4 - remainder))) | [
"def",
"write_string",
"(",
"w",
":",
"Writer",
",",
"s",
":",
"AnyStr",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"buf",
"=",
"s",
".",
"encode",
"(",
")",
"else",
":",
"buf",
"=",
"s",
"write_uint32",
"(",
"w... | https://github.com/trezor/trezor-firmware/blob/5c4703c9bbfb962fbbe409c2e40030f30161e4f0/core/src/apps/stellar/writers.py#L21-L32 | ||
biocore/scikit-bio | ecdfc7941d8c21eb2559ff1ab313d6e9348781da | skbio/stats/composition.py | python | ilr_inv | (mat, basis=None, check=True) | return clr_inv(np.dot(mat, basis)) | r"""
Performs inverse isometric log ratio transform.
This function transforms compositions from the real space to
Aitchison geometry. The :math:`ilr^{-1}` transform is both an isometry,
and an isomorphism defined on the following spaces
:math:`ilr^{-1}: \mathbb{R}^{D-1} \rightarrow S^D`
The inverse ilr transformation is defined as follows
.. math::
ilr^{-1}(x) = \bigoplus\limits_{i=1}^{D-1} x \odot e_i
where :math:`[e_1,\ldots, e_{D-1}]` is an orthonormal basis in the simplex.
If an orthonormal basis isn't specified, the J. J. Egozcue orthonormal
basis derived from Gram-Schmidt orthogonalization will be used by
default.
Parameters
----------
mat: numpy.ndarray, float
a matrix of transformed proportions where
rows = compositions and
columns = components
basis: numpy.ndarray, float, optional
orthonormal basis for Aitchison simplex
defaults to J.J.Egozcue orthonormal basis
check: bool
Specifies if the basis is orthonormal.
Examples
--------
>>> import numpy as np
>>> from skbio.stats.composition import ilr
>>> x = np.array([.1, .3, .6,])
>>> ilr_inv(x)
array([ 0.34180297, 0.29672718, 0.22054469, 0.14092516])
Notes
-----
If the `basis` parameter is specified, it is expected to be a basis in the
Aitchison simplex. If there are `D-1` elements specified in `mat`, then
the dimensions of the basis needs be `D-1 x D`, where rows represent
basis vectors, and the columns represent proportions. | r"""
Performs inverse isometric log ratio transform. | [
"r",
"Performs",
"inverse",
"isometric",
"log",
"ratio",
"transform",
"."
] | def ilr_inv(mat, basis=None, check=True):
r"""
Performs inverse isometric log ratio transform.
This function transforms compositions from the real space to
Aitchison geometry. The :math:`ilr^{-1}` transform is both an isometry,
and an isomorphism defined on the following spaces
:math:`ilr^{-1}: \mathbb{R}^{D-1} \rightarrow S^D`
The inverse ilr transformation is defined as follows
.. math::
ilr^{-1}(x) = \bigoplus\limits_{i=1}^{D-1} x \odot e_i
where :math:`[e_1,\ldots, e_{D-1}]` is an orthonormal basis in the simplex.
If an orthonormal basis isn't specified, the J. J. Egozcue orthonormal
basis derived from Gram-Schmidt orthogonalization will be used by
default.
Parameters
----------
mat: numpy.ndarray, float
a matrix of transformed proportions where
rows = compositions and
columns = components
basis: numpy.ndarray, float, optional
orthonormal basis for Aitchison simplex
defaults to J.J.Egozcue orthonormal basis
check: bool
Specifies if the basis is orthonormal.
Examples
--------
>>> import numpy as np
>>> from skbio.stats.composition import ilr
>>> x = np.array([.1, .3, .6,])
>>> ilr_inv(x)
array([ 0.34180297, 0.29672718, 0.22054469, 0.14092516])
Notes
-----
If the `basis` parameter is specified, it is expected to be a basis in the
Aitchison simplex. If there are `D-1` elements specified in `mat`, then
the dimensions of the basis needs be `D-1 x D`, where rows represent
basis vectors, and the columns represent proportions.
"""
if basis is None:
basis = _gram_schmidt_basis(mat.shape[-1] + 1)
else:
if len(basis.shape) != 2:
raise ValueError("Basis needs to be a 2D matrix, "
"not a %dD matrix." %
(len(basis.shape)))
if check:
_check_orthogonality(basis)
# this is necessary, since the clr function
# performs np.squeeze()
basis = np.atleast_2d(clr(basis))
return clr_inv(np.dot(mat, basis)) | [
"def",
"ilr_inv",
"(",
"mat",
",",
"basis",
"=",
"None",
",",
"check",
"=",
"True",
")",
":",
"if",
"basis",
"is",
"None",
":",
"basis",
"=",
"_gram_schmidt_basis",
"(",
"mat",
".",
"shape",
"[",
"-",
"1",
"]",
"+",
"1",
")",
"else",
":",
"if",
... | https://github.com/biocore/scikit-bio/blob/ecdfc7941d8c21eb2559ff1ab313d6e9348781da/skbio/stats/composition.py#L579-L645 | |
javipalanca/spade | 6a857c2ae0a86b3bdfd20ccfcd28a11e1c6db81e | spade/web.py | python | WebApp.start | (
self,
hostname: Optional[str] = None,
port: Optional[int] = None,
templates_path: Optional[str] = None,
) | return self.agent.submit(
start_server_in_loop(self.runner, self.hostname, self.port, self.agent)
) | Starts the web interface.
Args:
hostname (str, optional): host name to listen from. (Default value = None)
port (int, optional): port to listen from. (Default value = None)
templates_path (str, optional): path to look for templates. (Default value = None) | Starts the web interface. | [
"Starts",
"the",
"web",
"interface",
"."
] | def start(
self,
hostname: Optional[str] = None,
port: Optional[int] = None,
templates_path: Optional[str] = None,
) -> None:
"""
Starts the web interface.
Args:
hostname (str, optional): host name to listen from. (Default value = None)
port (int, optional): port to listen from. (Default value = None)
templates_path (str, optional): path to look for templates. (Default value = None)
"""
self.hostname = hostname if hostname else "localhost"
if port:
self.port = port
elif not self.port:
self.port = unused_port(self.hostname)
if templates_path:
self.loaders.insert(0, jinja2.FileSystemLoader(templates_path))
self._set_loaders()
self.setup_routes()
self.runner = aioweb.AppRunner(self.app)
return self.agent.submit(
start_server_in_loop(self.runner, self.hostname, self.port, self.agent)
) | [
"def",
"start",
"(",
"self",
",",
"hostname",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"port",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"templates_path",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
")",
"->",
"None",
... | https://github.com/javipalanca/spade/blob/6a857c2ae0a86b3bdfd20ccfcd28a11e1c6db81e/spade/web.py#L61-L88 | |
pawamoy/aria2p | 2855c6a9a38e36278671258439f6caf59c39cfc3 | src/aria2p/downloads.py | python | Download.gid | (self) | return self._struct["gid"] | GID of the download.
Returns:
The download GID. | GID of the download. | [
"GID",
"of",
"the",
"download",
"."
] | def gid(self) -> str:
"""
GID of the download.
Returns:
The download GID.
"""
return self._struct["gid"] | [
"def",
"gid",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_struct",
"[",
"\"gid\"",
"]"
] | https://github.com/pawamoy/aria2p/blob/2855c6a9a38e36278671258439f6caf59c39cfc3/src/aria2p/downloads.py#L375-L382 | |
prof7bit/goxtool | e307f12df2df37a3a109953e805ad19d6c6e0628 | goxtool.py | python | WinStatus.slot_orderlag | (self, dummy_sender, (usec, text)) | slot for order_lag mesages | slot for order_lag mesages | [
"slot",
"for",
"order_lag",
"mesages"
] | def slot_orderlag(self, dummy_sender, (usec, text)):
"""slot for order_lag mesages"""
self.order_lag = usec
self.order_lag_txt = text
self.do_paint() | [
"def",
"slot_orderlag",
"(",
"self",
",",
"dummy_sender",
",",
"(",
"usec",
",",
"text",
")",
")",
":",
"self",
".",
"order_lag",
"=",
"usec",
"self",
".",
"order_lag_txt",
"=",
"text",
"self",
".",
"do_paint",
"(",
")"
] | https://github.com/prof7bit/goxtool/blob/e307f12df2df37a3a109953e805ad19d6c6e0628/goxtool.py#L990-L994 | ||
ceph/teuthology | 6fc2011361437a9dfe4e45b50de224392eed8abc | teuthology/config.py | python | YamlConfig.update | (self, in_dict) | Update an existing configuration using dict.update()
:param in_dict: The dict to use to update | Update an existing configuration using dict.update() | [
"Update",
"an",
"existing",
"configuration",
"using",
"dict",
".",
"update",
"()"
] | def update(self, in_dict):
"""
Update an existing configuration using dict.update()
:param in_dict: The dict to use to update
"""
self._conf.update(in_dict) | [
"def",
"update",
"(",
"self",
",",
"in_dict",
")",
":",
"self",
".",
"_conf",
".",
"update",
"(",
"in_dict",
")"
] | https://github.com/ceph/teuthology/blob/6fc2011361437a9dfe4e45b50de224392eed8abc/teuthology/config.py#L46-L52 | ||
suavecode/SUAVE | 4f83c467c5662b6cc611ce2ab6c0bdd25fd5c0a5 | trunk/SUAVE/Methods/Aerodynamics/Common/Fidelity_Zero/Lift/fuselage_correction.py | python | fuselage_correction | (state,settings,geometry) | return aircraft_lift_total | Corrects aircraft lift based on fuselage effects
Assumptions:
None
Source:
adg.stanford.edu (Stanford AA241 A/B Course Notes)
Inputs:
settings.fuselage_lift_correction [Unitless]
state.conditions.
freestream.mach_number [Unitless]
aerodynamics.angle_of_attack [radians]
aerodynamics.lift_coefficient [Unitless]
Outputs:
aircraft_lift_total [Unitless]
Properties Used:
N/A | Corrects aircraft lift based on fuselage effects | [
"Corrects",
"aircraft",
"lift",
"based",
"on",
"fuselage",
"effects"
] | def fuselage_correction(state,settings,geometry):
"""Corrects aircraft lift based on fuselage effects
Assumptions:
None
Source:
adg.stanford.edu (Stanford AA241 A/B Course Notes)
Inputs:
settings.fuselage_lift_correction [Unitless]
state.conditions.
freestream.mach_number [Unitless]
aerodynamics.angle_of_attack [radians]
aerodynamics.lift_coefficient [Unitless]
Outputs:
aircraft_lift_total [Unitless]
Properties Used:
N/A
"""
# unpack
fus_correction = settings.fuselage_lift_correction
wings_lift_comp = state.conditions.aerodynamics.lift_coefficient
# total lift, accounting one fuselage
aircraft_lift_total = wings_lift_comp * fus_correction
state.conditions.aerodynamics.lift_coefficient= aircraft_lift_total
return aircraft_lift_total | [
"def",
"fuselage_correction",
"(",
"state",
",",
"settings",
",",
"geometry",
")",
":",
"# unpack",
"fus_correction",
"=",
"settings",
".",
"fuselage_lift_correction",
"wings_lift_comp",
"=",
"state",
".",
"conditions",
".",
"aerodynamics",
".",
"lift_coefficient",
... | https://github.com/suavecode/SUAVE/blob/4f83c467c5662b6cc611ce2ab6c0bdd25fd5c0a5/trunk/SUAVE/Methods/Aerodynamics/Common/Fidelity_Zero/Lift/fuselage_correction.py#L14-L46 | |
apple/ccs-calendarserver | 13c706b985fb728b9aab42dc0fef85aae21921c3 | txdav/base/datastore/dbapiclient.py | python | DiagnosticCursorWrapper.close | (self) | [] | def close(self):
self.realCursor.close() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"realCursor",
".",
"close",
"(",
")"
] | https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txdav/base/datastore/dbapiclient.py#L84-L85 | ||||
Alescontrela/Numpy-CNN | be15d0139327a690813343a6e15d651fd043fa89 | CNN/backward.py | python | maxpoolBackward | (dpool, orig, f, s) | return dout | Backpropagation through a maxpooling layer. The gradients are passed through the indices of greatest value in the original maxpooling during the forward step. | Backpropagation through a maxpooling layer. The gradients are passed through the indices of greatest value in the original maxpooling during the forward step. | [
"Backpropagation",
"through",
"a",
"maxpooling",
"layer",
".",
"The",
"gradients",
"are",
"passed",
"through",
"the",
"indices",
"of",
"greatest",
"value",
"in",
"the",
"original",
"maxpooling",
"during",
"the",
"forward",
"step",
"."
] | def maxpoolBackward(dpool, orig, f, s):
'''
Backpropagation through a maxpooling layer. The gradients are passed through the indices of greatest value in the original maxpooling during the forward step.
'''
(n_c, orig_dim, _) = orig.shape
dout = np.zeros(orig.shape)
for curr_c in range(n_c):
curr_y = out_y = 0
while curr_y + f <= orig_dim:
curr_x = out_x = 0
while curr_x + f <= orig_dim:
# obtain index of largest value in input for current window
(a, b) = nanargmax(orig[curr_c, curr_y:curr_y+f, curr_x:curr_x+f])
dout[curr_c, curr_y+a, curr_x+b] = dpool[curr_c, out_y, out_x]
curr_x += s
out_x += 1
curr_y += s
out_y += 1
return dout | [
"def",
"maxpoolBackward",
"(",
"dpool",
",",
"orig",
",",
"f",
",",
"s",
")",
":",
"(",
"n_c",
",",
"orig_dim",
",",
"_",
")",
"=",
"orig",
".",
"shape",
"dout",
"=",
"np",
".",
"zeros",
"(",
"orig",
".",
"shape",
")",
"for",
"curr_c",
"in",
"r... | https://github.com/Alescontrela/Numpy-CNN/blob/be15d0139327a690813343a6e15d651fd043fa89/CNN/backward.py#L48-L70 | |
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.9.40/roles/openshift_facts/library/openshift_facts.py | python | set_buildoverrides_facts | (facts) | return facts | Set build overrides
Args:
facts(dict): existing facts
Returns:
facts(dict): Updated facts with missing values | Set build overrides | [
"Set",
"build",
"overrides"
] | def set_buildoverrides_facts(facts):
""" Set build overrides
Args:
facts(dict): existing facts
Returns:
facts(dict): Updated facts with missing values
"""
if 'buildoverrides' in facts:
buildoverrides = facts['buildoverrides']
# If we're actually defining a buildoverrides config then create admission_plugin_config
# then merge buildoverrides[config] structure into admission_plugin_config
if 'config' in buildoverrides:
if 'admission_plugin_config' not in facts['master']:
facts['master']['admission_plugin_config'] = dict()
facts['master']['admission_plugin_config'].update(buildoverrides['config'])
return facts | [
"def",
"set_buildoverrides_facts",
"(",
"facts",
")",
":",
"if",
"'buildoverrides'",
"in",
"facts",
":",
"buildoverrides",
"=",
"facts",
"[",
"'buildoverrides'",
"]",
"# If we're actually defining a buildoverrides config then create admission_plugin_config",
"# then merge buildov... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/openshift_facts/library/openshift_facts.py#L1227-L1244 | |
angr/angr | 4b04d56ace135018083d36d9083805be8146688b | angr/exploration_techniques/__init__.py | python | ExplorationTechnique.setup | (self, simgr) | Perform any initialization on this manager you might need to do.
:param angr.SimulationManager simgr: The simulation manager to which you have just been added | Perform any initialization on this manager you might need to do. | [
"Perform",
"any",
"initialization",
"on",
"this",
"manager",
"you",
"might",
"need",
"to",
"do",
"."
] | def setup(self, simgr):
"""
Perform any initialization on this manager you might need to do.
:param angr.SimulationManager simgr: The simulation manager to which you have just been added
"""
pass | [
"def",
"setup",
"(",
"self",
",",
"simgr",
")",
":",
"pass"
] | https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/exploration_techniques/__init__.py#L74-L80 | ||
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/key.py | python | Key.gen_keys | (self, keydir=None, keyname=None, keysize=None, user=None) | return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + ".pub")) | Generate minion RSA public keypair | Generate minion RSA public keypair | [
"Generate",
"minion",
"RSA",
"public",
"keypair"
] | def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
"""
Generate minion RSA public keypair
"""
keydir, keyname, keysize, user = self._get_key_attrs(
keydir, keyname, keysize, user
)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + ".pub")) | [
"def",
"gen_keys",
"(",
"self",
",",
"keydir",
"=",
"None",
",",
"keyname",
"=",
"None",
",",
"keysize",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"keydir",
",",
"keyname",
",",
"keysize",
",",
"user",
"=",
"self",
".",
"_get_key_attrs",
"(",
... | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/key.py#L356-L364 | |
IronLanguages/ironpython3 | 7a7bb2a872eeab0d1009fc8a6e24dca43f65b693 | Src/StdLib/Lib/smtplib.py | python | SMTP.noop | (self) | return self.docmd("noop") | SMTP 'noop' command -- doesn't do anything :> | SMTP 'noop' command -- doesn't do anything :> | [
"SMTP",
"noop",
"command",
"--",
"doesn",
"t",
"do",
"anything",
":",
">"
] | def noop(self):
"""SMTP 'noop' command -- doesn't do anything :>"""
return self.docmd("noop") | [
"def",
"noop",
"(",
"self",
")",
":",
"return",
"self",
".",
"docmd",
"(",
"\"noop\"",
")"
] | https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/smtplib.py#L494-L496 | |
getpatchwork/patchwork | 60a7b11d12f9e1a6bd08d787d37066c8d89a52ae | patchwork/models.py | python | EmailMixin.patch_responses | (self) | return ''.join([match.group(0) + '\n' for match in
self.response_re.finditer(self.content)]) | [] | def patch_responses(self):
if not self.content:
return ''
return ''.join([match.group(0) + '\n' for match in
self.response_re.finditer(self.content)]) | [
"def",
"patch_responses",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"content",
":",
"return",
"''",
"return",
"''",
".",
"join",
"(",
"[",
"match",
".",
"group",
"(",
"0",
")",
"+",
"'\\n'",
"for",
"match",
"in",
"self",
".",
"response_re",
... | https://github.com/getpatchwork/patchwork/blob/60a7b11d12f9e1a6bd08d787d37066c8d89a52ae/patchwork/models.py#L324-L329 | |||
PaloAltoNetworks/pan-os-python | 30f6cd9e29d0e3c2549d46c722f6dcb507acd437 | panos/base.py | python | PanObject.about | (self, parameter=None) | Return information about this object or the given parameter.
If no parameter is specified, then invoking this function is similar to
doing `vars(obj)`: it will return a dict of key/value pairs, with the
difference being that the keys are all specifically parameters attached
to this `VersionedPanObject`, and the values being what the current
settings are for those keys.
If a parameter is specified and this object is connected to a
parent PanDevice, then version specific information on the parameter
is returned.
If a parameter is specified but this object is not connected to a
PanDevice instance, then all versioning information for the given
parameter is returned.
Args:
parameter (str): The parameter to get info for.
Returns:
dict: An informational dict about either the object as a whole
or the specified parameter.
Raises:
AttributeError: If a parameter is specified that does not exist
on this object. | Return information about this object or the given parameter. | [
"Return",
"information",
"about",
"this",
"object",
"or",
"the",
"given",
"parameter",
"."
] | def about(self, parameter=None):
"""Return information about this object or the given parameter.
If no parameter is specified, then invoking this function is similar to
doing `vars(obj)`: it will return a dict of key/value pairs, with the
difference being that the keys are all specifically parameters attached
to this `VersionedPanObject`, and the values being what the current
settings are for those keys.
If a parameter is specified and this object is connected to a
parent PanDevice, then version specific information on the parameter
is returned.
If a parameter is specified but this object is not connected to a
PanDevice instance, then all versioning information for the given
parameter is returned.
Args:
parameter (str): The parameter to get info for.
Returns:
dict: An informational dict about either the object as a whole
or the specified parameter.
Raises:
AttributeError: If a parameter is specified that does not exist
on this object.
"""
if parameter is None:
return self._about_object()
else:
return self._about_parameter(parameter) | [
"def",
"about",
"(",
"self",
",",
"parameter",
"=",
"None",
")",
":",
"if",
"parameter",
"is",
"None",
":",
"return",
"self",
".",
"_about_object",
"(",
")",
"else",
":",
"return",
"self",
".",
"_about_parameter",
"(",
"parameter",
")"
] | https://github.com/PaloAltoNetworks/pan-os-python/blob/30f6cd9e29d0e3c2549d46c722f6dcb507acd437/panos/base.py#L1716-L1748 | ||
aiidateam/aiida-core | c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2 | aiida/transports/plugins/local.py | python | LocalTransport.copy | (self, remotesource, remotedestination, dereference=False, recursive=True) | Copies a file or a folder from 'remote' remotesource to 'remote' remotedestination.
Automatically redirects to copyfile or copytree.
:param remotesource: path to local file
:param remotedestination: path to remote file
:param dereference: follow symbolic links. Default = False
:param recursive: if True copy directories recursively, otherwise only copy the specified file(s)
:type recursive: bool
:raise ValueError: if 'remote' remotesource or remotedestinationis not valid
:raise OSError: if remotesource does not exist | Copies a file or a folder from 'remote' remotesource to 'remote' remotedestination.
Automatically redirects to copyfile or copytree. | [
"Copies",
"a",
"file",
"or",
"a",
"folder",
"from",
"remote",
"remotesource",
"to",
"remote",
"remotedestination",
".",
"Automatically",
"redirects",
"to",
"copyfile",
"or",
"copytree",
"."
] | def copy(self, remotesource, remotedestination, dereference=False, recursive=True):
"""
Copies a file or a folder from 'remote' remotesource to 'remote' remotedestination.
Automatically redirects to copyfile or copytree.
:param remotesource: path to local file
:param remotedestination: path to remote file
:param dereference: follow symbolic links. Default = False
:param recursive: if True copy directories recursively, otherwise only copy the specified file(s)
:type recursive: bool
:raise ValueError: if 'remote' remotesource or remotedestinationis not valid
:raise OSError: if remotesource does not exist
"""
if not remotesource:
raise ValueError('Input remotesource to copy must be a non empty object')
if not remotedestination:
raise ValueError('Input remotedestination to copy must be a non empty object')
if not self.has_magic(remotesource):
if not os.path.exists(os.path.join(self.curdir, remotesource)):
raise OSError('Source not found')
if self.normalize(remotesource) == self.normalize(remotedestination):
raise ValueError('Cannot copy from itself to itself')
# # by default, overwrite old files
# if not remotedestination .startswith('.'):
# if self.isfile(remotedestination) or self.isdir(remotedestination):
# self.rmtree(remotedestination)
the_destination = os.path.join(self.curdir, remotedestination)
if self.has_magic(remotesource):
if self.has_magic(remotedestination):
raise ValueError('Pathname patterns are not allowed in the remotedestination')
to_copy_list = self.glob(remotesource)
if len(to_copy_list) > 1:
if not self.path_exists(remotedestination) or self.isfile(remotedestination):
raise OSError("Can't copy more than one file in the same remotedestination file")
for source in to_copy_list:
# If s is an absolute path, then the_s = s
the_s = os.path.join(self.curdir, source)
if self.isfile(source):
# With shutil, use the full path (the_s)
shutil.copy(the_s, the_destination)
else:
# With self.copytree, the (possible) relative path is OK
self.copytree(source, remotedestination, dereference)
else:
# If s is an absolute path, then the_source = remotesource
the_source = os.path.join(self.curdir, remotesource)
if self.isfile(remotesource):
# With shutil, use the full path (the_source)
shutil.copy(the_source, the_destination)
else:
# With self.copytree, the (possible) relative path is OK
self.copytree(remotesource, remotedestination, dereference) | [
"def",
"copy",
"(",
"self",
",",
"remotesource",
",",
"remotedestination",
",",
"dereference",
"=",
"False",
",",
"recursive",
"=",
"True",
")",
":",
"if",
"not",
"remotesource",
":",
"raise",
"ValueError",
"(",
"'Input remotesource to copy must be a non empty objec... | https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/transports/plugins/local.py#L533-L592 | ||
python273/vk_api | 1ef82594baabc80802ef4792aceee9180ae3e9c9 | vk_api/keyboard.py | python | VkKeyboard.get_empty_keyboard | (cls) | return keyboard.get_keyboard() | Получить json пустой клавиатуры.
Если отправить пустую клавиатуру, текущая у пользователя исчезнет. | Получить json пустой клавиатуры.
Если отправить пустую клавиатуру, текущая у пользователя исчезнет. | [
"Получить",
"json",
"пустой",
"клавиатуры",
".",
"Если",
"отправить",
"пустую",
"клавиатуру",
"текущая",
"у",
"пользователя",
"исчезнет",
"."
] | def get_empty_keyboard(cls):
""" Получить json пустой клавиатуры.
Если отправить пустую клавиатуру, текущая у пользователя исчезнет.
"""
keyboard = cls()
keyboard.keyboard['buttons'] = []
return keyboard.get_keyboard() | [
"def",
"get_empty_keyboard",
"(",
"cls",
")",
":",
"keyboard",
"=",
"cls",
"(",
")",
"keyboard",
".",
"keyboard",
"[",
"'buttons'",
"]",
"=",
"[",
"]",
"return",
"keyboard",
".",
"get_keyboard",
"(",
")"
] | https://github.com/python273/vk_api/blob/1ef82594baabc80802ef4792aceee9180ae3e9c9/vk_api/keyboard.py#L81-L87 | |
zhang-can/ECO-pytorch | 355c3866b35cdaa5d451263c1f3291c150e22eeb | tf_model_zoo/models/im2txt/im2txt/inference_utils/inference_wrapper_base.py | python | InferenceWrapperBase.build_model | (self, model_config) | Builds the model for inference.
Args:
model_config: Object containing configuration for building the model.
Returns:
model: The model object. | Builds the model for inference. | [
"Builds",
"the",
"model",
"for",
"inference",
"."
] | def build_model(self, model_config):
"""Builds the model for inference.
Args:
model_config: Object containing configuration for building the model.
Returns:
model: The model object.
"""
tf.logging.fatal("Please implement build_model in subclass") | [
"def",
"build_model",
"(",
"self",
",",
"model_config",
")",
":",
"tf",
".",
"logging",
".",
"fatal",
"(",
"\"Please implement build_model in subclass\"",
")"
] | https://github.com/zhang-can/ECO-pytorch/blob/355c3866b35cdaa5d451263c1f3291c150e22eeb/tf_model_zoo/models/im2txt/im2txt/inference_utils/inference_wrapper_base.py#L62-L71 | ||
openedx/edx-platform | 68dd185a0ab45862a2a61e0f803d7e03d2be71b5 | common/djangoapps/terrain/stubs/lti.py | python | StubLtiHandler._send_lti2_delete | (self) | return self._send_lti2(payload) | Send a delete back to consumer | Send a delete back to consumer | [
"Send",
"a",
"delete",
"back",
"to",
"consumer"
] | def _send_lti2_delete(self):
"""
Send a delete back to consumer
"""
payload = textwrap.dedent("""
{
"@context" : "http://purl.imsglobal.org/ctx/lis/v2/Result",
"@type" : "Result"
}
""")
return self._send_lti2(payload) | [
"def",
"_send_lti2_delete",
"(",
"self",
")",
":",
"payload",
"=",
"textwrap",
".",
"dedent",
"(",
"\"\"\"\n {\n \"@context\" : \"http://purl.imsglobal.org/ctx/lis/v2/Result\",\n \"@type\" : \"Result\"\n }\n \"\"\"",
")",
"return",
"self",
".",
... | https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/common/djangoapps/terrain/stubs/lti.py#L157-L167 | |
errbotio/errbot | 66e1de8e1d7daa62be7f9ed1b2ac8832f09fa25d | errbot/botplugin.py | python | BotPlugin.callback_mention | (
self, message: Message, mentioned_people: Sequence[Identifier]
) | Triggered if there are mentioned people in message.
Override this method to get notified when someone was mentioned in message.
[Note: This might not be implemented by all backends.]
:param message:
representing the message that was received.
:param mentioned_people:
all mentioned people in this message. | Triggered if there are mentioned people in message. | [
"Triggered",
"if",
"there",
"are",
"mentioned",
"people",
"in",
"message",
"."
] | def callback_mention(
self, message: Message, mentioned_people: Sequence[Identifier]
) -> None:
"""
Triggered if there are mentioned people in message.
Override this method to get notified when someone was mentioned in message.
[Note: This might not be implemented by all backends.]
:param message:
representing the message that was received.
:param mentioned_people:
all mentioned people in this message.
"""
pass | [
"def",
"callback_mention",
"(",
"self",
",",
"message",
":",
"Message",
",",
"mentioned_people",
":",
"Sequence",
"[",
"Identifier",
"]",
")",
"->",
"None",
":",
"pass"
] | https://github.com/errbotio/errbot/blob/66e1de8e1d7daa62be7f9ed1b2ac8832f09fa25d/errbot/botplugin.py#L484-L498 | ||
Phype/telnet-iot-honeypot | f1d4b75245d72990d339668f37a1670fc85c0c9b | honeypot/shell/shell.py | python | Env.write | (self, string) | [] | def write(self, string):
self.output(string) | [
"def",
"write",
"(",
"self",
",",
"string",
")",
":",
"self",
".",
"output",
"(",
"string",
")"
] | https://github.com/Phype/telnet-iot-honeypot/blob/f1d4b75245d72990d339668f37a1670fc85c0c9b/honeypot/shell/shell.py#L55-L56 | ||||
MrGiovanni/UNetPlusPlus | e145ba63862982bf1099cf2ec11d5466b434ae0b | keras/segmentation_models/backbones/inception_resnet_v2.py | python | InceptionResNetV2 | (include_top=True,
weights='imagenet',
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000) | return model | Instantiates the Inception-ResNet v2 architecture.
Optionally loads weights pre-trained on ImageNet.
Note that when using TensorFlow, for best performance you should
set `"image_data_format": "channels_last"` in your Keras config
at `~/.keras/keras.json`.
The model and the weights are compatible with TensorFlow, Theano and
CNTK backends. The data format convention used by the model is
the one specified in your Keras config file.
Note that the default input image size for this model is 299x299, instead
of 224x224 as in the VGG16 and ResNet models. Also, the input preprocessing
function is different (i.e., do not use `imagenet_utils.preprocess_input()`
with this model. Use `preprocess_input()` defined in this module instead).
# Arguments
include_top: whether to include the fully-connected
layer at the top of the network.
weights: one of `None` (random initialization),
'imagenet' (pre-training on ImageNet),
or the path to the weights file to be loaded.
input_tensor: optional Keras tensor (i.e. output of `layers.Input()`)
to use as image input for the model.
input_shape: optional shape tuple, only to be specified
if `include_top` is `False` (otherwise the input shape
has to be `(299, 299, 3)` (with `'channels_last'` data format)
or `(3, 299, 299)` (with `'channels_first'` data format).
It should have exactly 3 inputs channels,
and width and height should be no smaller than 139.
E.g. `(150, 150, 3)` would be one valid value.
pooling: Optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model will be
the 4D tensor output of the last convolutional layer.
- `'avg'` means that global average pooling
will be applied to the output of the
last convolutional layer, and thus
the output of the model will be a 2D tensor.
- `'max'` means that global max pooling will be applied.
classes: optional number of classes to classify images
into, only to be specified if `include_top` is `True`, and
if no `weights` argument is specified.
# Returns
A Keras `Model` instance.
# Raises
ValueError: in case of invalid argument for `weights`,
or invalid input shape. | Instantiates the Inception-ResNet v2 architecture.
Optionally loads weights pre-trained on ImageNet.
Note that when using TensorFlow, for best performance you should
set `"image_data_format": "channels_last"` in your Keras config
at `~/.keras/keras.json`.
The model and the weights are compatible with TensorFlow, Theano and
CNTK backends. The data format convention used by the model is
the one specified in your Keras config file.
Note that the default input image size for this model is 299x299, instead
of 224x224 as in the VGG16 and ResNet models. Also, the input preprocessing
function is different (i.e., do not use `imagenet_utils.preprocess_input()`
with this model. Use `preprocess_input()` defined in this module instead).
# Arguments
include_top: whether to include the fully-connected
layer at the top of the network.
weights: one of `None` (random initialization),
'imagenet' (pre-training on ImageNet),
or the path to the weights file to be loaded.
input_tensor: optional Keras tensor (i.e. output of `layers.Input()`)
to use as image input for the model.
input_shape: optional shape tuple, only to be specified
if `include_top` is `False` (otherwise the input shape
has to be `(299, 299, 3)` (with `'channels_last'` data format)
or `(3, 299, 299)` (with `'channels_first'` data format).
It should have exactly 3 inputs channels,
and width and height should be no smaller than 139.
E.g. `(150, 150, 3)` would be one valid value.
pooling: Optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model will be
the 4D tensor output of the last convolutional layer.
- `'avg'` means that global average pooling
will be applied to the output of the
last convolutional layer, and thus
the output of the model will be a 2D tensor.
- `'max'` means that global max pooling will be applied.
classes: optional number of classes to classify images
into, only to be specified if `include_top` is `True`, and
if no `weights` argument is specified.
# Returns
A Keras `Model` instance.
# Raises
ValueError: in case of invalid argument for `weights`,
or invalid input shape. | [
"Instantiates",
"the",
"Inception",
"-",
"ResNet",
"v2",
"architecture",
".",
"Optionally",
"loads",
"weights",
"pre",
"-",
"trained",
"on",
"ImageNet",
".",
"Note",
"that",
"when",
"using",
"TensorFlow",
"for",
"best",
"performance",
"you",
"should",
"set",
"... | def InceptionResNetV2(include_top=True,
weights='imagenet',
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000):
"""Instantiates the Inception-ResNet v2 architecture.
Optionally loads weights pre-trained on ImageNet.
Note that when using TensorFlow, for best performance you should
set `"image_data_format": "channels_last"` in your Keras config
at `~/.keras/keras.json`.
The model and the weights are compatible with TensorFlow, Theano and
CNTK backends. The data format convention used by the model is
the one specified in your Keras config file.
Note that the default input image size for this model is 299x299, instead
of 224x224 as in the VGG16 and ResNet models. Also, the input preprocessing
function is different (i.e., do not use `imagenet_utils.preprocess_input()`
with this model. Use `preprocess_input()` defined in this module instead).
# Arguments
include_top: whether to include the fully-connected
layer at the top of the network.
weights: one of `None` (random initialization),
'imagenet' (pre-training on ImageNet),
or the path to the weights file to be loaded.
input_tensor: optional Keras tensor (i.e. output of `layers.Input()`)
to use as image input for the model.
input_shape: optional shape tuple, only to be specified
if `include_top` is `False` (otherwise the input shape
has to be `(299, 299, 3)` (with `'channels_last'` data format)
or `(3, 299, 299)` (with `'channels_first'` data format).
It should have exactly 3 inputs channels,
and width and height should be no smaller than 139.
E.g. `(150, 150, 3)` would be one valid value.
pooling: Optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model will be
the 4D tensor output of the last convolutional layer.
- `'avg'` means that global average pooling
will be applied to the output of the
last convolutional layer, and thus
the output of the model will be a 2D tensor.
- `'max'` means that global max pooling will be applied.
classes: optional number of classes to classify images
into, only to be specified if `include_top` is `True`, and
if no `weights` argument is specified.
# Returns
A Keras `Model` instance.
# Raises
ValueError: in case of invalid argument for `weights`,
or invalid input shape.
"""
if not (weights in {'imagenet', None} or os.path.exists(weights)):
raise ValueError('The `weights` argument should be either '
'`None` (random initialization), `imagenet` '
'(pre-training on ImageNet), '
'or the path to the weights file to be loaded.')
if weights == 'imagenet' and include_top and classes != 1000:
raise ValueError('If using `weights` as imagenet with `include_top`'
' as true, `classes` should be 1000')
# Determine proper input shape
input_shape = _obtain_input_shape(
input_shape,
default_size=299,
min_size=139,
data_format=K.image_data_format(),
require_flatten=False,
weights=weights)
if input_tensor is None:
img_input = Input(shape=input_shape)
else:
if not K.is_keras_tensor(input_tensor):
img_input = Input(tensor=input_tensor, shape=input_shape)
else:
img_input = input_tensor
# Stem block: 35 x 35 x 192
x = conv2d_bn(img_input, 32, 3, strides=2, padding='same')
x = conv2d_bn(x, 32, 3, padding='same')
x = conv2d_bn(x, 64, 3)
x = MaxPooling2D(3, strides=2, padding='same')(x)
x = conv2d_bn(x, 80, 1, padding='same')
x = conv2d_bn(x, 192, 3, padding='same')
x = MaxPooling2D(3, strides=2, padding='same')(x)
# Mixed 5b (Inception-A block): 35 x 35 x 320
branch_0 = conv2d_bn(x, 96, 1)
branch_1 = conv2d_bn(x, 48, 1)
branch_1 = conv2d_bn(branch_1, 64, 5)
branch_2 = conv2d_bn(x, 64, 1)
branch_2 = conv2d_bn(branch_2, 96, 3)
branch_2 = conv2d_bn(branch_2, 96, 3)
branch_pool = AveragePooling2D(3, strides=1, padding='same')(x)
branch_pool = conv2d_bn(branch_pool, 64, 1)
branches = [branch_0, branch_1, branch_2, branch_pool]
channel_axis = 1 if K.image_data_format() == 'channels_first' else 3
x = Concatenate(axis=channel_axis, name='mixed_5b')(branches)
# 10x block35 (Inception-ResNet-A block): 35 x 35 x 320
for block_idx in range(1, 11):
x = inception_resnet_block(x,
scale=0.17,
block_type='block35',
block_idx=block_idx)
# Mixed 6a (Reduction-A block): 17 x 17 x 1088
branch_0 = conv2d_bn(x, 384, 3, strides=2, padding='same')
branch_1 = conv2d_bn(x, 256, 1)
branch_1 = conv2d_bn(branch_1, 256, 3)
branch_1 = conv2d_bn(branch_1, 384, 3, strides=2, padding='same')
branch_pool = MaxPooling2D(3, strides=2, padding='same')(x)
branches = [branch_0, branch_1, branch_pool]
x = Concatenate(axis=channel_axis, name='mixed_6a')(branches)
# 20x block17 (Inception-ResNet-B block): 17 x 17 x 1088
for block_idx in range(1, 21):
x = inception_resnet_block(x,
scale=0.1,
block_type='block17',
block_idx=block_idx)
# Mixed 7a (Reduction-B block): 8 x 8 x 2080
branch_0 = conv2d_bn(x, 256, 1)
branch_0 = conv2d_bn(branch_0, 384, 3, strides=2, padding='same')
branch_1 = conv2d_bn(x, 256, 1)
branch_1 = conv2d_bn(branch_1, 288, 3, strides=2, padding='same')
branch_2 = conv2d_bn(x, 256, 1)
branch_2 = conv2d_bn(branch_2, 288, 3)
branch_2 = conv2d_bn(branch_2, 320, 3, strides=2, padding='same')
branch_pool = MaxPooling2D(3, strides=2, padding='same')(x)
branches = [branch_0, branch_1, branch_2, branch_pool]
x = Concatenate(axis=channel_axis, name='mixed_7a')(branches)
# 10x block8 (Inception-ResNet-C block): 8 x 8 x 2080
for block_idx in range(1, 10):
x = inception_resnet_block(x,
scale=0.2,
block_type='block8',
block_idx=block_idx)
x = inception_resnet_block(x,
scale=1.,
activation=None,
block_type='block8',
block_idx=10)
# Final convolution block: 8 x 8 x 1536
x = conv2d_bn(x, 1536, 1, name='conv_7b')
if include_top:
# Classification block
x = GlobalAveragePooling2D(name='avg_pool')(x)
x = Dense(classes, activation='softmax', name='predictions')(x)
else:
if pooling == 'avg':
x = GlobalAveragePooling2D()(x)
elif pooling == 'max':
x = GlobalMaxPooling2D()(x)
# Ensure that the model takes into account
# any potential predecessors of `input_tensor`
if input_tensor is not None:
inputs = get_source_inputs(input_tensor)
else:
inputs = img_input
# Create model
model = Model(inputs, x, name='inception_resnet_v2')
# Load weights
if weights == 'imagenet':
if K.image_data_format() == 'channels_first':
if K.backend() == 'tensorflow':
warnings.warn('You are using the TensorFlow backend, yet you '
'are using the Theano '
'image data format convention '
'(`image_data_format="channels_first"`). '
'For best performance, set '
'`image_data_format="channels_last"` in '
'your Keras config '
'at ~/.keras/keras.json.')
if include_top:
fname = 'inception_resnet_v2_weights_tf_dim_ordering_tf_kernels.h5'
weights_path = get_file(fname,
BASE_WEIGHT_URL + fname,
cache_subdir='models',
file_hash='e693bd0210a403b3192acc6073ad2e96')
else:
fname = 'inception_resnet_v2_weights_tf_dim_ordering_tf_kernels_notop.h5'
weights_path = get_file(fname,
BASE_WEIGHT_URL + fname,
cache_subdir='models',
file_hash='d19885ff4a710c122648d3b5c3b684e4')
model.load_weights(weights_path)
elif weights is not None:
model.load_weights(weights)
return model | [
"def",
"InceptionResNetV2",
"(",
"include_top",
"=",
"True",
",",
"weights",
"=",
"'imagenet'",
",",
"input_tensor",
"=",
"None",
",",
"input_shape",
"=",
"None",
",",
"pooling",
"=",
"None",
",",
"classes",
"=",
"1000",
")",
":",
"if",
"not",
"(",
"weig... | https://github.com/MrGiovanni/UNetPlusPlus/blob/e145ba63862982bf1099cf2ec11d5466b434ae0b/keras/segmentation_models/backbones/inception_resnet_v2.py#L173-L371 | |
hyperledger/aries-cloudagent-python | 2f36776e99f6053ae92eed8123b5b1b2e891c02a | aries_cloudagent/indy/sdk/error.py | python | IndyErrorHandler.__enter__ | (self) | return self | Enter the context manager. | Enter the context manager. | [
"Enter",
"the",
"context",
"manager",
"."
] | def __enter__(self):
"""Enter the context manager."""
return self | [
"def",
"__enter__",
"(",
"self",
")",
":",
"return",
"self"
] | https://github.com/hyperledger/aries-cloudagent-python/blob/2f36776e99f6053ae92eed8123b5b1b2e891c02a/aries_cloudagent/indy/sdk/error.py#L18-L20 | |
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | Python-2.7.13/Lib/xmllib.py | python | XMLParser.parse_comment | (self, i) | return res.end(0) | [] | def parse_comment(self, i):
rawdata = self.rawdata
if rawdata[i:i+4] != '<!--':
raise Error('unexpected call to handle_comment')
res = commentclose.search(rawdata, i+4)
if res is None:
return -1
if doubledash.search(rawdata, i+4, res.start(0)):
self.syntax_error("`--' inside comment")
if rawdata[res.start(0)-1] == '-':
self.syntax_error('comment cannot end in three dashes')
if not self.__accept_utf8 and \
illegal.search(rawdata, i+4, res.start(0)):
self.syntax_error('illegal character in comment')
self.handle_comment(rawdata[i+4: res.start(0)])
return res.end(0) | [
"def",
"parse_comment",
"(",
"self",
",",
"i",
")",
":",
"rawdata",
"=",
"self",
".",
"rawdata",
"if",
"rawdata",
"[",
"i",
":",
"i",
"+",
"4",
"]",
"!=",
"'<!--'",
":",
"raise",
"Error",
"(",
"'unexpected call to handle_comment'",
")",
"res",
"=",
"co... | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/xmllib.py#L426-L441 | |||
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/modules/zypperpkg.py | python | _Zypper.__call__ | (self, *args, **kwargs) | return self | :param args:
:param kwargs:
:return: | :param args:
:param kwargs:
:return: | [
":",
"param",
"args",
":",
":",
"param",
"kwargs",
":",
":",
"return",
":"
] | def __call__(self, *args, **kwargs):
"""
:param args:
:param kwargs:
:return:
"""
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if "no_repo_failure" in kwargs:
self.__ignore_repo_failure = kwargs["no_repo_failure"]
if "systemd_scope" in kwargs:
self.__systemd_scope = kwargs["systemd_scope"]
if "root" in kwargs:
self.__root = kwargs["root"]
return self | [
"def",
"__call__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Reset after the call",
"if",
"self",
".",
"__called",
":",
"self",
".",
"_reset",
"(",
")",
"# Ignore exit code for 106 (repo is not available)",
"if",
"\"no_repo_failure\"",
... | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/zypperpkg.py#L138-L155 | |
guildai/guildai | 1665985a3d4d788efc1a3180ca51cc417f71ca78 | guild/external/pip/_vendor/urllib3/contrib/socks.py | python | SOCKSConnection._new_conn | (self) | return conn | Establish a new connection via the SOCKS proxy. | Establish a new connection via the SOCKS proxy. | [
"Establish",
"a",
"new",
"connection",
"via",
"the",
"SOCKS",
"proxy",
"."
] | def _new_conn(self):
"""
Establish a new connection via the SOCKS proxy.
"""
extra_kw = {}
if self.source_address:
extra_kw['source_address'] = self.source_address
if self.socket_options:
extra_kw['socket_options'] = self.socket_options
try:
conn = socks.create_connection(
(self.host, self.port),
proxy_type=self._socks_options['socks_version'],
proxy_addr=self._socks_options['proxy_host'],
proxy_port=self._socks_options['proxy_port'],
proxy_username=self._socks_options['username'],
proxy_password=self._socks_options['password'],
proxy_rdns=self._socks_options['rdns'],
timeout=self.timeout,
**extra_kw
)
except SocketTimeout as e:
raise ConnectTimeoutError(
self, "Connection to %s timed out. (connect timeout=%s)" %
(self.host, self.timeout))
except socks.ProxyError as e:
# This is fragile as hell, but it seems to be the only way to raise
# useful errors here.
if e.socket_err:
error = e.socket_err
if isinstance(error, SocketTimeout):
raise ConnectTimeoutError(
self,
"Connection to %s timed out. (connect timeout=%s)" %
(self.host, self.timeout)
)
else:
raise NewConnectionError(
self,
"Failed to establish a new connection: %s" % error
)
else:
raise NewConnectionError(
self,
"Failed to establish a new connection: %s" % e
)
except SocketError as e: # Defensive: PySocks should catch all these.
raise NewConnectionError(
self, "Failed to establish a new connection: %s" % e)
return conn | [
"def",
"_new_conn",
"(",
"self",
")",
":",
"extra_kw",
"=",
"{",
"}",
"if",
"self",
".",
"source_address",
":",
"extra_kw",
"[",
"'source_address'",
"]",
"=",
"self",
".",
"source_address",
"if",
"self",
".",
"socket_options",
":",
"extra_kw",
"[",
"'socke... | https://github.com/guildai/guildai/blob/1665985a3d4d788efc1a3180ca51cc417f71ca78/guild/external/pip/_vendor/urllib3/contrib/socks.py#L67-L122 | |
missionpinball/mpf | 8e6b74cff4ba06d2fec9445742559c1068b88582 | mpf/platforms/pololu/pololu_ticcmd_wrapper.py | python | PololuTiccmdWrapper._run_loop | (self) | Run the asyncio loop in this thread. | Run the asyncio loop in this thread. | [
"Run",
"the",
"asyncio",
"loop",
"in",
"this",
"thread",
"."
] | def _run_loop(self):
"""Run the asyncio loop in this thread."""
asyncio.set_event_loop(self.loop)
self.stop_future = asyncio.Future()
self.loop.run_until_complete(self.stop_future)
self.loop.close() | [
"def",
"_run_loop",
"(",
"self",
")",
":",
"asyncio",
".",
"set_event_loop",
"(",
"self",
".",
"loop",
")",
"self",
".",
"stop_future",
"=",
"asyncio",
".",
"Future",
"(",
")",
"self",
".",
"loop",
".",
"run_until_complete",
"(",
"self",
".",
"stop_futur... | https://github.com/missionpinball/mpf/blob/8e6b74cff4ba06d2fec9445742559c1068b88582/mpf/platforms/pololu/pololu_ticcmd_wrapper.py#L46-L51 | ||
LandGrey/ClassHound | ccf09aea102ca6633027f18dbb8c9f217f4b3190 | classhound.py | python | disk_path_to_url_dir_path | (disk_path) | return url_dir, url_path | :param disk_path:
:return: /WEB-INF/config', '/WEB-INF/config/cache-context.xml | :param disk_path:
:return: /WEB-INF/config', '/WEB-INF/config/cache-context.xml | [
":",
"param",
"disk_path",
":",
":",
"return",
":",
"/",
"WEB",
"-",
"INF",
"/",
"config",
"/",
"WEB",
"-",
"INF",
"/",
"config",
"/",
"cache",
"-",
"context",
".",
"xml"
] | def disk_path_to_url_dir_path(disk_path):
"""
:param disk_path:
:return: /WEB-INF/config', '/WEB-INF/config/cache-context.xml
"""
url_path = os.path.abspath(disk_path)[len(os.path.abspath(workspace)):].replace('\\', '/')
url_dir = os.path.split(url_path)[0]
return url_dir, url_path | [
"def",
"disk_path_to_url_dir_path",
"(",
"disk_path",
")",
":",
"url_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"disk_path",
")",
"[",
"len",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"workspace",
")",
")",
":",
"]",
".",
"replace",
"(",
... | https://github.com/LandGrey/ClassHound/blob/ccf09aea102ca6633027f18dbb8c9f217f4b3190/classhound.py#L111-L118 | |
vpelletier/python-libusb1 | 86ad8ab73f7442874de71c1f9f824724d21da92b | usb1/__init__.py | python | USBDeviceHandle.setAutoDetachKernelDriver | (self, enable) | Control automatic kernel driver detach.
enable (bool)
True to enable auto-detach, False to disable it. | Control automatic kernel driver detach.
enable (bool)
True to enable auto-detach, False to disable it. | [
"Control",
"automatic",
"kernel",
"driver",
"detach",
".",
"enable",
"(",
"bool",
")",
"True",
"to",
"enable",
"auto",
"-",
"detach",
"False",
"to",
"disable",
"it",
"."
] | def setAutoDetachKernelDriver(self, enable):
"""
Control automatic kernel driver detach.
enable (bool)
True to enable auto-detach, False to disable it.
"""
mayRaiseUSBError(libusb1.libusb_set_auto_detach_kernel_driver(
self.__handle, bool(enable),
)) | [
"def",
"setAutoDetachKernelDriver",
"(",
"self",
",",
"enable",
")",
":",
"mayRaiseUSBError",
"(",
"libusb1",
".",
"libusb_set_auto_detach_kernel_driver",
"(",
"self",
".",
"__handle",
",",
"bool",
"(",
"enable",
")",
",",
")",
")"
] | https://github.com/vpelletier/python-libusb1/blob/86ad8ab73f7442874de71c1f9f824724d21da92b/usb1/__init__.py#L1211-L1219 | ||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | ansible/roles/lib_repoquery/library/repoquery.py | python | Repoquery.__init__ | (self,
name,
query_type,
show_duplicates,
match_version,
verbose
) | Constructor for YumList | Constructor for YumList | [
"Constructor",
"for",
"YumList"
] | def __init__(self,
name,
query_type,
show_duplicates,
match_version,
verbose
):
''' Constructor for YumList '''
super(Repoquery, self).__init__(None)
self.name = name
self.query_type = query_type
self.show_duplicates = show_duplicates
self.match_version = match_version
self.verbose = verbose
if self.match_version:
self.show_duplicates = True
self.query_format = "%{version}|%{release}|%{arch}|%{repo}|%{version}-%{release}" | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"query_type",
",",
"show_duplicates",
",",
"match_version",
",",
"verbose",
")",
":",
"super",
"(",
"Repoquery",
",",
"self",
")",
".",
"__init__",
"(",
"None",
")",
"self",
".",
"name",
"=",
"name",
"s... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_repoquery/library/repoquery.py#L82-L100 | ||
knownsec/Pocsuite | 877d1b1604629b8dcd6e53b167c3c98249e5e94f | pocsuite/api/seebug.py | python | Seebug.poc_list | (self) | return self.poc_search() | Get available poc(s) related to the seebug api | Get available poc(s) related to the seebug api | [
"Get",
"available",
"poc",
"(",
"s",
")",
"related",
"to",
"the",
"seebug",
"api"
] | def poc_list(self):
"""Get available poc(s) related to the seebug api
"""
return self.poc_search() | [
"def",
"poc_list",
"(",
"self",
")",
":",
"return",
"self",
".",
"poc_search",
"(",
")"
] | https://github.com/knownsec/Pocsuite/blob/877d1b1604629b8dcd6e53b167c3c98249e5e94f/pocsuite/api/seebug.py#L38-L41 | |
plotly/plotly.py | cfad7862594b35965c0e000813bd7805e8494a5b | packages/python/plotly/plotly/graph_objs/surface/_colorbar.py | python | ColorBar.titleside | (self) | return self["titleside"] | Deprecated: Please use surface.colorbar.title.side instead.
Determines the location of color bar's title with respect to
the color bar. Defaults to "top" when `orientation` if "v" and
defaults to "right" when `orientation` if "h". Note that the
title's location used to be set by the now deprecated
`titleside` attribute.
The 'side' property is an enumeration that may be specified as:
- One of the following enumeration values:
['right', 'top', 'bottom']
Returns
------- | Deprecated: Please use surface.colorbar.title.side instead.
Determines the location of color bar's title with respect to
the color bar. Defaults to "top" when `orientation` if "v" and
defaults to "right" when `orientation` if "h". Note that the
title's location used to be set by the now deprecated
`titleside` attribute.
The 'side' property is an enumeration that may be specified as:
- One of the following enumeration values:
['right', 'top', 'bottom'] | [
"Deprecated",
":",
"Please",
"use",
"surface",
".",
"colorbar",
".",
"title",
".",
"side",
"instead",
".",
"Determines",
"the",
"location",
"of",
"color",
"bar",
"s",
"title",
"with",
"respect",
"to",
"the",
"color",
"bar",
".",
"Defaults",
"to",
"top",
... | def titleside(self):
"""
Deprecated: Please use surface.colorbar.title.side instead.
Determines the location of color bar's title with respect to
the color bar. Defaults to "top" when `orientation` if "v" and
defaults to "right" when `orientation` if "h". Note that the
title's location used to be set by the now deprecated
`titleside` attribute.
The 'side' property is an enumeration that may be specified as:
- One of the following enumeration values:
['right', 'top', 'bottom']
Returns
-------
"""
return self["titleside"] | [
"def",
"titleside",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"titleside\"",
"]"
] | https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/surface/_colorbar.py#L1232-L1249 | |
linxid/Machine_Learning_Study_Path | 558e82d13237114bbb8152483977806fc0c222af | Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/encodings/cp273.py | python | IncrementalEncoder.encode | (self, input, final=False) | return codecs.charmap_encode(input,self.errors,encoding_table)[0] | [] | def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_table)[0] | [
"def",
"encode",
"(",
"self",
",",
"input",
",",
"final",
"=",
"False",
")",
":",
"return",
"codecs",
".",
"charmap_encode",
"(",
"input",
",",
"self",
".",
"errors",
",",
"encoding_table",
")",
"[",
"0",
"]"
] | https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/encodings/cp273.py#L18-L19 | |||
openstack/barbican | a9d2b133c8dc3307974f119f9a2b23a4ba82e8ce | barbican/model/models.py | python | ProjectSecretStore.__init__ | (self, project_id=None, secret_store_id=None, check_exc=True) | Creates project secret store mapping entity. | Creates project secret store mapping entity. | [
"Creates",
"project",
"secret",
"store",
"mapping",
"entity",
"."
] | def __init__(self, project_id=None, secret_store_id=None, check_exc=True):
"""Creates project secret store mapping entity."""
super(ProjectSecretStore, self).__init__()
msg = u._("Must supply non-None {0} argument for ProjectSecretStore "
" entry.")
if not project_id and check_exc:
raise exception.MissingArgumentError(msg.format("project_id"))
self.project_id = project_id
if not secret_store_id and check_exc:
raise exception.MissingArgumentError(msg.format("secret_store_id"))
self.secret_store_id = secret_store_id
self.status = States.ACTIVE | [
"def",
"__init__",
"(",
"self",
",",
"project_id",
"=",
"None",
",",
"secret_store_id",
"=",
"None",
",",
"check_exc",
"=",
"True",
")",
":",
"super",
"(",
"ProjectSecretStore",
",",
"self",
")",
".",
"__init__",
"(",
")",
"msg",
"=",
"u",
".",
"_",
... | https://github.com/openstack/barbican/blob/a9d2b133c8dc3307974f119f9a2b23a4ba82e8ce/barbican/model/models.py#L1489-L1503 | ||
huawei-noah/Pretrained-Language-Model | d4694a134bdfacbaef8ff1d99735106bd3b3372b | NEZHA-TensorFlow/utils/create_glue_data.py | python | ColaProcessor.get_labels | (self) | return ["0", "1"] | See base class. | See base class. | [
"See",
"base",
"class",
"."
] | def get_labels(self):
"""See base class."""
return ["0", "1"] | [
"def",
"get_labels",
"(",
"self",
")",
":",
"return",
"[",
"\"0\"",
",",
"\"1\"",
"]"
] | https://github.com/huawei-noah/Pretrained-Language-Model/blob/d4694a134bdfacbaef8ff1d99735106bd3b3372b/NEZHA-TensorFlow/utils/create_glue_data.py#L293-L295 | |
rogerbinns/apsw | 00a7eb5138f2f00976f0c76cb51906afecbe298f | tools/shell.py | python | Shell._set_db | (self, newv) | Sets the open database (or None) and filename | Sets the open database (or None) and filename | [
"Sets",
"the",
"open",
"database",
"(",
"or",
"None",
")",
"and",
"filename"
] | def _set_db(self, newv):
"Sets the open database (or None) and filename"
(db, dbfilename) = newv
if self._db:
self._db.close(True)
self._db = None
self._db = db
self.dbfilename = dbfilename | [
"def",
"_set_db",
"(",
"self",
",",
"newv",
")",
":",
"(",
"db",
",",
"dbfilename",
")",
"=",
"newv",
"if",
"self",
".",
"_db",
":",
"self",
".",
"_db",
".",
"close",
"(",
"True",
")",
"self",
".",
"_db",
"=",
"None",
"self",
".",
"_db",
"=",
... | https://github.com/rogerbinns/apsw/blob/00a7eb5138f2f00976f0c76cb51906afecbe298f/tools/shell.py#L153-L160 | ||
pyvista/pyvista | 012dbb95a9aae406c3cd4cd94fc8c477f871e426 | pyvista/core/pointset.py | python | PolyData.n_faces | (self) | return self.n_cells | Return the number of cells.
Alias for ``n_cells``.
Examples
--------
>>> import pyvista
>>> plane = pyvista.Plane(i_resolution=2, j_resolution=2)
>>> plane.n_faces
4 | Return the number of cells. | [
"Return",
"the",
"number",
"of",
"cells",
"."
] | def n_faces(self) -> int:
"""Return the number of cells.
Alias for ``n_cells``.
Examples
--------
>>> import pyvista
>>> plane = pyvista.Plane(i_resolution=2, j_resolution=2)
>>> plane.n_faces
4
"""
return self.n_cells | [
"def",
"n_faces",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"n_cells"
] | https://github.com/pyvista/pyvista/blob/012dbb95a9aae406c3cd4cd94fc8c477f871e426/pyvista/core/pointset.py#L786-L799 | |
broadinstitute/gtex-pipeline | 3481dd43b2e8a33cc217155483ce25d5255aafa9 | rnaseq/src/mpileup.py | python | remove_indels | (read_bases) | return b.decode() | Remove indels from pileup output | Remove indels from pileup output | [
"Remove",
"indels",
"from",
"pileup",
"output"
] | def remove_indels(read_bases):
"""Remove indels from pileup output"""
# read_bases = ',,,-19tcttagtaagattacacat,,,+2at...'
indel = re.compile('[-+]\d+')
b = bytearray(read_bases.encode())
ix = []
# ins = []
# dels = []
for m in indel.finditer(read_bases):
s = m.group()
n = int(s[1:])
# if s[0]=='+':
# ins.append([m.end(), m.end()+n])
# else:
# dels.append([m.end(), m.end()+n])
ix.append([m.start(), m.end()+n])
# ins = [read_bases[i[0]:i[1]] for i in ins]
# dels = [read_bases[i[0]:i[1]] for i in dels]
# ins = '|'.join(['{}:{}'.format(j,i) for i,j in pd.Series(ins).value_counts().items()])
# dels = '|'.join(['{}:{}'.format(j,i) for i,j in pd.Series(dels).value_counts().items()])
# if ins=='':
# ins = 'NA'
# if dels=='':
# dels = 'NA'
for i in ix[::-1]:
b[i[0]:i[1]] = b''
return b.decode() | [
"def",
"remove_indels",
"(",
"read_bases",
")",
":",
"# read_bases = ',,,-19tcttagtaagattacacat,,,+2at...'",
"indel",
"=",
"re",
".",
"compile",
"(",
"'[-+]\\d+'",
")",
"b",
"=",
"bytearray",
"(",
"read_bases",
".",
"encode",
"(",
")",
")",
"ix",
"=",
"[",
"]"... | https://github.com/broadinstitute/gtex-pipeline/blob/3481dd43b2e8a33cc217155483ce25d5255aafa9/rnaseq/src/mpileup.py#L9-L41 | |
saltstack/raet | 54858029568115550c7cb7d93e999d9c52b1494a | raet/road/stacking.py | python | RoadStack.fetchRemoteByKeys | (self, sighex, prihex) | return None | Search for remote with matching (name, sighex, prihex)
Return remote if found Otherwise return None | Search for remote with matching (name, sighex, prihex)
Return remote if found Otherwise return None | [
"Search",
"for",
"remote",
"with",
"matching",
"(",
"name",
"sighex",
"prihex",
")",
"Return",
"remote",
"if",
"found",
"Otherwise",
"return",
"None"
] | def fetchRemoteByKeys(self, sighex, prihex):
'''
Search for remote with matching (name, sighex, prihex)
Return remote if found Otherwise return None
'''
for remote in self.remotes.values():
if (remote.signer.keyhex == sighex or
remote.priver.keyhex == prihex):
return remote
return None | [
"def",
"fetchRemoteByKeys",
"(",
"self",
",",
"sighex",
",",
"prihex",
")",
":",
"for",
"remote",
"in",
"self",
".",
"remotes",
".",
"values",
"(",
")",
":",
"if",
"(",
"remote",
".",
"signer",
".",
"keyhex",
"==",
"sighex",
"or",
"remote",
".",
"pri... | https://github.com/saltstack/raet/blob/54858029568115550c7cb7d93e999d9c52b1494a/raet/road/stacking.py#L213-L223 | |
quic/aimet | dae9bae9a77ca719aa7553fefde4768270fc3518 | TrainingExtensions/torch/src/python/aimet_torch/qc_quantize_op.py | python | tensor_quantizer_factory | (bitwidth: int, round_mode: str, quant_scheme: QuantScheme,
use_symmetric_encodings: bool, enabled_by_default: bool,
data_type: QuantizationDataType = QuantizationDataType.int) | return tensor_quantizer | Instantiates TensorQuantizer depending on the quant_scheme
:param bitwidth: Quantization bitwidth
:param round_mode: Rounding mode (e.g. Nearest)
:param quant_scheme: Quantization scheme (e.g. Range Learning)
:param use_symmetric_encodings: True if symmetric encoding is used. False otherwise.
:param enabled_by_default: True if quantization of tensor is enabled. False otherwise.
:return: An instance of StaticGridPerTensorQuantizer | Instantiates TensorQuantizer depending on the quant_scheme
:param bitwidth: Quantization bitwidth
:param round_mode: Rounding mode (e.g. Nearest)
:param quant_scheme: Quantization scheme (e.g. Range Learning)
:param use_symmetric_encodings: True if symmetric encoding is used. False otherwise.
:param enabled_by_default: True if quantization of tensor is enabled. False otherwise.
:return: An instance of StaticGridPerTensorQuantizer | [
"Instantiates",
"TensorQuantizer",
"depending",
"on",
"the",
"quant_scheme",
":",
"param",
"bitwidth",
":",
"Quantization",
"bitwidth",
":",
"param",
"round_mode",
":",
"Rounding",
"mode",
"(",
"e",
".",
"g",
".",
"Nearest",
")",
":",
"param",
"quant_scheme",
... | def tensor_quantizer_factory(bitwidth: int, round_mode: str, quant_scheme: QuantScheme,
use_symmetric_encodings: bool, enabled_by_default: bool,
data_type: QuantizationDataType = QuantizationDataType.int):
"""
Instantiates TensorQuantizer depending on the quant_scheme
:param bitwidth: Quantization bitwidth
:param round_mode: Rounding mode (e.g. Nearest)
:param quant_scheme: Quantization scheme (e.g. Range Learning)
:param use_symmetric_encodings: True if symmetric encoding is used. False otherwise.
:param enabled_by_default: True if quantization of tensor is enabled. False otherwise.
:return: An instance of StaticGridPerTensorQuantizer
"""
if quant_scheme == QuantScheme.post_training_tf_enhanced or quant_scheme == QuantScheme.post_training_tf:
tensor_quantizer = StaticGridPerTensorQuantizer(bitwidth, round_mode, quant_scheme,
use_symmetric_encodings, enabled_by_default,
data_type=data_type)
elif quant_scheme == QuantScheme.training_range_learning_with_tf_init or \
quant_scheme == QuantScheme.training_range_learning_with_tf_enhanced_init:
tensor_quantizer = LearnedGridTensorQuantizer(bitwidth, round_mode, quant_scheme, use_symmetric_encodings,
enabled_by_default, data_type)
else:
raise AssertionError("Unsupported quant_scheme: " + str(quant_scheme))
return tensor_quantizer | [
"def",
"tensor_quantizer_factory",
"(",
"bitwidth",
":",
"int",
",",
"round_mode",
":",
"str",
",",
"quant_scheme",
":",
"QuantScheme",
",",
"use_symmetric_encodings",
":",
"bool",
",",
"enabled_by_default",
":",
"bool",
",",
"data_type",
":",
"QuantizationDataType"... | https://github.com/quic/aimet/blob/dae9bae9a77ca719aa7553fefde4768270fc3518/TrainingExtensions/torch/src/python/aimet_torch/qc_quantize_op.py#L66-L93 | |
redis/redis-py | 0affa0ed3f3cbcb6dec29b34a580f769f69ae9f7 | redis/commands/search/commands.py | python | SearchCommands.dict_del | (self, name, *terms) | return self.execute_command(*cmd) | Deletes terms from a dictionary.
### Parameters
- **name**: Dictionary name.
- **terms**: List of items for removing from the dictionary.
For more information: https://oss.redis.com/redisearch/Commands/#ftdictdel | Deletes terms from a dictionary. | [
"Deletes",
"terms",
"from",
"a",
"dictionary",
"."
] | def dict_del(self, name, *terms):
"""Deletes terms from a dictionary.
### Parameters
- **name**: Dictionary name.
- **terms**: List of items for removing from the dictionary.
For more information: https://oss.redis.com/redisearch/Commands/#ftdictdel
""" # noqa
cmd = [DICT_DEL_CMD, name]
cmd.extend(terms)
return self.execute_command(*cmd) | [
"def",
"dict_del",
"(",
"self",
",",
"name",
",",
"*",
"terms",
")",
":",
"# noqa",
"cmd",
"=",
"[",
"DICT_DEL_CMD",
",",
"name",
"]",
"cmd",
".",
"extend",
"(",
"terms",
")",
"return",
"self",
".",
"execute_command",
"(",
"*",
"cmd",
")"
] | https://github.com/redis/redis-py/blob/0affa0ed3f3cbcb6dec29b34a580f769f69ae9f7/redis/commands/search/commands.py#L590-L602 | |
pyparallel/pyparallel | 11e8c6072d48c8f13641925d17b147bf36ee0ba3 | Lib/distutils/msvccompiler.py | python | get_build_version | () | return None | Return the version of MSVC that was used to build Python.
For Python 2.3 and up, the version number is included in
sys.version. For earlier versions, assume the compiler is MSVC 6. | Return the version of MSVC that was used to build Python. | [
"Return",
"the",
"version",
"of",
"MSVC",
"that",
"was",
"used",
"to",
"build",
"Python",
"."
] | def get_build_version():
"""Return the version of MSVC that was used to build Python.
For Python 2.3 and up, the version number is included in
sys.version. For earlier versions, assume the compiler is MSVC 6.
"""
prefix = "MSC v."
i = sys.version.find(prefix)
if i == -1:
return 6
i = i + len(prefix)
s, rest = sys.version[i:].split(" ", 1)
majorVersion = int(s[:-2]) - 6
minorVersion = int(s[2:3]) / 10.0
# I don't think paths are affected by minor version in version 6
if majorVersion == 6:
minorVersion = 0
if majorVersion >= 6:
return majorVersion + minorVersion
# else we don't know what version of the compiler this is
return None | [
"def",
"get_build_version",
"(",
")",
":",
"prefix",
"=",
"\"MSC v.\"",
"i",
"=",
"sys",
".",
"version",
".",
"find",
"(",
"prefix",
")",
"if",
"i",
"==",
"-",
"1",
":",
"return",
"6",
"i",
"=",
"i",
"+",
"len",
"(",
"prefix",
")",
"s",
",",
"r... | https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/distutils/msvccompiler.py#L147-L167 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.