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
sequence | function
stringlengths 18
4.83M
| function_tokens
sequence | url
stringlengths 83
304
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
TheAlgorithms/Python | 9af2eef9b3761bf51580dedfb6fa7136ca0c5c2c | linear_algebra/src/rayleigh_quotient.py | python | rayleigh_quotient | (A: np.ndarray, v: np.ndarray) | return (v_star_dot.dot(v)) / (v_star.dot(v)) | Returns the Rayleigh quotient of a Hermitian matrix A and
vector v.
>>> import numpy as np
>>> A = np.array([
... [1, 2, 4],
... [2, 3, -1],
... [4, -1, 1]
... ])
>>> v = np.array([
... [1],
... [2],
... [3]
... ])
>>> rayleigh_quotient(A, v)
array([[3.]]) | Returns the Rayleigh quotient of a Hermitian matrix A and
vector v.
>>> import numpy as np
>>> A = np.array([
... [1, 2, 4],
... [2, 3, -1],
... [4, -1, 1]
... ])
>>> v = np.array([
... [1],
... [2],
... [3]
... ])
>>> rayleigh_quotient(A, v)
array([[3.]]) | [
"Returns",
"the",
"Rayleigh",
"quotient",
"of",
"a",
"Hermitian",
"matrix",
"A",
"and",
"vector",
"v",
".",
">>>",
"import",
"numpy",
"as",
"np",
">>>",
"A",
"=",
"np",
".",
"array",
"(",
"[",
"...",
"[",
"1",
"2",
"4",
"]",
"...",
"[",
"2",
"3",
"-",
"1",
"]",
"...",
"[",
"4",
"-",
"1",
"1",
"]",
"...",
"]",
")",
">>>",
"v",
"=",
"np",
".",
"array",
"(",
"[",
"...",
"[",
"1",
"]",
"...",
"[",
"2",
"]",
"...",
"[",
"3",
"]",
"...",
"]",
")",
">>>",
"rayleigh_quotient",
"(",
"A",
"v",
")",
"array",
"(",
"[[",
"3",
".",
"]]",
")"
] | def rayleigh_quotient(A: np.ndarray, v: np.ndarray) -> Any:
"""
Returns the Rayleigh quotient of a Hermitian matrix A and
vector v.
>>> import numpy as np
>>> A = np.array([
... [1, 2, 4],
... [2, 3, -1],
... [4, -1, 1]
... ])
>>> v = np.array([
... [1],
... [2],
... [3]
... ])
>>> rayleigh_quotient(A, v)
array([[3.]])
"""
v_star = v.conjugate().T
v_star_dot = v_star.dot(A)
assert isinstance(v_star_dot, np.ndarray)
return (v_star_dot.dot(v)) / (v_star.dot(v)) | [
"def",
"rayleigh_quotient",
"(",
"A",
":",
"np",
".",
"ndarray",
",",
"v",
":",
"np",
".",
"ndarray",
")",
"->",
"Any",
":",
"v_star",
"=",
"v",
".",
"conjugate",
"(",
")",
".",
"T",
"v_star_dot",
"=",
"v_star",
".",
"dot",
"(",
"A",
")",
"assert",
"isinstance",
"(",
"v_star_dot",
",",
"np",
".",
"ndarray",
")",
"return",
"(",
"v_star_dot",
".",
"dot",
"(",
"v",
")",
")",
"/",
"(",
"v_star",
".",
"dot",
"(",
"v",
")",
")"
] | https://github.com/TheAlgorithms/Python/blob/9af2eef9b3761bf51580dedfb6fa7136ca0c5c2c/linear_algebra/src/rayleigh_quotient.py#L29-L50 |
|
sithis993/Crypter | 4b3148912dbe8f68c952b39f0c51c69513fe4af4 | CrypterBuilder/Gui.py | python | Gui.__save_config | (self, event) | @summary: Saves the configuration/user input data to the configuration file | [] | def __save_config(self, event):
'''
@summary: Saves the configuration/user input data to the configuration file
'''
# If not saved, used currently loaded config file path
if self.SaveFilePicker.GetPath():
self.config_file_path = self.SaveFilePicker.GetPath()
# Get data from form
user_input_dict = self.__get_input_data()
# Parse filetypes to encrypt
# Remove any trailing and leading spaces, dots
user_input_dict["filetypes_to_encrypt"] = user_input_dict["filetypes_to_encrypt"].split(",")
for index in range(len(user_input_dict["filetypes_to_encrypt"])):
user_input_dict["filetypes_to_encrypt"][index] = user_input_dict["filetypes_to_encrypt"][index].strip().strip(".")
# Parse encrypted file extension
user_input_dict["encrypted_file_extension"] = user_input_dict["encrypted_file_extension"].strip(".")
# Try to write the config to file
try:
with open(self.config_file_path, "w") as config_file_handle:
json.dump(user_input_dict, config_file_handle, indent=6)
self.console.log(msg="Build configuration successfully saved to file %s"
% self.config_file_path)
self.StatusBar.SetStatusText("Config Saved To %s" % self.config_file_path)
self.__build_config_file = self.config_file_path
self.__update_loaded_config_file()
except Exception as ex:
self.console.log(msg="The configuration could not be saved to %s: %s"
% (self.config_file_path, ex),
ccode=ERROR_CANNOT_WRITE
)
self.StatusBar.SetStatusText("Error saving configuration file %s" % self.config_file_path)
self.config_file_path = None | [
"def",
"__save_config",
"(",
"self",
",",
"event",
")",
":",
"# If not saved, used currently loaded config file path",
"if",
"self",
".",
"SaveFilePicker",
".",
"GetPath",
"(",
")",
":",
"self",
".",
"config_file_path",
"=",
"self",
".",
"SaveFilePicker",
".",
"GetPath",
"(",
")",
"# Get data from form",
"user_input_dict",
"=",
"self",
".",
"__get_input_data",
"(",
")",
"# Parse filetypes to encrypt",
"# Remove any trailing and leading spaces, dots",
"user_input_dict",
"[",
"\"filetypes_to_encrypt\"",
"]",
"=",
"user_input_dict",
"[",
"\"filetypes_to_encrypt\"",
"]",
".",
"split",
"(",
"\",\"",
")",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"user_input_dict",
"[",
"\"filetypes_to_encrypt\"",
"]",
")",
")",
":",
"user_input_dict",
"[",
"\"filetypes_to_encrypt\"",
"]",
"[",
"index",
"]",
"=",
"user_input_dict",
"[",
"\"filetypes_to_encrypt\"",
"]",
"[",
"index",
"]",
".",
"strip",
"(",
")",
".",
"strip",
"(",
"\".\"",
")",
"# Parse encrypted file extension",
"user_input_dict",
"[",
"\"encrypted_file_extension\"",
"]",
"=",
"user_input_dict",
"[",
"\"encrypted_file_extension\"",
"]",
".",
"strip",
"(",
"\".\"",
")",
"# Try to write the config to file",
"try",
":",
"with",
"open",
"(",
"self",
".",
"config_file_path",
",",
"\"w\"",
")",
"as",
"config_file_handle",
":",
"json",
".",
"dump",
"(",
"user_input_dict",
",",
"config_file_handle",
",",
"indent",
"=",
"6",
")",
"self",
".",
"console",
".",
"log",
"(",
"msg",
"=",
"\"Build configuration successfully saved to file %s\"",
"%",
"self",
".",
"config_file_path",
")",
"self",
".",
"StatusBar",
".",
"SetStatusText",
"(",
"\"Config Saved To %s\"",
"%",
"self",
".",
"config_file_path",
")",
"self",
".",
"__build_config_file",
"=",
"self",
".",
"config_file_path",
"self",
".",
"__update_loaded_config_file",
"(",
")",
"except",
"Exception",
"as",
"ex",
":",
"self",
".",
"console",
".",
"log",
"(",
"msg",
"=",
"\"The configuration could not be saved to %s: %s\"",
"%",
"(",
"self",
".",
"config_file_path",
",",
"ex",
")",
",",
"ccode",
"=",
"ERROR_CANNOT_WRITE",
")",
"self",
".",
"StatusBar",
".",
"SetStatusText",
"(",
"\"Error saving configuration file %s\"",
"%",
"self",
".",
"config_file_path",
")",
"self",
".",
"config_file_path",
"=",
"None"
] | https://github.com/sithis993/Crypter/blob/4b3148912dbe8f68c952b39f0c51c69513fe4af4/CrypterBuilder/Gui.py#L230-L265 |
|||
CoinAlpha/hummingbot | 36f6149c1644c07cd36795b915f38b8f49b798e7 | hummingbot/connector/exchange/gate_io/gate_io_exchange.py | python | GateIoExchange.cancel | (self, trading_pair: str, order_id: str) | return order_id | Cancel an order. This function returns immediately.
To get the cancellation result, you'll have to wait for OrderCancelledEvent.
:param trading_pair: The market (e.g. BTC-USDT) of the order.
:param order_id: The internal order id (also called client_order_id) | Cancel an order. This function returns immediately.
To get the cancellation result, you'll have to wait for OrderCancelledEvent.
:param trading_pair: The market (e.g. BTC-USDT) of the order.
:param order_id: The internal order id (also called client_order_id) | [
"Cancel",
"an",
"order",
".",
"This",
"function",
"returns",
"immediately",
".",
"To",
"get",
"the",
"cancellation",
"result",
"you",
"ll",
"have",
"to",
"wait",
"for",
"OrderCancelledEvent",
".",
":",
"param",
"trading_pair",
":",
"The",
"market",
"(",
"e",
".",
"g",
".",
"BTC",
"-",
"USDT",
")",
"of",
"the",
"order",
".",
":",
"param",
"order_id",
":",
"The",
"internal",
"order",
"id",
"(",
"also",
"called",
"client_order_id",
")"
] | def cancel(self, trading_pair: str, order_id: str):
"""
Cancel an order. This function returns immediately.
To get the cancellation result, you'll have to wait for OrderCancelledEvent.
:param trading_pair: The market (e.g. BTC-USDT) of the order.
:param order_id: The internal order id (also called client_order_id)
"""
safe_ensure_future(self._execute_cancel(trading_pair, order_id))
return order_id | [
"def",
"cancel",
"(",
"self",
",",
"trading_pair",
":",
"str",
",",
"order_id",
":",
"str",
")",
":",
"safe_ensure_future",
"(",
"self",
".",
"_execute_cancel",
"(",
"trading_pair",
",",
"order_id",
")",
")",
"return",
"order_id"
] | https://github.com/CoinAlpha/hummingbot/blob/36f6149c1644c07cd36795b915f38b8f49b798e7/hummingbot/connector/exchange/gate_io/gate_io_exchange.py#L387-L395 |
|
kovidgoyal/calibre | 2b41671370f2a9eb1109b9ae901ccf915f1bd0c8 | src/calibre/gui2/dialogs/quickview.py | python | Quickview.add_columns_to_widget | (self) | Get the list of columns from the preferences. Clear the current table
and add the current column set | Get the list of columns from the preferences. Clear the current table
and add the current column set | [
"Get",
"the",
"list",
"of",
"columns",
"from",
"the",
"preferences",
".",
"Clear",
"the",
"current",
"table",
"and",
"add",
"the",
"current",
"column",
"set"
] | def add_columns_to_widget(self):
'''
Get the list of columns from the preferences. Clear the current table
and add the current column set
'''
self.column_order = [x[0] for x in get_qv_field_list(self.fm) if x[1]]
self.books_table.clear()
self.books_table.setRowCount(0)
self.books_table.setColumnCount(len(self.column_order))
for idx,col in enumerate(self.column_order):
t = QTableWidgetItem(self.fm[col]['name'])
self.books_table.setHorizontalHeaderItem(idx, t) | [
"def",
"add_columns_to_widget",
"(",
"self",
")",
":",
"self",
".",
"column_order",
"=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"get_qv_field_list",
"(",
"self",
".",
"fm",
")",
"if",
"x",
"[",
"1",
"]",
"]",
"self",
".",
"books_table",
".",
"clear",
"(",
")",
"self",
".",
"books_table",
".",
"setRowCount",
"(",
"0",
")",
"self",
".",
"books_table",
".",
"setColumnCount",
"(",
"len",
"(",
"self",
".",
"column_order",
")",
")",
"for",
"idx",
",",
"col",
"in",
"enumerate",
"(",
"self",
".",
"column_order",
")",
":",
"t",
"=",
"QTableWidgetItem",
"(",
"self",
".",
"fm",
"[",
"col",
"]",
"[",
"'name'",
"]",
")",
"self",
".",
"books_table",
".",
"setHorizontalHeaderItem",
"(",
"idx",
",",
"t",
")"
] | https://github.com/kovidgoyal/calibre/blob/2b41671370f2a9eb1109b9ae901ccf915f1bd0c8/src/calibre/gui2/dialogs/quickview.py#L363-L374 |
||
wechatpy/wechatpy | 5f693a7e90156786c2540ad3c941d12cdf6d88ef | wechatpy/client/api/scan.py | python | WeChatScan.set_test_whitelist | (self, userids=None, usernames=None) | return self._post("testwhitelist/set", data=data) | 设置测试人员白名单
注意:每次设置均被视为一次重置,而非增量设置。openid、微信号合计最多设置10个。
详情请参考
http://mp.weixin.qq.com/wiki/15/1007691d0f1c10a0588c6517f12ed70f.html
:param userids: 可选,测试人员的 openid 列表
:param usernames: 可选,测试人员的微信号列表
:return: 返回的 JSON 数据包 | 设置测试人员白名单 | [
"设置测试人员白名单"
] | def set_test_whitelist(self, userids=None, usernames=None):
"""
设置测试人员白名单
注意:每次设置均被视为一次重置,而非增量设置。openid、微信号合计最多设置10个。
详情请参考
http://mp.weixin.qq.com/wiki/15/1007691d0f1c10a0588c6517f12ed70f.html
:param userids: 可选,测试人员的 openid 列表
:param usernames: 可选,测试人员的微信号列表
:return: 返回的 JSON 数据包
"""
data = optionaldict(openid=userids, username=usernames)
return self._post("testwhitelist/set", data=data) | [
"def",
"set_test_whitelist",
"(",
"self",
",",
"userids",
"=",
"None",
",",
"usernames",
"=",
"None",
")",
":",
"data",
"=",
"optionaldict",
"(",
"openid",
"=",
"userids",
",",
"username",
"=",
"usernames",
")",
"return",
"self",
".",
"_post",
"(",
"\"testwhitelist/set\"",
",",
"data",
"=",
"data",
")"
] | https://github.com/wechatpy/wechatpy/blob/5f693a7e90156786c2540ad3c941d12cdf6d88ef/wechatpy/client/api/scan.py#L75-L89 |
|
beeware/ouroboros | a29123c6fab6a807caffbb7587cf548e0c370296 | ouroboros/_pyio.py | python | RawIOBase.readall | (self) | Read until EOF, using multiple read() call. | Read until EOF, using multiple read() call. | [
"Read",
"until",
"EOF",
"using",
"multiple",
"read",
"()",
"call",
"."
] | def readall(self):
"""Read until EOF, using multiple read() call."""
res = bytearray()
while True:
data = self.read(DEFAULT_BUFFER_SIZE)
if not data:
break
res += data
if res:
return bytes(res)
else:
# b'' or None
return data | [
"def",
"readall",
"(",
"self",
")",
":",
"res",
"=",
"bytearray",
"(",
")",
"while",
"True",
":",
"data",
"=",
"self",
".",
"read",
"(",
"DEFAULT_BUFFER_SIZE",
")",
"if",
"not",
"data",
":",
"break",
"res",
"+=",
"data",
"if",
"res",
":",
"return",
"bytes",
"(",
"res",
")",
"else",
":",
"# b'' or None",
"return",
"data"
] | https://github.com/beeware/ouroboros/blob/a29123c6fab6a807caffbb7587cf548e0c370296/ouroboros/_pyio.py#L577-L589 |
||
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/core.py | python | split_entity_id | (entity_id: str) | return entity_id.split(".", 1) | Split a state entity ID into domain and object ID. | Split a state entity ID into domain and object ID. | [
"Split",
"a",
"state",
"entity",
"ID",
"into",
"domain",
"and",
"object",
"ID",
"."
] | def split_entity_id(entity_id: str) -> list[str]:
"""Split a state entity ID into domain and object ID."""
return entity_id.split(".", 1) | [
"def",
"split_entity_id",
"(",
"entity_id",
":",
"str",
")",
"->",
"list",
"[",
"str",
"]",
":",
"return",
"entity_id",
".",
"split",
"(",
"\".\"",
",",
"1",
")"
] | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/core.py#L145-L147 |
|
jasbur/RaspiWiFi | 9c936eef427b4964b7405b9a098f971cebbb892e | libs/configuration_app/app.py | python | manual_ssid_entry | () | return render_template('manual_ssid_entry.html') | [] | def manual_ssid_entry():
return render_template('manual_ssid_entry.html') | [
"def",
"manual_ssid_entry",
"(",
")",
":",
"return",
"render_template",
"(",
"'manual_ssid_entry.html'",
")"
] | https://github.com/jasbur/RaspiWiFi/blob/9c936eef427b4964b7405b9a098f971cebbb892e/libs/configuration_app/app.py#L21-L22 |
|||
spotify/luigi | c3b66f4a5fa7eaa52f9a72eb6704b1049035c789 | luigi/notifications.py | python | wrap_traceback | (traceback) | return wrapped | For internal use only (until further notice) | For internal use only (until further notice) | [
"For",
"internal",
"use",
"only",
"(",
"until",
"further",
"notice",
")"
] | def wrap_traceback(traceback):
"""
For internal use only (until further notice)
"""
if email().format == 'html':
try:
from pygments import highlight
from pygments.lexers import PythonTracebackLexer
from pygments.formatters import HtmlFormatter
with_pygments = True
except ImportError:
with_pygments = False
if with_pygments:
formatter = HtmlFormatter(noclasses=True)
wrapped = highlight(traceback, PythonTracebackLexer(), formatter)
else:
wrapped = '<pre>%s</pre>' % traceback
else:
wrapped = traceback
return wrapped | [
"def",
"wrap_traceback",
"(",
"traceback",
")",
":",
"if",
"email",
"(",
")",
".",
"format",
"==",
"'html'",
":",
"try",
":",
"from",
"pygments",
"import",
"highlight",
"from",
"pygments",
".",
"lexers",
"import",
"PythonTracebackLexer",
"from",
"pygments",
".",
"formatters",
"import",
"HtmlFormatter",
"with_pygments",
"=",
"True",
"except",
"ImportError",
":",
"with_pygments",
"=",
"False",
"if",
"with_pygments",
":",
"formatter",
"=",
"HtmlFormatter",
"(",
"noclasses",
"=",
"True",
")",
"wrapped",
"=",
"highlight",
"(",
"traceback",
",",
"PythonTracebackLexer",
"(",
")",
",",
"formatter",
")",
"else",
":",
"wrapped",
"=",
"'<pre>%s</pre>'",
"%",
"traceback",
"else",
":",
"wrapped",
"=",
"traceback",
"return",
"wrapped"
] | https://github.com/spotify/luigi/blob/c3b66f4a5fa7eaa52f9a72eb6704b1049035c789/luigi/notifications.py#L159-L180 |
|
DeepPavlov/convai | 54d921f99606960941ece4865a396925dfc264f4 | 2017/solutions/kaib/ParlAI/parlai/mturk/core/agents.py | python | MTurkAgent.change_conversation | (self, conversation_id, agent_id, change_callback) | Handle changing a conversation for an agent, takes a callback for
when the command is acknowledged | Handle changing a conversation for an agent, takes a callback for
when the command is acknowledged | [
"Handle",
"changing",
"a",
"conversation",
"for",
"an",
"agent",
"takes",
"a",
"callback",
"for",
"when",
"the",
"command",
"is",
"acknowledged"
] | def change_conversation(self, conversation_id, agent_id, change_callback):
"""Handle changing a conversation for an agent, takes a callback for
when the command is acknowledged
"""
self.id = agent_id
self.conversation_id = conversation_id
data = {
'text': data_model.COMMAND_CHANGE_CONVERSATION,
'conversation_id': conversation_id,
'agent_id': agent_id
}
self.manager.send_command(
self.worker_id,
self.assignment_id,
data,
ack_func=change_callback
) | [
"def",
"change_conversation",
"(",
"self",
",",
"conversation_id",
",",
"agent_id",
",",
"change_callback",
")",
":",
"self",
".",
"id",
"=",
"agent_id",
"self",
".",
"conversation_id",
"=",
"conversation_id",
"data",
"=",
"{",
"'text'",
":",
"data_model",
".",
"COMMAND_CHANGE_CONVERSATION",
",",
"'conversation_id'",
":",
"conversation_id",
",",
"'agent_id'",
":",
"agent_id",
"}",
"self",
".",
"manager",
".",
"send_command",
"(",
"self",
".",
"worker_id",
",",
"self",
".",
"assignment_id",
",",
"data",
",",
"ack_func",
"=",
"change_callback",
")"
] | https://github.com/DeepPavlov/convai/blob/54d921f99606960941ece4865a396925dfc264f4/2017/solutions/kaib/ParlAI/parlai/mturk/core/agents.py#L253-L269 |
||
1040003585/WebScrapingWithPython | a770fa5b03894076c8c9539b1ffff34424ffc016 | ResourceCode/wswp-places-c573d29efa3a/web2py/gluon/scheduler.py | python | MetaScheduler.pop_task | (self) | Fetches a task ready to be executed | Fetches a task ready to be executed | [
"Fetches",
"a",
"task",
"ready",
"to",
"be",
"executed"
] | def pop_task(self):
"""Fetches a task ready to be executed"""
raise NotImplementedError | [
"def",
"pop_task",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/1040003585/WebScrapingWithPython/blob/a770fa5b03894076c8c9539b1ffff34424ffc016/ResourceCode/wswp-places-c573d29efa3a/web2py/gluon/scheduler.py#L458-L460 |
||
calico/basenji | 2dae9b54744bd0495041c4259c22593054eef50b | basenji/layers.py | python | relative_shift | (x) | return x | Shift the relative logits like in TransformerXL. | Shift the relative logits like in TransformerXL. | [
"Shift",
"the",
"relative",
"logits",
"like",
"in",
"TransformerXL",
"."
] | def relative_shift(x):
"""Shift the relative logits like in TransformerXL."""
# We prepend zeros on the final timescale dimension.
to_pad = tf.zeros_like(x[..., :1])
x = tf.concat([to_pad, x], -1)
_, num_heads, t1, t2 = x.shape
x = tf.reshape(x, [-1, num_heads, t2, t1])
x = tf.slice(x, [0, 0, 1, 0], [-1, -1, -1, -1])
x = tf.reshape(x, [-1, num_heads, t1, t2 - 1])
x = tf.slice(x, [0, 0, 0, 0], [-1, -1, -1, (t2 + 1) // 2])
return x | [
"def",
"relative_shift",
"(",
"x",
")",
":",
"# We prepend zeros on the final timescale dimension.",
"to_pad",
"=",
"tf",
".",
"zeros_like",
"(",
"x",
"[",
"...",
",",
":",
"1",
"]",
")",
"x",
"=",
"tf",
".",
"concat",
"(",
"[",
"to_pad",
",",
"x",
"]",
",",
"-",
"1",
")",
"_",
",",
"num_heads",
",",
"t1",
",",
"t2",
"=",
"x",
".",
"shape",
"x",
"=",
"tf",
".",
"reshape",
"(",
"x",
",",
"[",
"-",
"1",
",",
"num_heads",
",",
"t2",
",",
"t1",
"]",
")",
"x",
"=",
"tf",
".",
"slice",
"(",
"x",
",",
"[",
"0",
",",
"0",
",",
"1",
",",
"0",
"]",
",",
"[",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
"]",
")",
"x",
"=",
"tf",
".",
"reshape",
"(",
"x",
",",
"[",
"-",
"1",
",",
"num_heads",
",",
"t1",
",",
"t2",
"-",
"1",
"]",
")",
"x",
"=",
"tf",
".",
"slice",
"(",
"x",
",",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
",",
"[",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
",",
"(",
"t2",
"+",
"1",
")",
"//",
"2",
"]",
")",
"return",
"x"
] | https://github.com/calico/basenji/blob/2dae9b54744bd0495041c4259c22593054eef50b/basenji/layers.py#L356-L366 |
|
dddomodossola/remi | 2c208054cc57ae610277084e41ed8e183b8fd727 | remi/gui.py | python | Tag.disable_refresh | (self) | Prevents the parent widgets to be notified about an update.
This is required to improve performances in case of widgets updated
multiple times in a procedure. | Prevents the parent widgets to be notified about an update.
This is required to improve performances in case of widgets updated
multiple times in a procedure. | [
"Prevents",
"the",
"parent",
"widgets",
"to",
"be",
"notified",
"about",
"an",
"update",
".",
"This",
"is",
"required",
"to",
"improve",
"performances",
"in",
"case",
"of",
"widgets",
"updated",
"multiple",
"times",
"in",
"a",
"procedure",
"."
] | def disable_refresh(self):
""" Prevents the parent widgets to be notified about an update.
This is required to improve performances in case of widgets updated
multiple times in a procedure.
"""
self.refresh_enabled = False | [
"def",
"disable_refresh",
"(",
"self",
")",
":",
"self",
".",
"refresh_enabled",
"=",
"False"
] | https://github.com/dddomodossola/remi/blob/2c208054cc57ae610277084e41ed8e183b8fd727/remi/gui.py#L409-L414 |
||
kanzure/nanoengineer | 874e4c9f8a9190f093625b267f9767e19f82e6c4 | cad/src/cnt/commands/InsertNanotube/InsertNanotube_PropertyManager.py | python | InsertNanotube_PropertyManager._setEndPoints | (self) | Set the two endpoints of the nanotube using the values from the
X, Y, Z coordinate spinboxes in the property manager.
@note: The group box containing the 2 sets of XYZ spin boxes are
currently hidden. | Set the two endpoints of the nanotube using the values from the
X, Y, Z coordinate spinboxes in the property manager. | [
"Set",
"the",
"two",
"endpoints",
"of",
"the",
"nanotube",
"using",
"the",
"values",
"from",
"the",
"X",
"Y",
"Z",
"coordinate",
"spinboxes",
"in",
"the",
"property",
"manager",
"."
] | def _setEndPoints(self):
"""
Set the two endpoints of the nanotube using the values from the
X, Y, Z coordinate spinboxes in the property manager.
@note: The group box containing the 2 sets of XYZ spin boxes are
currently hidden.
"""
# First endpoint (origin) of nanotube
x1 = self.x1SpinBox.value()
y1 = self.y1SpinBox.value()
z1 = self.z1SpinBox.value()
# Second endpoint (direction vector/axis) of nanotube.
x2 = self.x2SpinBox.value()
y2 = self.y2SpinBox.value()
z2 = self.z2SpinBox.value()
if not self.endPoint1:
self.endPoint1 = V(x1, y1, z1)
if not self.endPoint2:
self.endPoint2 = V(x2, y2, z2)
self.nanotube.setEndPoints(self.endPoint1, self.endPoint2) | [
"def",
"_setEndPoints",
"(",
"self",
")",
":",
"# First endpoint (origin) of nanotube",
"x1",
"=",
"self",
".",
"x1SpinBox",
".",
"value",
"(",
")",
"y1",
"=",
"self",
".",
"y1SpinBox",
".",
"value",
"(",
")",
"z1",
"=",
"self",
".",
"z1SpinBox",
".",
"value",
"(",
")",
"# Second endpoint (direction vector/axis) of nanotube.",
"x2",
"=",
"self",
".",
"x2SpinBox",
".",
"value",
"(",
")",
"y2",
"=",
"self",
".",
"y2SpinBox",
".",
"value",
"(",
")",
"z2",
"=",
"self",
".",
"z2SpinBox",
".",
"value",
"(",
")",
"if",
"not",
"self",
".",
"endPoint1",
":",
"self",
".",
"endPoint1",
"=",
"V",
"(",
"x1",
",",
"y1",
",",
"z1",
")",
"if",
"not",
"self",
".",
"endPoint2",
":",
"self",
".",
"endPoint2",
"=",
"V",
"(",
"x2",
",",
"y2",
",",
"z2",
")",
"self",
".",
"nanotube",
".",
"setEndPoints",
"(",
"self",
".",
"endPoint1",
",",
"self",
".",
"endPoint2",
")"
] | https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/cnt/commands/InsertNanotube/InsertNanotube_PropertyManager.py#L432-L455 |
||
djsutherland/opt-mmd | 5c02a92972df099628a4bc8351980ad9f317b6d0 | gan/model_tmmd.py | python | DCGAN.train | (self, config) | Train DCGAN | Train DCGAN | [
"Train",
"DCGAN"
] | def train(self, config):
"""Train DCGAN"""
if config.dataset == 'mnist':
data_X, data_y = self.load_mnist()
else:
data = glob(os.path.join("./data", config.dataset, "*.jpg"))
if self.config.use_kernel:
kernel_optim = tf.train.MomentumOptimizer(self.lr, 0.9) \
.minimize(self.ratio_loss, var_list=self.g_vars, global_step=self.global_step)
self.sess.run(tf.global_variables_initializer())
TrainSummary = tf.summary.merge_all()
self.writer = tf.summary.FileWriter(self.log_dir, self.sess.graph)
sample_z = np.random.uniform(-1, 1, size=(self.sample_size , self.z_dim))
if config.dataset == 'mnist':
sample_images = data_X[0:self.sample_size]
else:
return
counter = 1
start_time = time.time()
if self.load(self.checkpoint_dir):
print(" [*] Load SUCCESS")
else:
print(" [!] Load failed...")
if config.dataset == 'mnist':
batch_idxs = len(data_X) // config.batch_size
else:
data = glob(os.path.join("./data", config.dataset, "*.jpg"))
batch_idxs = min(len(data), config.train_size) // config.batch_size
lr = self.config.learning_rate
for it in xrange(self.config.max_iteration):
if np.mod(it, batch_idxs) == 0:
perm = np.random.permutation(len(data_X))
if np.mod(it, 10000) == 1:
lr = lr * self.config.decay_rate
idx = np.mod(it, batch_idxs)
batch_images = data_X[perm[idx*config.batch_size:
(idx+1)*config.batch_size]]
batch_z = np.random.uniform(
-1, 1, [config.batch_size, self.z_dim]).astype(np.float32)
if self.config.use_kernel:
_ , summary_str, step, ratio_loss = self.sess.run(
[kernel_optim, TrainSummary, self.global_step,
self.ratio_loss],
feed_dict={self.lr: lr, self.images: batch_images,
self.z: batch_z})
counter += 1
if np.mod(counter, 10) == 1:
self.writer.add_summary(summary_str, step)
print("Epoch: [%2d] time: %4.4f, ratio_loss: %.8f"
% (it, time.time() - start_time, ratio_loss))
if np.mod(counter, 500) == 1:
self.save(self.checkpoint_dir, counter)
samples = self.sess.run(self.sampler, feed_dict={
self.z: sample_z, self.images: sample_images})
print(samples.shape)
p = os.path.join(self.sample_dir, 'train_{:02d}.png'.format(it))
save_images(samples[:64, :, :, :], [8, 8], p) | [
"def",
"train",
"(",
"self",
",",
"config",
")",
":",
"if",
"config",
".",
"dataset",
"==",
"'mnist'",
":",
"data_X",
",",
"data_y",
"=",
"self",
".",
"load_mnist",
"(",
")",
"else",
":",
"data",
"=",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"\"./data\"",
",",
"config",
".",
"dataset",
",",
"\"*.jpg\"",
")",
")",
"if",
"self",
".",
"config",
".",
"use_kernel",
":",
"kernel_optim",
"=",
"tf",
".",
"train",
".",
"MomentumOptimizer",
"(",
"self",
".",
"lr",
",",
"0.9",
")",
".",
"minimize",
"(",
"self",
".",
"ratio_loss",
",",
"var_list",
"=",
"self",
".",
"g_vars",
",",
"global_step",
"=",
"self",
".",
"global_step",
")",
"self",
".",
"sess",
".",
"run",
"(",
"tf",
".",
"global_variables_initializer",
"(",
")",
")",
"TrainSummary",
"=",
"tf",
".",
"summary",
".",
"merge_all",
"(",
")",
"self",
".",
"writer",
"=",
"tf",
".",
"summary",
".",
"FileWriter",
"(",
"self",
".",
"log_dir",
",",
"self",
".",
"sess",
".",
"graph",
")",
"sample_z",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"1",
",",
"1",
",",
"size",
"=",
"(",
"self",
".",
"sample_size",
",",
"self",
".",
"z_dim",
")",
")",
"if",
"config",
".",
"dataset",
"==",
"'mnist'",
":",
"sample_images",
"=",
"data_X",
"[",
"0",
":",
"self",
".",
"sample_size",
"]",
"else",
":",
"return",
"counter",
"=",
"1",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"if",
"self",
".",
"load",
"(",
"self",
".",
"checkpoint_dir",
")",
":",
"print",
"(",
"\" [*] Load SUCCESS\"",
")",
"else",
":",
"print",
"(",
"\" [!] Load failed...\"",
")",
"if",
"config",
".",
"dataset",
"==",
"'mnist'",
":",
"batch_idxs",
"=",
"len",
"(",
"data_X",
")",
"//",
"config",
".",
"batch_size",
"else",
":",
"data",
"=",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"\"./data\"",
",",
"config",
".",
"dataset",
",",
"\"*.jpg\"",
")",
")",
"batch_idxs",
"=",
"min",
"(",
"len",
"(",
"data",
")",
",",
"config",
".",
"train_size",
")",
"//",
"config",
".",
"batch_size",
"lr",
"=",
"self",
".",
"config",
".",
"learning_rate",
"for",
"it",
"in",
"xrange",
"(",
"self",
".",
"config",
".",
"max_iteration",
")",
":",
"if",
"np",
".",
"mod",
"(",
"it",
",",
"batch_idxs",
")",
"==",
"0",
":",
"perm",
"=",
"np",
".",
"random",
".",
"permutation",
"(",
"len",
"(",
"data_X",
")",
")",
"if",
"np",
".",
"mod",
"(",
"it",
",",
"10000",
")",
"==",
"1",
":",
"lr",
"=",
"lr",
"*",
"self",
".",
"config",
".",
"decay_rate",
"idx",
"=",
"np",
".",
"mod",
"(",
"it",
",",
"batch_idxs",
")",
"batch_images",
"=",
"data_X",
"[",
"perm",
"[",
"idx",
"*",
"config",
".",
"batch_size",
":",
"(",
"idx",
"+",
"1",
")",
"*",
"config",
".",
"batch_size",
"]",
"]",
"batch_z",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"1",
",",
"1",
",",
"[",
"config",
".",
"batch_size",
",",
"self",
".",
"z_dim",
"]",
")",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"if",
"self",
".",
"config",
".",
"use_kernel",
":",
"_",
",",
"summary_str",
",",
"step",
",",
"ratio_loss",
"=",
"self",
".",
"sess",
".",
"run",
"(",
"[",
"kernel_optim",
",",
"TrainSummary",
",",
"self",
".",
"global_step",
",",
"self",
".",
"ratio_loss",
"]",
",",
"feed_dict",
"=",
"{",
"self",
".",
"lr",
":",
"lr",
",",
"self",
".",
"images",
":",
"batch_images",
",",
"self",
".",
"z",
":",
"batch_z",
"}",
")",
"counter",
"+=",
"1",
"if",
"np",
".",
"mod",
"(",
"counter",
",",
"10",
")",
"==",
"1",
":",
"self",
".",
"writer",
".",
"add_summary",
"(",
"summary_str",
",",
"step",
")",
"print",
"(",
"\"Epoch: [%2d] time: %4.4f, ratio_loss: %.8f\"",
"%",
"(",
"it",
",",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
",",
"ratio_loss",
")",
")",
"if",
"np",
".",
"mod",
"(",
"counter",
",",
"500",
")",
"==",
"1",
":",
"self",
".",
"save",
"(",
"self",
".",
"checkpoint_dir",
",",
"counter",
")",
"samples",
"=",
"self",
".",
"sess",
".",
"run",
"(",
"self",
".",
"sampler",
",",
"feed_dict",
"=",
"{",
"self",
".",
"z",
":",
"sample_z",
",",
"self",
".",
"images",
":",
"sample_images",
"}",
")",
"print",
"(",
"samples",
".",
"shape",
")",
"p",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"sample_dir",
",",
"'train_{:02d}.png'",
".",
"format",
"(",
"it",
")",
")",
"save_images",
"(",
"samples",
"[",
":",
"64",
",",
":",
",",
":",
",",
":",
"]",
",",
"[",
"8",
",",
"8",
"]",
",",
"p",
")"
] | https://github.com/djsutherland/opt-mmd/blob/5c02a92972df099628a4bc8351980ad9f317b6d0/gan/model_tmmd.py#L113-L178 |
||
oracle/graalpython | 577e02da9755d916056184ec441c26e00b70145c | graalpython/lib-python/3/ipaddress.py | python | IPv6Address.ipv4_mapped | (self) | return IPv4Address(self._ip & 0xFFFFFFFF) | Return the IPv4 mapped address.
Returns:
If the IPv6 address is a v4 mapped address, return the
IPv4 mapped address. Return None otherwise. | Return the IPv4 mapped address. | [
"Return",
"the",
"IPv4",
"mapped",
"address",
"."
] | def ipv4_mapped(self):
"""Return the IPv4 mapped address.
Returns:
If the IPv6 address is a v4 mapped address, return the
IPv4 mapped address. Return None otherwise.
"""
if (self._ip >> 32) != 0xFFFF:
return None
return IPv4Address(self._ip & 0xFFFFFFFF) | [
"def",
"ipv4_mapped",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_ip",
">>",
"32",
")",
"!=",
"0xFFFF",
":",
"return",
"None",
"return",
"IPv4Address",
"(",
"self",
".",
"_ip",
"&",
"0xFFFFFFFF",
")"
] | https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/ipaddress.py#L1941-L1951 |
|
sethmlarson/virtualbox-python | 984a6e2cb0e8996f4df40f4444c1528849f1c70d | virtualbox/library.py | python | IDHCPServer.get_config | (self, scope, name, slot, may_add) | return config | Gets or adds a configuration.
in scope of type :class:`DHCPConfigScope`
The kind of configuration being sought or added.
in name of type str
Meaning depends on the @a scope:
- Ignored when the @a scope is :py:attr:`DHCPConfigScope.global_p` .
- A VM name or UUID for :py:attr:`DHCPConfigScope.machine_nic` .
- A MAC address for :py:attr:`DHCPConfigScope.mac` .
- A group name for :py:attr:`DHCPConfigScope.group` .
in slot of type int
The NIC slot when @a scope is set to :py:attr:`DHCPConfigScope.machine_nic` ,
must be zero for all other scope values.
in may_add of type bool
Set to @c TRUE if the configuration should be added if not found.
If set to @c FALSE the method will fail with VBOX_E_OBJECT_NOT_FOUND.
return config of type :class:`IDHCPConfig`
The requested configuration. | Gets or adds a configuration. | [
"Gets",
"or",
"adds",
"a",
"configuration",
"."
] | def get_config(self, scope, name, slot, may_add):
"""Gets or adds a configuration.
in scope of type :class:`DHCPConfigScope`
The kind of configuration being sought or added.
in name of type str
Meaning depends on the @a scope:
- Ignored when the @a scope is :py:attr:`DHCPConfigScope.global_p` .
- A VM name or UUID for :py:attr:`DHCPConfigScope.machine_nic` .
- A MAC address for :py:attr:`DHCPConfigScope.mac` .
- A group name for :py:attr:`DHCPConfigScope.group` .
in slot of type int
The NIC slot when @a scope is set to :py:attr:`DHCPConfigScope.machine_nic` ,
must be zero for all other scope values.
in may_add of type bool
Set to @c TRUE if the configuration should be added if not found.
If set to @c FALSE the method will fail with VBOX_E_OBJECT_NOT_FOUND.
return config of type :class:`IDHCPConfig`
The requested configuration.
"""
if not isinstance(scope, DHCPConfigScope):
raise TypeError("scope can only be an instance of type DHCPConfigScope")
if not isinstance(name, basestring):
raise TypeError("name can only be an instance of type basestring")
if not isinstance(slot, baseinteger):
raise TypeError("slot can only be an instance of type baseinteger")
if not isinstance(may_add, bool):
raise TypeError("may_add can only be an instance of type bool")
config = self._call("getConfig", in_p=[scope, name, slot, may_add])
config = IDHCPConfig(config)
return config | [
"def",
"get_config",
"(",
"self",
",",
"scope",
",",
"name",
",",
"slot",
",",
"may_add",
")",
":",
"if",
"not",
"isinstance",
"(",
"scope",
",",
"DHCPConfigScope",
")",
":",
"raise",
"TypeError",
"(",
"\"scope can only be an instance of type DHCPConfigScope\"",
")",
"if",
"not",
"isinstance",
"(",
"name",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"name can only be an instance of type basestring\"",
")",
"if",
"not",
"isinstance",
"(",
"slot",
",",
"baseinteger",
")",
":",
"raise",
"TypeError",
"(",
"\"slot can only be an instance of type baseinteger\"",
")",
"if",
"not",
"isinstance",
"(",
"may_add",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"may_add can only be an instance of type bool\"",
")",
"config",
"=",
"self",
".",
"_call",
"(",
"\"getConfig\"",
",",
"in_p",
"=",
"[",
"scope",
",",
"name",
",",
"slot",
",",
"may_add",
"]",
")",
"config",
"=",
"IDHCPConfig",
"(",
"config",
")",
"return",
"config"
] | https://github.com/sethmlarson/virtualbox-python/blob/984a6e2cb0e8996f4df40f4444c1528849f1c70d/virtualbox/library.py#L9589-L9624 |
|
giotto-ai/giotto-tda | 608aab4071677ec02623c306636439e30a229de6 | gtda/externals/python/periodic_cubical_complex_interface.py | python | PeriodicCubicalComplex.__is_persistence_defined | (self) | return False | Returns true if Persistence pointer is not NULL. | Returns true if Persistence pointer is not NULL. | [
"Returns",
"true",
"if",
"Persistence",
"pointer",
"is",
"not",
"NULL",
"."
] | def __is_persistence_defined(self):
"""Returns true if Persistence pointer is not NULL.
"""
if self.pcohptr is not None:
return True
return False | [
"def",
"__is_persistence_defined",
"(",
"self",
")",
":",
"if",
"self",
".",
"pcohptr",
"is",
"not",
"None",
":",
"return",
"True",
"return",
"False"
] | https://github.com/giotto-ai/giotto-tda/blob/608aab4071677ec02623c306636439e30a229de6/gtda/externals/python/periodic_cubical_complex_interface.py#L63-L68 |
|
ibm-research-tokyo/dybm | a6d308c896c2f66680ee9c5d05a3d7826cc27c64 | src/pydybm/time_series/functional_dybm.py | python | FuncLinearDyBM._update_parameters | (self, delta) | update the parameters by delta
Parameters
----------
delta: dict
amount by which the parameters are updated | update the parameters by delta | [
"update",
"the",
"parameters",
"by",
"delta"
] | def _update_parameters(self, delta):
"""
update the parameters by delta
Parameters
----------
delta: dict
amount by which the parameters are updated
"""
self.l_DyBM._update_parameters(delta) | [
"def",
"_update_parameters",
"(",
"self",
",",
"delta",
")",
":",
"self",
".",
"l_DyBM",
".",
"_update_parameters",
"(",
"delta",
")"
] | https://github.com/ibm-research-tokyo/dybm/blob/a6d308c896c2f66680ee9c5d05a3d7826cc27c64/src/pydybm/time_series/functional_dybm.py#L831-L840 |
||
odlgroup/odl | 0b088df8dc4621c68b9414c3deff9127f4c4f11d | odl/phantom/transmission.py | python | shepp_logan | (space, modified=False, min_pt=None, max_pt=None) | return ellipsoid_phantom(space, ellipsoids, min_pt, max_pt) | Standard Shepp-Logan phantom in 2 or 3 dimensions.
Parameters
----------
space : `DiscretizedSpace`
Space in which the phantom is created, must be 2- or 3-dimensional.
If ``space.shape`` is 1 in an axis, a corresponding slice of the
phantom is created.
modified : `bool`, optional
True if the modified Shepp-Logan phantom should be given.
The modified phantom has greatly amplified contrast to aid
visualization.
min_pt, max_pt : array-like, optional
If provided, use these vectors to determine the bounding box of the
phantom instead of ``space.min_pt`` and ``space.max_pt``.
It is currently required that ``min_pt >= space.min_pt`` and
``max_pt <= space.max_pt``, i.e., shifting or scaling outside the
original space is not allowed.
Providing one of them results in a shift, e.g., for ``min_pt``::
new_min_pt = min_pt
new_max_pt = space.max_pt + (min_pt - space.min_pt)
Providing both results in a scaled version of the phantom.
See Also
--------
forbild : Similar phantom but with more complexity. Only supports 2d.
odl.phantom.geometric.defrise : Geometry test phantom
shepp_logan_ellipsoids : Get the parameters that define this phantom
odl.phantom.geometric.ellipsoid_phantom :
Function for creating arbitrary ellipsoid phantoms
References
----------
.. _Shepp-Logan phantom: https://en.wikipedia.org/wiki/Shepp-Logan_phantom | Standard Shepp-Logan phantom in 2 or 3 dimensions. | [
"Standard",
"Shepp",
"-",
"Logan",
"phantom",
"in",
"2",
"or",
"3",
"dimensions",
"."
] | def shepp_logan(space, modified=False, min_pt=None, max_pt=None):
"""Standard Shepp-Logan phantom in 2 or 3 dimensions.
Parameters
----------
space : `DiscretizedSpace`
Space in which the phantom is created, must be 2- or 3-dimensional.
If ``space.shape`` is 1 in an axis, a corresponding slice of the
phantom is created.
modified : `bool`, optional
True if the modified Shepp-Logan phantom should be given.
The modified phantom has greatly amplified contrast to aid
visualization.
min_pt, max_pt : array-like, optional
If provided, use these vectors to determine the bounding box of the
phantom instead of ``space.min_pt`` and ``space.max_pt``.
It is currently required that ``min_pt >= space.min_pt`` and
``max_pt <= space.max_pt``, i.e., shifting or scaling outside the
original space is not allowed.
Providing one of them results in a shift, e.g., for ``min_pt``::
new_min_pt = min_pt
new_max_pt = space.max_pt + (min_pt - space.min_pt)
Providing both results in a scaled version of the phantom.
See Also
--------
forbild : Similar phantom but with more complexity. Only supports 2d.
odl.phantom.geometric.defrise : Geometry test phantom
shepp_logan_ellipsoids : Get the parameters that define this phantom
odl.phantom.geometric.ellipsoid_phantom :
Function for creating arbitrary ellipsoid phantoms
References
----------
.. _Shepp-Logan phantom: https://en.wikipedia.org/wiki/Shepp-Logan_phantom
"""
ellipsoids = shepp_logan_ellipsoids(space.ndim, modified)
return ellipsoid_phantom(space, ellipsoids, min_pt, max_pt) | [
"def",
"shepp_logan",
"(",
"space",
",",
"modified",
"=",
"False",
",",
"min_pt",
"=",
"None",
",",
"max_pt",
"=",
"None",
")",
":",
"ellipsoids",
"=",
"shepp_logan_ellipsoids",
"(",
"space",
".",
"ndim",
",",
"modified",
")",
"return",
"ellipsoid_phantom",
"(",
"space",
",",
"ellipsoids",
",",
"min_pt",
",",
"max_pt",
")"
] | https://github.com/odlgroup/odl/blob/0b088df8dc4621c68b9414c3deff9127f4c4f11d/odl/phantom/transmission.py#L114-L154 |
|
getsentry/sentry | 83b1f25aac3e08075e0e2495bc29efaf35aca18a | src/sentry/models/release.py | python | ReleaseQuerySet.filter_to_semver | (self) | return self.filter(major__isnull=False) | Filters the queryset to only include semver compatible rows | Filters the queryset to only include semver compatible rows | [
"Filters",
"the",
"queryset",
"to",
"only",
"include",
"semver",
"compatible",
"rows"
] | def filter_to_semver(self):
"""
Filters the queryset to only include semver compatible rows
"""
return self.filter(major__isnull=False) | [
"def",
"filter_to_semver",
"(",
"self",
")",
":",
"return",
"self",
".",
"filter",
"(",
"major__isnull",
"=",
"False",
")"
] | https://github.com/getsentry/sentry/blob/83b1f25aac3e08075e0e2495bc29efaf35aca18a/src/sentry/models/release.py#L139-L143 |
|
larryhastings/gilectomy | 4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a | Lib/xml/sax/_exceptions.py | python | SAXException.getMessage | (self) | return self._msg | Return a message for this exception. | Return a message for this exception. | [
"Return",
"a",
"message",
"for",
"this",
"exception",
"."
] | def getMessage(self):
"Return a message for this exception."
return self._msg | [
"def",
"getMessage",
"(",
"self",
")",
":",
"return",
"self",
".",
"_msg"
] | https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/xml/sax/_exceptions.py#L26-L28 |
|
angr/angr-management | 60ae5fa483e74810fb3a3da8d37b00034d7fefab | angrmanagement/ui/views/hex_view.py | python | PatchHighlightRegion.can_merge_with | (self, other: 'PatchHighlightRegion') | return other.patch.addr == (self.patch.addr + len(self.patch)) | Determine if this patch can be merged with `other`. We only consider directly adjacent patches. | Determine if this patch can be merged with `other`. We only consider directly adjacent patches. | [
"Determine",
"if",
"this",
"patch",
"can",
"be",
"merged",
"with",
"other",
".",
"We",
"only",
"consider",
"directly",
"adjacent",
"patches",
"."
] | def can_merge_with(self, other: 'PatchHighlightRegion') -> bool:
"""
Determine if this patch can be merged with `other`. We only consider directly adjacent patches.
"""
return other.patch.addr == (self.patch.addr + len(self.patch)) | [
"def",
"can_merge_with",
"(",
"self",
",",
"other",
":",
"'PatchHighlightRegion'",
")",
"->",
"bool",
":",
"return",
"other",
".",
"patch",
".",
"addr",
"==",
"(",
"self",
".",
"patch",
".",
"addr",
"+",
"len",
"(",
"self",
".",
"patch",
")",
")"
] | https://github.com/angr/angr-management/blob/60ae5fa483e74810fb3a3da8d37b00034d7fefab/angrmanagement/ui/views/hex_view.py#L118-L122 |
|
accel-brain/accel-brain-code | 86f489dc9be001a3bae6d053f48d6b57c0bedb95 | Accel-Brain-Base/accelbrainbase/controllablemodel/_mxnet/gan_controller.py | python | GANController.set_generator_loss | (self, value) | setter for `GeneratorLoss`. | setter for `GeneratorLoss`. | [
"setter",
"for",
"GeneratorLoss",
"."
] | def set_generator_loss(self, value):
''' setter for `GeneratorLoss`. '''
self.__generator_loss = value | [
"def",
"set_generator_loss",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"__generator_loss",
"=",
"value"
] | https://github.com/accel-brain/accel-brain-code/blob/86f489dc9be001a3bae6d053f48d6b57c0bedb95/Accel-Brain-Base/accelbrainbase/controllablemodel/_mxnet/gan_controller.py#L417-L419 |
||
qutebrowser/qutebrowser | 3a2aaaacbf97f4bf0c72463f3da94ed2822a5442 | qutebrowser/config/configfiles.py | python | YamlConfig.__iter__ | (self) | Iterate over configutils.Values items. | Iterate over configutils.Values items. | [
"Iterate",
"over",
"configutils",
".",
"Values",
"items",
"."
] | def __iter__(self) -> Iterator[configutils.Values]:
"""Iterate over configutils.Values items."""
yield from self._values.values() | [
"def",
"__iter__",
"(",
"self",
")",
"->",
"Iterator",
"[",
"configutils",
".",
"Values",
"]",
":",
"yield",
"from",
"self",
".",
"_values",
".",
"values",
"(",
")"
] | https://github.com/qutebrowser/qutebrowser/blob/3a2aaaacbf97f4bf0c72463f3da94ed2822a5442/qutebrowser/config/configfiles.py#L211-L213 |
||
Drakkar-Software/OctoBot | c80ed2270e5d085994213955c0f56b9e3b70b476 | octobot/producers/interface_producer.py | python | InterfaceProducer._create_interface_if_relevant | (self, interface_factory, interface_class,
backtesting_enabled, edited_config) | [] | async def _create_interface_if_relevant(self, interface_factory, interface_class,
backtesting_enabled, edited_config):
if self._is_interface_relevant(interface_class, backtesting_enabled):
await self.send(bot_id=self.octobot.bot_id,
subject=common_enums.OctoBotChannelSubjects.CREATION.value,
action=service_channel_consumer.OctoBotChannelServiceActions.INTERFACE.value,
data={
service_channel_consumer.OctoBotChannelServiceDataKeys.EDITED_CONFIG.value:
edited_config,
service_channel_consumer.OctoBotChannelServiceDataKeys.BACKTESTING_ENABLED.value:
backtesting_enabled,
service_channel_consumer.OctoBotChannelServiceDataKeys.CLASS.value: interface_class,
service_channel_consumer.OctoBotChannelServiceDataKeys.FACTORY.value: interface_factory
}) | [
"async",
"def",
"_create_interface_if_relevant",
"(",
"self",
",",
"interface_factory",
",",
"interface_class",
",",
"backtesting_enabled",
",",
"edited_config",
")",
":",
"if",
"self",
".",
"_is_interface_relevant",
"(",
"interface_class",
",",
"backtesting_enabled",
")",
":",
"await",
"self",
".",
"send",
"(",
"bot_id",
"=",
"self",
".",
"octobot",
".",
"bot_id",
",",
"subject",
"=",
"common_enums",
".",
"OctoBotChannelSubjects",
".",
"CREATION",
".",
"value",
",",
"action",
"=",
"service_channel_consumer",
".",
"OctoBotChannelServiceActions",
".",
"INTERFACE",
".",
"value",
",",
"data",
"=",
"{",
"service_channel_consumer",
".",
"OctoBotChannelServiceDataKeys",
".",
"EDITED_CONFIG",
".",
"value",
":",
"edited_config",
",",
"service_channel_consumer",
".",
"OctoBotChannelServiceDataKeys",
".",
"BACKTESTING_ENABLED",
".",
"value",
":",
"backtesting_enabled",
",",
"service_channel_consumer",
".",
"OctoBotChannelServiceDataKeys",
".",
"CLASS",
".",
"value",
":",
"interface_class",
",",
"service_channel_consumer",
".",
"OctoBotChannelServiceDataKeys",
".",
"FACTORY",
".",
"value",
":",
"interface_factory",
"}",
")"
] | https://github.com/Drakkar-Software/OctoBot/blob/c80ed2270e5d085994213955c0f56b9e3b70b476/octobot/producers/interface_producer.py#L101-L114 |
||||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_hxb2/lib/python3.5/site-packages/pip/_vendor/requests/packages/chardet/chardistribution.py | python | EUCJPDistributionAnalysis.get_order | (self, aBuf) | [] | def get_order(self, aBuf):
# for euc-JP encoding, we are interested
# first byte range: 0xa0 -- 0xfe
# second byte range: 0xa1 -- 0xfe
# no validation needed here. State machine has done that
char = wrap_ord(aBuf[0])
if char >= 0xA0:
return 94 * (char - 0xA1) + wrap_ord(aBuf[1]) - 0xa1
else:
return -1 | [
"def",
"get_order",
"(",
"self",
",",
"aBuf",
")",
":",
"# for euc-JP encoding, we are interested",
"# first byte range: 0xa0 -- 0xfe",
"# second byte range: 0xa1 -- 0xfe",
"# no validation needed here. State machine has done that",
"char",
"=",
"wrap_ord",
"(",
"aBuf",
"[",
"0",
"]",
")",
"if",
"char",
">=",
"0xA0",
":",
"return",
"94",
"*",
"(",
"char",
"-",
"0xA1",
")",
"+",
"wrap_ord",
"(",
"aBuf",
"[",
"1",
"]",
")",
"-",
"0xa1",
"else",
":",
"return",
"-",
"1"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/pip/_vendor/requests/packages/chardet/chardistribution.py#L222-L231 |
||||
DeepPavlov/convai | 54d921f99606960941ece4865a396925dfc264f4 | 2017/solutions/kaib/demo/bot_code/QA.py | python | QA.__init__ | (self, opt, cuda=False) | self.doc_reader = PqmnAgent(opt)
self.doc_reader.model.network.eval() | self.doc_reader = PqmnAgent(opt)
self.doc_reader.model.network.eval() | [
"self",
".",
"doc_reader",
"=",
"PqmnAgent",
"(",
"opt",
")",
"self",
".",
"doc_reader",
".",
"model",
".",
"network",
".",
"eval",
"()"
] | def __init__(self, opt, cuda=False):
print('initialize QA module (NOTE : NO PREPROCESS CODE FOR NOW. IMPORT IT FROM CC)')
# Check options
assert('pretrained_model' in opt)
assert(opt['datatype'] == 'valid') # SQuAD only have valid data
opt['batchsize']=1 #online mode
opt['cuda'] = cuda
opt['no_cuda'] = True
# Load document reader
#self.doc_reader = DocReaderAgent(opt)
#self.doc_reader = DrqaAgent(opt)
# Ver2
"""
self.doc_reader = PqmnAgent(opt)
self.doc_reader.model.network.eval()
"""
# Ver3
self.agent = create_agent(opt)
self.agent.model.network.eval() | [
"def",
"__init__",
"(",
"self",
",",
"opt",
",",
"cuda",
"=",
"False",
")",
":",
"print",
"(",
"'initialize QA module (NOTE : NO PREPROCESS CODE FOR NOW. IMPORT IT FROM CC)'",
")",
"# Check options",
"assert",
"(",
"'pretrained_model'",
"in",
"opt",
")",
"assert",
"(",
"opt",
"[",
"'datatype'",
"]",
"==",
"'valid'",
")",
"# SQuAD only have valid data",
"opt",
"[",
"'batchsize'",
"]",
"=",
"1",
"#online mode",
"opt",
"[",
"'cuda'",
"]",
"=",
"cuda",
"opt",
"[",
"'no_cuda'",
"]",
"=",
"True",
"# Load document reader",
"#self.doc_reader = DocReaderAgent(opt)",
"#self.doc_reader = DrqaAgent(opt)",
"# Ver2",
"# Ver3",
"self",
".",
"agent",
"=",
"create_agent",
"(",
"opt",
")",
"self",
".",
"agent",
".",
"model",
".",
"network",
".",
"eval",
"(",
")"
] | https://github.com/DeepPavlov/convai/blob/54d921f99606960941ece4865a396925dfc264f4/2017/solutions/kaib/demo/bot_code/QA.py#L23-L45 |
||
MrYsLab/pymata-aio | ccd1fd361d85a71cdde1c46cc733155ac43e93f7 | examples/sparkfun_redbot/sparkfun_experiments/library/mma8452q3.py | python | MMA8452Q3.check_who_am_i | (self) | return rval | This method checks verifies the device ID.
@return: True if valid, False if not | This method checks verifies the device ID. | [
"This",
"method",
"checks",
"verifies",
"the",
"device",
"ID",
"."
] | def check_who_am_i(self):
"""
This method checks verifies the device ID.
@return: True if valid, False if not
"""
register = self.MMA8452Q_Register['WHO_AM_I']
self.board.i2c_read_request(self.address, register, 1,
Constants.I2C_READ | Constants.I2C_END_TX_MASK,
self.data_val, Constants.CB_TYPE_DIRECT)
reply = self.wait_for_read_result()
if reply[self.data_start] == self.device_id:
rval = True
else:
rval = False
return rval | [
"def",
"check_who_am_i",
"(",
"self",
")",
":",
"register",
"=",
"self",
".",
"MMA8452Q_Register",
"[",
"'WHO_AM_I'",
"]",
"self",
".",
"board",
".",
"i2c_read_request",
"(",
"self",
".",
"address",
",",
"register",
",",
"1",
",",
"Constants",
".",
"I2C_READ",
"|",
"Constants",
".",
"I2C_END_TX_MASK",
",",
"self",
".",
"data_val",
",",
"Constants",
".",
"CB_TYPE_DIRECT",
")",
"reply",
"=",
"self",
".",
"wait_for_read_result",
"(",
")",
"if",
"reply",
"[",
"self",
".",
"data_start",
"]",
"==",
"self",
".",
"device_id",
":",
"rval",
"=",
"True",
"else",
":",
"rval",
"=",
"False",
"return",
"rval"
] | https://github.com/MrYsLab/pymata-aio/blob/ccd1fd361d85a71cdde1c46cc733155ac43e93f7/examples/sparkfun_redbot/sparkfun_experiments/library/mma8452q3.py#L163-L181 |
|
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/docutils/utils/math/math2html.py | python | BracketProcessor.resize | (self, command, size) | Resize a bracket command to the given size. | Resize a bracket command to the given size. | [
"Resize",
"a",
"bracket",
"command",
"to",
"the",
"given",
"size",
"."
] | def resize(self, command, size):
"Resize a bracket command to the given size."
character = command.extracttext()
alignment = command.command.replace('\\', '')
bracket = BigBracket(size, character, alignment)
command.output = ContentsOutput()
command.contents = bracket.getcontents() | [
"def",
"resize",
"(",
"self",
",",
"command",
",",
"size",
")",
":",
"character",
"=",
"command",
".",
"extracttext",
"(",
")",
"alignment",
"=",
"command",
".",
"command",
".",
"replace",
"(",
"'\\\\'",
",",
"''",
")",
"bracket",
"=",
"BigBracket",
"(",
"size",
",",
"character",
",",
"alignment",
")",
"command",
".",
"output",
"=",
"ContentsOutput",
"(",
")",
"command",
".",
"contents",
"=",
"bracket",
".",
"getcontents",
"(",
")"
] | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/docutils/utils/math/math2html.py#L4802-L4808 |
||
google-research/meta-dataset | c67dd2bb66fb2a4ce7e4e9906878e13d9b851eb5 | meta_dataset/models/functional_backbones.py | python | resnet34 | (x,
is_training,
weight_decay,
params=None,
moments=None,
reuse=tf.AUTO_REUSE,
scope='resnet34',
backprop_through_moments=True,
use_bounded_activation=False,
max_stride=None,
deeplab_alignment=True,
keep_spatial_dims=False) | return _resnet(
x,
is_training,
weight_decay,
scope,
reuse=reuse,
params=params,
moments=moments,
backprop_through_moments=backprop_through_moments,
use_bounded_activation=use_bounded_activation,
blocks=(3, 4, 6, 3),
max_stride=max_stride,
deeplab_alignment=deeplab_alignment,
keep_spatial_dims=keep_spatial_dims) | ResNet34 embedding function. | ResNet34 embedding function. | [
"ResNet34",
"embedding",
"function",
"."
] | def resnet34(x,
is_training,
weight_decay,
params=None,
moments=None,
reuse=tf.AUTO_REUSE,
scope='resnet34',
backprop_through_moments=True,
use_bounded_activation=False,
max_stride=None,
deeplab_alignment=True,
keep_spatial_dims=False):
"""ResNet34 embedding function."""
return _resnet(
x,
is_training,
weight_decay,
scope,
reuse=reuse,
params=params,
moments=moments,
backprop_through_moments=backprop_through_moments,
use_bounded_activation=use_bounded_activation,
blocks=(3, 4, 6, 3),
max_stride=max_stride,
deeplab_alignment=deeplab_alignment,
keep_spatial_dims=keep_spatial_dims) | [
"def",
"resnet34",
"(",
"x",
",",
"is_training",
",",
"weight_decay",
",",
"params",
"=",
"None",
",",
"moments",
"=",
"None",
",",
"reuse",
"=",
"tf",
".",
"AUTO_REUSE",
",",
"scope",
"=",
"'resnet34'",
",",
"backprop_through_moments",
"=",
"True",
",",
"use_bounded_activation",
"=",
"False",
",",
"max_stride",
"=",
"None",
",",
"deeplab_alignment",
"=",
"True",
",",
"keep_spatial_dims",
"=",
"False",
")",
":",
"return",
"_resnet",
"(",
"x",
",",
"is_training",
",",
"weight_decay",
",",
"scope",
",",
"reuse",
"=",
"reuse",
",",
"params",
"=",
"params",
",",
"moments",
"=",
"moments",
",",
"backprop_through_moments",
"=",
"backprop_through_moments",
",",
"use_bounded_activation",
"=",
"use_bounded_activation",
",",
"blocks",
"=",
"(",
"3",
",",
"4",
",",
"6",
",",
"3",
")",
",",
"max_stride",
"=",
"max_stride",
",",
"deeplab_alignment",
"=",
"deeplab_alignment",
",",
"keep_spatial_dims",
"=",
"keep_spatial_dims",
")"
] | https://github.com/google-research/meta-dataset/blob/c67dd2bb66fb2a4ce7e4e9906878e13d9b851eb5/meta_dataset/models/functional_backbones.py#L969-L995 |
|
sfu-db/dataprep | 6dfb9c659e8bf73f07978ae195d0372495c6f118 | dataprep/clean/clean_es_dni.py | python | _format | (val: Any, output_format: str = "standard", errors: str = "coarse") | return result | Reformat a number string with proper separators and whitespace.
Parameters
----------
val
The value of number string.
output_format
If output_format = 'compact', return string without any separators or whitespace.
If output_format = 'standard', return string with proper separators and whitespace.
Note: in the case of DNI, the compact format is the same as the standard one. | Reformat a number string with proper separators and whitespace. | [
"Reformat",
"a",
"number",
"string",
"with",
"proper",
"separators",
"and",
"whitespace",
"."
] | def _format(val: Any, output_format: str = "standard", errors: str = "coarse") -> Any:
"""
Reformat a number string with proper separators and whitespace.
Parameters
----------
val
The value of number string.
output_format
If output_format = 'compact', return string without any separators or whitespace.
If output_format = 'standard', return string with proper separators and whitespace.
Note: in the case of DNI, the compact format is the same as the standard one.
"""
val = str(val)
result: Any = []
if val in NULL_VALUES:
return [np.nan]
if not validate_es_dni(val):
if errors == "raise":
raise ValueError(f"Unable to parse value {val}")
error_result = val if errors == "ignore" else np.nan
return [error_result]
if output_format in {"compact", "standard"}:
result = [dni.compact(val)] + result
return result | [
"def",
"_format",
"(",
"val",
":",
"Any",
",",
"output_format",
":",
"str",
"=",
"\"standard\"",
",",
"errors",
":",
"str",
"=",
"\"coarse\"",
")",
"->",
"Any",
":",
"val",
"=",
"str",
"(",
"val",
")",
"result",
":",
"Any",
"=",
"[",
"]",
"if",
"val",
"in",
"NULL_VALUES",
":",
"return",
"[",
"np",
".",
"nan",
"]",
"if",
"not",
"validate_es_dni",
"(",
"val",
")",
":",
"if",
"errors",
"==",
"\"raise\"",
":",
"raise",
"ValueError",
"(",
"f\"Unable to parse value {val}\"",
")",
"error_result",
"=",
"val",
"if",
"errors",
"==",
"\"ignore\"",
"else",
"np",
".",
"nan",
"return",
"[",
"error_result",
"]",
"if",
"output_format",
"in",
"{",
"\"compact\"",
",",
"\"standard\"",
"}",
":",
"result",
"=",
"[",
"dni",
".",
"compact",
"(",
"val",
")",
"]",
"+",
"result",
"return",
"result"
] | https://github.com/sfu-db/dataprep/blob/6dfb9c659e8bf73f07978ae195d0372495c6f118/dataprep/clean/clean_es_dni.py#L133-L161 |
|
santhoshkolloju/Abstractive-Summarization-With-Transfer-Learning | 97ff2ae3ba9f2d478e174444c4e0f5349f28c319 | texar_repo/texar/modules/memory/memory_network.py | python | MemNetBase.raw_memory_dim | (self) | return self._raw_memory_dim | The dimension of memory element (or vocabulary size). | The dimension of memory element (or vocabulary size). | [
"The",
"dimension",
"of",
"memory",
"element",
"(",
"or",
"vocabulary",
"size",
")",
"."
] | def raw_memory_dim(self):
"""The dimension of memory element (or vocabulary size).
"""
return self._raw_memory_dim | [
"def",
"raw_memory_dim",
"(",
"self",
")",
":",
"return",
"self",
".",
"_raw_memory_dim"
] | https://github.com/santhoshkolloju/Abstractive-Summarization-With-Transfer-Learning/blob/97ff2ae3ba9f2d478e174444c4e0f5349f28c319/texar_repo/texar/modules/memory/memory_network.py#L386-L389 |
|
partho-maple/coding-interview-gym | f9b28916da31935a27900794cfb8b91be3b38b9b | leetcode.com/python/1088_Confusing_Number_II.py | python | Solution.confusingNumberII | (self, N) | return dfs(0, 0, 1) | :type N: int
:rtype: int | :type N: int
:rtype: int | [
":",
"type",
"N",
":",
"int",
":",
"rtype",
":",
"int"
] | def confusingNumberII(self, N):
"""
:type N: int
:rtype: int
"""
validDigits = [0, 1, 6, 8, 9]
m = {0: 0, 1: 1, 6: 9, 8: 8, 9: 6}
def dfs(currentNum, currentNumRotated, digitsInCurrentNum):
res = 0
if currentNum != currentNumRotated:
res += 1
# add one more digit with currentNum, from the list of valid digits rather than adding all 10 digits (from 0 to 9).
for digit in validDigits:
if digit == 0 and currentNum == 0:
continue
nextNum = currentNum*10 + digit
if nextNum <= N:
nextNumRotated = m[digit] * digitsInCurrentNum + currentNumRotated
digitsInNextNum = digitsInCurrentNum * 10
res += dfs(nextNum, nextNumRotated, digitsInNextNum)
return res
return dfs(0, 0, 1) | [
"def",
"confusingNumberII",
"(",
"self",
",",
"N",
")",
":",
"validDigits",
"=",
"[",
"0",
",",
"1",
",",
"6",
",",
"8",
",",
"9",
"]",
"m",
"=",
"{",
"0",
":",
"0",
",",
"1",
":",
"1",
",",
"6",
":",
"9",
",",
"8",
":",
"8",
",",
"9",
":",
"6",
"}",
"def",
"dfs",
"(",
"currentNum",
",",
"currentNumRotated",
",",
"digitsInCurrentNum",
")",
":",
"res",
"=",
"0",
"if",
"currentNum",
"!=",
"currentNumRotated",
":",
"res",
"+=",
"1",
"# add one more digit with currentNum, from the list of valid digits rather than adding all 10 digits (from 0 to 9).",
"for",
"digit",
"in",
"validDigits",
":",
"if",
"digit",
"==",
"0",
"and",
"currentNum",
"==",
"0",
":",
"continue",
"nextNum",
"=",
"currentNum",
"*",
"10",
"+",
"digit",
"if",
"nextNum",
"<=",
"N",
":",
"nextNumRotated",
"=",
"m",
"[",
"digit",
"]",
"*",
"digitsInCurrentNum",
"+",
"currentNumRotated",
"digitsInNextNum",
"=",
"digitsInCurrentNum",
"*",
"10",
"res",
"+=",
"dfs",
"(",
"nextNum",
",",
"nextNumRotated",
",",
"digitsInNextNum",
")",
"return",
"res",
"return",
"dfs",
"(",
"0",
",",
"0",
",",
"1",
")"
] | https://github.com/partho-maple/coding-interview-gym/blob/f9b28916da31935a27900794cfb8b91be3b38b9b/leetcode.com/python/1088_Confusing_Number_II.py#L52-L76 |
|
junsukchoe/ADL | dab2e78163bd96970ec9ae41de62835332dbf4fe | tensorpack/compat/tensor_spec.py | python | TensorSpec.name | (self) | return self._name | Returns the (optionally provided) name of the described tensor. | Returns the (optionally provided) name of the described tensor. | [
"Returns",
"the",
"(",
"optionally",
"provided",
")",
"name",
"of",
"the",
"described",
"tensor",
"."
] | def name(self):
"""Returns the (optionally provided) name of the described tensor."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | https://github.com/junsukchoe/ADL/blob/dab2e78163bd96970ec9ae41de62835332dbf4fe/tensorpack/compat/tensor_spec.py#L71-L73 |
|
google/loaner | 24f9a9e70434e430f1beb4ead87e3675f4b53676 | loaner/deployments/deploy_impl.py | python | _ZipRecursively | (path, archive, root) | return | Recursive path ziping relative to the Chrome Application Bundle.
Args:
path: str, the path to traverse for the zip.
archive: ZipFile, the archive instance to write to.
root: str, the root path to strip off the archived files. | Recursive path ziping relative to the Chrome Application Bundle. | [
"Recursive",
"path",
"ziping",
"relative",
"to",
"the",
"Chrome",
"Application",
"Bundle",
"."
] | def _ZipRecursively(path, archive, root):
"""Recursive path ziping relative to the Chrome Application Bundle.
Args:
path: str, the path to traverse for the zip.
archive: ZipFile, the archive instance to write to.
root: str, the root path to strip off the archived files.
"""
paths = os.listdir(path)
for p in paths:
p = os.path.join(path, p)
if os.path.isdir(p):
_ZipRecursively(p, archive, root)
else:
archive.write(p, os.path.relpath(p, root))
return | [
"def",
"_ZipRecursively",
"(",
"path",
",",
"archive",
",",
"root",
")",
":",
"paths",
"=",
"os",
".",
"listdir",
"(",
"path",
")",
"for",
"p",
"in",
"paths",
":",
"p",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"p",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"p",
")",
":",
"_ZipRecursively",
"(",
"p",
",",
"archive",
",",
"root",
")",
"else",
":",
"archive",
".",
"write",
"(",
"p",
",",
"os",
".",
"path",
".",
"relpath",
"(",
"p",
",",
"root",
")",
")",
"return"
] | https://github.com/google/loaner/blob/24f9a9e70434e430f1beb4ead87e3675f4b53676/loaner/deployments/deploy_impl.py#L209-L224 |
|
oracle/oci-python-sdk | 3c1604e4e212008fb6718e2f68cdb5ef71fd5793 | src/oci/core/compute_client_composite_operations.py | python | ComputeClientCompositeOperations.__init__ | (self, client, work_request_client=None, **kwargs) | Creates a new ComputeClientCompositeOperations object
:param ComputeClient client:
The service client which will be wrapped by this object
:param oci.work_requests.WorkRequestClient work_request_client: (optional)
The work request service client which will be used to wait for work request states. Default is None. | Creates a new ComputeClientCompositeOperations object | [
"Creates",
"a",
"new",
"ComputeClientCompositeOperations",
"object"
] | def __init__(self, client, work_request_client=None, **kwargs):
"""
Creates a new ComputeClientCompositeOperations object
:param ComputeClient client:
The service client which will be wrapped by this object
:param oci.work_requests.WorkRequestClient work_request_client: (optional)
The work request service client which will be used to wait for work request states. Default is None.
"""
self.client = client
self._work_request_client = work_request_client if work_request_client else oci.work_requests.WorkRequestClient(self.client._config, **self.client._kwargs) | [
"def",
"__init__",
"(",
"self",
",",
"client",
",",
"work_request_client",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"client",
"=",
"client",
"self",
".",
"_work_request_client",
"=",
"work_request_client",
"if",
"work_request_client",
"else",
"oci",
".",
"work_requests",
".",
"WorkRequestClient",
"(",
"self",
".",
"client",
".",
"_config",
",",
"*",
"*",
"self",
".",
"client",
".",
"_kwargs",
")"
] | https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/core/compute_client_composite_operations.py#L17-L28 |
||
apache/tvm | 6eb4ed813ebcdcd9558f0906a1870db8302ff1e0 | python/tvm/topi/cuda/scan.py | python | inclusive_scan | (data, axis=-1, output_dtype=None, binop=tvm.tir.generic.add, identity_value=0) | return binop(data, ex_scan) | Do inclusive scan on 1D or multidimensional input.
Parameters
----------
data : tvm.te.Tensor
Input data of any shape.
axis: int, optional
The axis to do scan on. By default, scan is done on the innermost axis.
output_dtype: string, optional
The dtype of the output scan tensor. If not provided, the dtype of the input is used.
binop: function, optional
A binary associative op to use for scan. The function takes two TIR expressions
and produce a new TIR expression. By default it uses tvm.tir.generic.add to compute
prefix sum.
identity_value: int or float
A value for the binary operation which provides the identity property. E.g. if * is
your operator and i is the identity_value then a * i = a for all a in the domain of
your operation.
Returns
-------
output : tvm.te.Tensor
A N-D tensor of the same rank N as the input data. | Do inclusive scan on 1D or multidimensional input. | [
"Do",
"inclusive",
"scan",
"on",
"1D",
"or",
"multidimensional",
"input",
"."
] | def inclusive_scan(data, axis=-1, output_dtype=None, binop=tvm.tir.generic.add, identity_value=0):
"""Do inclusive scan on 1D or multidimensional input.
Parameters
----------
data : tvm.te.Tensor
Input data of any shape.
axis: int, optional
The axis to do scan on. By default, scan is done on the innermost axis.
output_dtype: string, optional
The dtype of the output scan tensor. If not provided, the dtype of the input is used.
binop: function, optional
A binary associative op to use for scan. The function takes two TIR expressions
and produce a new TIR expression. By default it uses tvm.tir.generic.add to compute
prefix sum.
identity_value: int or float
A value for the binary operation which provides the identity property. E.g. if * is
your operator and i is the identity_value then a * i = a for all a in the domain of
your operation.
Returns
-------
output : tvm.te.Tensor
A N-D tensor of the same rank N as the input data.
"""
ex_scan = exclusive_scan(
data, axis, output_dtype=output_dtype, binop=binop, identity_value=identity_value
)
if output_dtype is not None and data.dtype != output_dtype and output_dtype != "":
data = cast(data, output_dtype)
return binop(data, ex_scan) | [
"def",
"inclusive_scan",
"(",
"data",
",",
"axis",
"=",
"-",
"1",
",",
"output_dtype",
"=",
"None",
",",
"binop",
"=",
"tvm",
".",
"tir",
".",
"generic",
".",
"add",
",",
"identity_value",
"=",
"0",
")",
":",
"ex_scan",
"=",
"exclusive_scan",
"(",
"data",
",",
"axis",
",",
"output_dtype",
"=",
"output_dtype",
",",
"binop",
"=",
"binop",
",",
"identity_value",
"=",
"identity_value",
")",
"if",
"output_dtype",
"is",
"not",
"None",
"and",
"data",
".",
"dtype",
"!=",
"output_dtype",
"and",
"output_dtype",
"!=",
"\"\"",
":",
"data",
"=",
"cast",
"(",
"data",
",",
"output_dtype",
")",
"return",
"binop",
"(",
"data",
",",
"ex_scan",
")"
] | https://github.com/apache/tvm/blob/6eb4ed813ebcdcd9558f0906a1870db8302ff1e0/python/tvm/topi/cuda/scan.py#L453-L489 |
|
JiawangBian/SC-SfMLearner-Release | 05fc14ae72dbd142e3d37af05da14eedda51e443 | eval_depth.py | python | mkdir_if_not_exists | (path) | Make a directory if it does not exist.
Args:
path: directory to create | Make a directory if it does not exist.
Args:
path: directory to create | [
"Make",
"a",
"directory",
"if",
"it",
"does",
"not",
"exist",
".",
"Args",
":",
"path",
":",
"directory",
"to",
"create"
] | def mkdir_if_not_exists(path):
"""Make a directory if it does not exist.
Args:
path: directory to create
"""
if not os.path.exists(path):
os.makedirs(path) | [
"def",
"mkdir_if_not_exists",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"makedirs",
"(",
"path",
")"
] | https://github.com/JiawangBian/SC-SfMLearner-Release/blob/05fc14ae72dbd142e3d37af05da14eedda51e443/eval_depth.py#L23-L29 |
||
TengXiaoDai/DistributedCrawling | f5c2439e6ce68dd9b49bde084d76473ff9ed4963 | Lib/site-packages/pip/_vendor/requests/packages/urllib3/util/retry.py | python | Retry.from_int | (cls, retries, redirect=True, default=None) | return new_retries | Backwards-compatibility for the old retries format. | Backwards-compatibility for the old retries format. | [
"Backwards",
"-",
"compatibility",
"for",
"the",
"old",
"retries",
"format",
"."
] | def from_int(cls, retries, redirect=True, default=None):
""" Backwards-compatibility for the old retries format."""
if retries is None:
retries = default if default is not None else cls.DEFAULT
if isinstance(retries, Retry):
return retries
redirect = bool(redirect) and None
new_retries = cls(retries, redirect=redirect)
log.debug("Converted retries value: %r -> %r", retries, new_retries)
return new_retries | [
"def",
"from_int",
"(",
"cls",
",",
"retries",
",",
"redirect",
"=",
"True",
",",
"default",
"=",
"None",
")",
":",
"if",
"retries",
"is",
"None",
":",
"retries",
"=",
"default",
"if",
"default",
"is",
"not",
"None",
"else",
"cls",
".",
"DEFAULT",
"if",
"isinstance",
"(",
"retries",
",",
"Retry",
")",
":",
"return",
"retries",
"redirect",
"=",
"bool",
"(",
"redirect",
")",
"and",
"None",
"new_retries",
"=",
"cls",
"(",
"retries",
",",
"redirect",
"=",
"redirect",
")",
"log",
".",
"debug",
"(",
"\"Converted retries value: %r -> %r\"",
",",
"retries",
",",
"new_retries",
")",
"return",
"new_retries"
] | https://github.com/TengXiaoDai/DistributedCrawling/blob/f5c2439e6ce68dd9b49bde084d76473ff9ed4963/Lib/site-packages/pip/_vendor/requests/packages/urllib3/util/retry.py#L160-L171 |
|
marinho/geraldo | 868ebdce67176d9b6205cddc92476f642c783fff | geraldo/generators/text.py | python | TextGenerator.calculate_size | (self, size) | return calculate_size(size) | Uses the function 'calculate_size' to calculate a size | Uses the function 'calculate_size' to calculate a size | [
"Uses",
"the",
"function",
"calculate_size",
"to",
"calculate",
"a",
"size"
] | def calculate_size(self, size):
"""Uses the function 'calculate_size' to calculate a size"""
if isinstance(size, basestring):
if size.endswith('*cols') or size.endswith('*col'):
return int(size.split('*')[0]) * self.character_width
elif size.endswith('*rows') or size.endswith('*row'):
return int(size.split('*')[0]) * self.row_height
return calculate_size(size) | [
"def",
"calculate_size",
"(",
"self",
",",
"size",
")",
":",
"if",
"isinstance",
"(",
"size",
",",
"basestring",
")",
":",
"if",
"size",
".",
"endswith",
"(",
"'*cols'",
")",
"or",
"size",
".",
"endswith",
"(",
"'*col'",
")",
":",
"return",
"int",
"(",
"size",
".",
"split",
"(",
"'*'",
")",
"[",
"0",
"]",
")",
"*",
"self",
".",
"character_width",
"elif",
"size",
".",
"endswith",
"(",
"'*rows'",
")",
"or",
"size",
".",
"endswith",
"(",
"'*row'",
")",
":",
"return",
"int",
"(",
"size",
".",
"split",
"(",
"'*'",
")",
"[",
"0",
"]",
")",
"*",
"self",
".",
"row_height",
"return",
"calculate_size",
"(",
"size",
")"
] | https://github.com/marinho/geraldo/blob/868ebdce67176d9b6205cddc92476f642c783fff/geraldo/generators/text.py#L133-L141 |
|
IronLanguages/ironpython2 | 51fdedeeda15727717fb8268a805f71b06c0b9f1 | Src/StdLib/Lib/cgi.py | python | test | (environ=os.environ) | Robust test CGI script, usable as main program.
Write minimal HTTP headers and dump all information provided to
the script in HTML form. | Robust test CGI script, usable as main program. | [
"Robust",
"test",
"CGI",
"script",
"usable",
"as",
"main",
"program",
"."
] | def test(environ=os.environ):
"""Robust test CGI script, usable as main program.
Write minimal HTTP headers and dump all information provided to
the script in HTML form.
"""
print "Content-type: text/html"
print
sys.stderr = sys.stdout
try:
form = FieldStorage() # Replace with other classes to test those
print_directory()
print_arguments()
print_form(form)
print_environ(environ)
print_environ_usage()
def f():
exec "testing print_exception() -- <I>italics?</I>"
def g(f=f):
f()
print "<H3>What follows is a test, not an actual exception:</H3>"
g()
except:
print_exception()
print "<H1>Second try with a small maxlen...</H1>"
global maxlen
maxlen = 50
try:
form = FieldStorage() # Replace with other classes to test those
print_directory()
print_arguments()
print_form(form)
print_environ(environ)
except:
print_exception() | [
"def",
"test",
"(",
"environ",
"=",
"os",
".",
"environ",
")",
":",
"print",
"\"Content-type: text/html\"",
"print",
"sys",
".",
"stderr",
"=",
"sys",
".",
"stdout",
"try",
":",
"form",
"=",
"FieldStorage",
"(",
")",
"# Replace with other classes to test those",
"print_directory",
"(",
")",
"print_arguments",
"(",
")",
"print_form",
"(",
"form",
")",
"print_environ",
"(",
"environ",
")",
"print_environ_usage",
"(",
")",
"def",
"f",
"(",
")",
":",
"exec",
"\"testing print_exception() -- <I>italics?</I>\"",
"def",
"g",
"(",
"f",
"=",
"f",
")",
":",
"f",
"(",
")",
"print",
"\"<H3>What follows is a test, not an actual exception:</H3>\"",
"g",
"(",
")",
"except",
":",
"print_exception",
"(",
")",
"print",
"\"<H1>Second try with a small maxlen...</H1>\"",
"global",
"maxlen",
"maxlen",
"=",
"50",
"try",
":",
"form",
"=",
"FieldStorage",
"(",
")",
"# Replace with other classes to test those",
"print_directory",
"(",
")",
"print_arguments",
"(",
")",
"print_form",
"(",
"form",
")",
"print_environ",
"(",
"environ",
")",
"except",
":",
"print_exception",
"(",
")"
] | https://github.com/IronLanguages/ironpython2/blob/51fdedeeda15727717fb8268a805f71b06c0b9f1/Src/StdLib/Lib/cgi.py#L915-L952 |
||
glumpy/glumpy | 46a7635c08d3a200478397edbe0371a6c59cd9d7 | glumpy/app/clock.py | python | tick | (poll=False) | return _default.tick(poll) | Signify that one frame has passed on the default clock.
This will call any scheduled functions that have elapsed.
:Parameters:
`poll` : bool
If True, the function will call any scheduled functions
but will not sleep or busy-wait for any reason. Recommended
for advanced applications managing their own sleep timers
only.
:rtype: float
:return: The number of seconds since the last "tick", or 0 if this was the
first frame. | Signify that one frame has passed on the default clock. | [
"Signify",
"that",
"one",
"frame",
"has",
"passed",
"on",
"the",
"default",
"clock",
"."
] | def tick(poll=False):
'''Signify that one frame has passed on the default clock.
This will call any scheduled functions that have elapsed.
:Parameters:
`poll` : bool
If True, the function will call any scheduled functions
but will not sleep or busy-wait for any reason. Recommended
for advanced applications managing their own sleep timers
only.
:rtype: float
:return: The number of seconds since the last "tick", or 0 if this was the
first frame.
'''
return _default.tick(poll) | [
"def",
"tick",
"(",
"poll",
"=",
"False",
")",
":",
"return",
"_default",
".",
"tick",
"(",
"poll",
")"
] | https://github.com/glumpy/glumpy/blob/46a7635c08d3a200478397edbe0371a6c59cd9d7/glumpy/app/clock.py#L705-L722 |
|
fsspec/s3fs | dfa1cd28467541cfafb25056a0402a49bacd219a | s3fs/core.py | python | S3FileSystem._get_delegated_s3pars | (self, exp=3600) | Get temporary credentials from STS, appropriate for sending across a
network. Only relevant where the key/secret were explicitly provided.
Parameters
----------
exp : int
Time in seconds that credentials are good for
Returns
-------
dict of parameters | Get temporary credentials from STS, appropriate for sending across a
network. Only relevant where the key/secret were explicitly provided. | [
"Get",
"temporary",
"credentials",
"from",
"STS",
"appropriate",
"for",
"sending",
"across",
"a",
"network",
".",
"Only",
"relevant",
"where",
"the",
"key",
"/",
"secret",
"were",
"explicitly",
"provided",
"."
] | async def _get_delegated_s3pars(self, exp=3600):
"""Get temporary credentials from STS, appropriate for sending across a
network. Only relevant where the key/secret were explicitly provided.
Parameters
----------
exp : int
Time in seconds that credentials are good for
Returns
-------
dict of parameters
"""
if self.anon:
return {"anon": True}
if self.token: # already has temporary cred
return {
"key": self.key,
"secret": self.secret,
"token": self.token,
"anon": False,
}
if self.key is None or self.secret is None: # automatic credentials
return {"anon": False}
async with self.session.create_client("sts") as sts:
cred = sts.get_session_token(DurationSeconds=exp)["Credentials"]
return {
"key": cred["AccessKeyId"],
"secret": cred["SecretAccessKey"],
"token": cred["SessionToken"],
"anon": False,
} | [
"async",
"def",
"_get_delegated_s3pars",
"(",
"self",
",",
"exp",
"=",
"3600",
")",
":",
"if",
"self",
".",
"anon",
":",
"return",
"{",
"\"anon\"",
":",
"True",
"}",
"if",
"self",
".",
"token",
":",
"# already has temporary cred",
"return",
"{",
"\"key\"",
":",
"self",
".",
"key",
",",
"\"secret\"",
":",
"self",
".",
"secret",
",",
"\"token\"",
":",
"self",
".",
"token",
",",
"\"anon\"",
":",
"False",
",",
"}",
"if",
"self",
".",
"key",
"is",
"None",
"or",
"self",
".",
"secret",
"is",
"None",
":",
"# automatic credentials",
"return",
"{",
"\"anon\"",
":",
"False",
"}",
"async",
"with",
"self",
".",
"session",
".",
"create_client",
"(",
"\"sts\"",
")",
"as",
"sts",
":",
"cred",
"=",
"sts",
".",
"get_session_token",
"(",
"DurationSeconds",
"=",
"exp",
")",
"[",
"\"Credentials\"",
"]",
"return",
"{",
"\"key\"",
":",
"cred",
"[",
"\"AccessKeyId\"",
"]",
",",
"\"secret\"",
":",
"cred",
"[",
"\"SecretAccessKey\"",
"]",
",",
"\"token\"",
":",
"cred",
"[",
"\"SessionToken\"",
"]",
",",
"\"anon\"",
":",
"False",
",",
"}"
] | https://github.com/fsspec/s3fs/blob/dfa1cd28467541cfafb25056a0402a49bacd219a/s3fs/core.py#L449-L480 |
||
makerdao/pymaker | 9245b3e22bcb257004d54337df6c2b0c9cbe42c8 | pymaker/auctions.py | python | Clipper.take | (self, id: int, amt: Wad, max: Ray, who: Address = None, data=b'') | return Transact(self, self.web3, self.abi, self.address, self._contract, 'take',
[id, amt.value, max.value, who.address, data]) | Buy amount of collateral from auction indexed by id.
Args:
id: Auction id
amt: Upper limit on amount of collateral to buy
max: Maximum acceptable price (DAI / collateral)
who: Receiver of collateral and external call address
data: Data to pass in external call; if length 0, no call is done | Buy amount of collateral from auction indexed by id.
Args:
id: Auction id
amt: Upper limit on amount of collateral to buy
max: Maximum acceptable price (DAI / collateral)
who: Receiver of collateral and external call address
data: Data to pass in external call; if length 0, no call is done | [
"Buy",
"amount",
"of",
"collateral",
"from",
"auction",
"indexed",
"by",
"id",
".",
"Args",
":",
"id",
":",
"Auction",
"id",
"amt",
":",
"Upper",
"limit",
"on",
"amount",
"of",
"collateral",
"to",
"buy",
"max",
":",
"Maximum",
"acceptable",
"price",
"(",
"DAI",
"/",
"collateral",
")",
"who",
":",
"Receiver",
"of",
"collateral",
"and",
"external",
"call",
"address",
"data",
":",
"Data",
"to",
"pass",
"in",
"external",
"call",
";",
"if",
"length",
"0",
"no",
"call",
"is",
"done"
] | def take(self, id: int, amt: Wad, max: Ray, who: Address = None, data=b'') -> Transact:
"""Buy amount of collateral from auction indexed by id.
Args:
id: Auction id
amt: Upper limit on amount of collateral to buy
max: Maximum acceptable price (DAI / collateral)
who: Receiver of collateral and external call address
data: Data to pass in external call; if length 0, no call is done
"""
assert isinstance(id, int)
assert isinstance(amt, Wad)
assert isinstance(max, Ray)
if who:
assert isinstance(who, Address)
else:
who = Address(self.web3.eth.defaultAccount)
return Transact(self, self.web3, self.abi, self.address, self._contract, 'take',
[id, amt.value, max.value, who.address, data]) | [
"def",
"take",
"(",
"self",
",",
"id",
":",
"int",
",",
"amt",
":",
"Wad",
",",
"max",
":",
"Ray",
",",
"who",
":",
"Address",
"=",
"None",
",",
"data",
"=",
"b''",
")",
"->",
"Transact",
":",
"assert",
"isinstance",
"(",
"id",
",",
"int",
")",
"assert",
"isinstance",
"(",
"amt",
",",
"Wad",
")",
"assert",
"isinstance",
"(",
"max",
",",
"Ray",
")",
"if",
"who",
":",
"assert",
"isinstance",
"(",
"who",
",",
"Address",
")",
"else",
":",
"who",
"=",
"Address",
"(",
"self",
".",
"web3",
".",
"eth",
".",
"defaultAccount",
")",
"return",
"Transact",
"(",
"self",
",",
"self",
".",
"web3",
",",
"self",
".",
"abi",
",",
"self",
".",
"address",
",",
"self",
".",
"_contract",
",",
"'take'",
",",
"[",
"id",
",",
"amt",
".",
"value",
",",
"max",
".",
"value",
",",
"who",
".",
"address",
",",
"data",
"]",
")"
] | https://github.com/makerdao/pymaker/blob/9245b3e22bcb257004d54337df6c2b0c9cbe42c8/pymaker/auctions.py#L848-L867 |
|
bendmorris/static-python | 2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473 | Lib/datetime.py | python | date.__hash__ | (self) | return hash(self._getstate()) | Hash. | Hash. | [
"Hash",
"."
] | def __hash__(self):
"Hash."
return hash(self._getstate()) | [
"def",
"__hash__",
"(",
"self",
")",
":",
"return",
"hash",
"(",
"self",
".",
"_getstate",
"(",
")",
")"
] | https://github.com/bendmorris/static-python/blob/2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473/Lib/datetime.py#L823-L825 |
|
withdk/badusb2-mitm-poc | db2bfdb1dc9ad371aa665b292183c45577adfbaa | GoodFETMAXUSB.py | python | GoodFETMAXUSB.ctl_write_nd | (self,request) | return 0 | Control Write with no data stage. Assumes PERADDR is set
and the SUDFIFO contains the 8 setup bytes. Returns with
result code = HRSLT[3:0] (HRSL register). If there is an
error, the 4MSBits of the returned value indicate the stage 1
or 2. | Control Write with no data stage. Assumes PERADDR is set
and the SUDFIFO contains the 8 setup bytes. Returns with
result code = HRSLT[3:0] (HRSL register). If there is an
error, the 4MSBits of the returned value indicate the stage 1
or 2. | [
"Control",
"Write",
"with",
"no",
"data",
"stage",
".",
"Assumes",
"PERADDR",
"is",
"set",
"and",
"the",
"SUDFIFO",
"contains",
"the",
"8",
"setup",
"bytes",
".",
"Returns",
"with",
"result",
"code",
"=",
"HRSLT",
"[",
"3",
":",
"0",
"]",
"(",
"HRSL",
"register",
")",
".",
"If",
"there",
"is",
"an",
"error",
"the",
"4MSBits",
"of",
"the",
"returned",
"value",
"indicate",
"the",
"stage",
"1",
"or",
"2",
"."
] | def ctl_write_nd(self,request):
"""Control Write with no data stage. Assumes PERADDR is set
and the SUDFIFO contains the 8 setup bytes. Returns with
result code = HRSLT[3:0] (HRSL register). If there is an
error, the 4MSBits of the returned value indicate the stage 1
or 2."""
# 1. Send the SETUP token and 8 setup bytes.
# Should ACK immediately.
self.writebytes(rSUDFIFO,request);
resultcode=self.send_packet(tokSETUP,0); #SETUP packet to EP0.
if resultcode: return resultcode;
# 2. No data stage, so the last operation is to send an IN
# token to the peripheral as the STATUS (handhsake) stage of
# this control transfer. We should get NAK or the DATA1 PID.
# When we get back to the DATA1 PID the 3421 automatically
# sends the closing NAK.
resultcode=self.send_packet(tokINHS,0); #Function takes care of retries.
if resultcode: return resultcode;
return 0; | [
"def",
"ctl_write_nd",
"(",
"self",
",",
"request",
")",
":",
"# 1. Send the SETUP token and 8 setup bytes. ",
"# Should ACK immediately.",
"self",
".",
"writebytes",
"(",
"rSUDFIFO",
",",
"request",
")",
"resultcode",
"=",
"self",
".",
"send_packet",
"(",
"tokSETUP",
",",
"0",
")",
"#SETUP packet to EP0.",
"if",
"resultcode",
":",
"return",
"resultcode",
"# 2. No data stage, so the last operation is to send an IN",
"# token to the peripheral as the STATUS (handhsake) stage of",
"# this control transfer. We should get NAK or the DATA1 PID.",
"# When we get back to the DATA1 PID the 3421 automatically",
"# sends the closing NAK.",
"resultcode",
"=",
"self",
".",
"send_packet",
"(",
"tokINHS",
",",
"0",
")",
"#Function takes care of retries.",
"if",
"resultcode",
":",
"return",
"resultcode",
"return",
"0"
] | https://github.com/withdk/badusb2-mitm-poc/blob/db2bfdb1dc9ad371aa665b292183c45577adfbaa/GoodFETMAXUSB.py#L376-L397 |
|
yanpanlau/DDPG-Keras-Torcs | 455fadee1016ef15ef08817d98ec376d7e34b500 | snakeoil3_gym.py | python | destringify | (s) | u'''makes a string into a value or a list of strings into a list of
values (if possible) | u'''makes a string into a value or a list of strings into a list of
values (if possible) | [
"u",
"makes",
"a",
"string",
"into",
"a",
"value",
"or",
"a",
"list",
"of",
"strings",
"into",
"a",
"list",
"of",
"values",
"(",
"if",
"possible",
")"
] | def destringify(s):
u'''makes a string into a value or a list of strings into a list of
values (if possible)'''
if not s: return s
if type(s) is unicode:
try:
return float(s)
except ValueError:
print u"Could not find a value in %s" % s
return s
elif type(s) is list:
if len(s) < 2:
return destringify(s[0])
else:
return [destringify(i) for i in s] | [
"def",
"destringify",
"(",
"s",
")",
":",
"if",
"not",
"s",
":",
"return",
"s",
"if",
"type",
"(",
"s",
")",
"is",
"unicode",
":",
"try",
":",
"return",
"float",
"(",
"s",
")",
"except",
"ValueError",
":",
"print",
"u\"Could not find a value in %s\"",
"%",
"s",
"return",
"s",
"elif",
"type",
"(",
"s",
")",
"is",
"list",
":",
"if",
"len",
"(",
"s",
")",
"<",
"2",
":",
"return",
"destringify",
"(",
"s",
"[",
"0",
"]",
")",
"else",
":",
"return",
"[",
"destringify",
"(",
"i",
")",
"for",
"i",
"in",
"s",
"]"
] | https://github.com/yanpanlau/DDPG-Keras-Torcs/blob/455fadee1016ef15ef08817d98ec376d7e34b500/snakeoil3_gym.py#L515-L529 |
||
makerbot/ReplicatorG | d6f2b07785a5a5f1e172fb87cb4303b17c575d5d | skein_engines/skeinforge-47/fabmetheus_utilities/svg_reader.py | python | getTricomplexmatrix | (transformWords) | return tricomplex | Get matrixSVG by transformWords. | Get matrixSVG by transformWords. | [
"Get",
"matrixSVG",
"by",
"transformWords",
"."
] | def getTricomplexmatrix(transformWords):
"Get matrixSVG by transformWords."
tricomplex = [euclidean.getComplexByWords(transformWords)]
tricomplex.append(euclidean.getComplexByWords(transformWords, 2))
tricomplex.append(euclidean.getComplexByWords(transformWords, 4))
return tricomplex | [
"def",
"getTricomplexmatrix",
"(",
"transformWords",
")",
":",
"tricomplex",
"=",
"[",
"euclidean",
".",
"getComplexByWords",
"(",
"transformWords",
")",
"]",
"tricomplex",
".",
"append",
"(",
"euclidean",
".",
"getComplexByWords",
"(",
"transformWords",
",",
"2",
")",
")",
"tricomplex",
".",
"append",
"(",
"euclidean",
".",
"getComplexByWords",
"(",
"transformWords",
",",
"4",
")",
")",
"return",
"tricomplex"
] | https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-47/fabmetheus_utilities/svg_reader.py#L280-L285 |
|
hatRiot/zarp | 2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad | src/lib/scapy/config.py | python | CacheInstance.iteritems | (self) | return ((k,v) for (k,v) in dict.iteritems(self) if t0-self._timetable[k] < self.timeout) | [] | def iteritems(self):
if self.timeout is None:
return dict.iteritems(self)
t0=time.time()
return ((k,v) for (k,v) in dict.iteritems(self) if t0-self._timetable[k] < self.timeout) | [
"def",
"iteritems",
"(",
"self",
")",
":",
"if",
"self",
".",
"timeout",
"is",
"None",
":",
"return",
"dict",
".",
"iteritems",
"(",
"self",
")",
"t0",
"=",
"time",
".",
"time",
"(",
")",
"return",
"(",
"(",
"k",
",",
"v",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"dict",
".",
"iteritems",
"(",
"self",
")",
"if",
"t0",
"-",
"self",
".",
"_timetable",
"[",
"k",
"]",
"<",
"self",
".",
"timeout",
")"
] | https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/lib/scapy/config.py#L187-L191 |
|||
polakowo/vectorbt | 6638735c131655760474d72b9f045d1dbdbd8fe9 | apps/candlestick-patterns/app.py | python | update_metric_stats | (window_width, stats_json, metric) | return dict(
data=[
go.Box(
x=stats_dict['rand'][metric],
quartilemethod="linear",
jitter=0.3,
pointpos=1.8,
boxpoints='all',
boxmean='sd',
hoveron="points",
hovertemplate='%{x}<br>Random',
name='',
marker=dict(
color=color_schema['blue'],
opacity=0.5,
size=8,
),
),
go.Box(
x=stats_dict['hold'][metric],
quartilemethod="linear",
boxpoints="all",
jitter=0,
pointpos=1.8,
hoveron="points",
hovertemplate='%{x}<br>Buy & Hold',
fillcolor="rgba(0,0,0,0)",
line=dict(color="rgba(0,0,0,0)"),
name='',
marker=dict(
color=color_schema['orange'],
size=8,
),
),
go.Box(
x=stats_dict['main'][metric],
quartilemethod="linear",
boxpoints="all",
jitter=0,
pointpos=1.8,
hoveron="points",
hovertemplate='%{x}<br>Strategy',
fillcolor="rgba(0,0,0,0)",
line=dict(color="rgba(0,0,0,0)"),
name='',
marker=dict(
color=color_schema['green'],
size=8,
),
),
],
layout=merge_dicts(
default_layout,
dict(
height=max(350, height),
showlegend=False,
margin=dict(l=60, r=20, t=40, b=20),
hovermode="closest",
xaxis=dict(
gridcolor=gridcolor,
title=metric,
side='top'
),
yaxis=dict(
gridcolor=gridcolor
),
)
)
) | Once a new metric has been selected, plot its distribution. | Once a new metric has been selected, plot its distribution. | [
"Once",
"a",
"new",
"metric",
"has",
"been",
"selected",
"plot",
"its",
"distribution",
"."
] | def update_metric_stats(window_width, stats_json, metric):
"""Once a new metric has been selected, plot its distribution."""
stats_dict = json.loads(stats_json)
height = int(9 / 21 * 2 / 3 * 2 / 3 * window_width)
return dict(
data=[
go.Box(
x=stats_dict['rand'][metric],
quartilemethod="linear",
jitter=0.3,
pointpos=1.8,
boxpoints='all',
boxmean='sd',
hoveron="points",
hovertemplate='%{x}<br>Random',
name='',
marker=dict(
color=color_schema['blue'],
opacity=0.5,
size=8,
),
),
go.Box(
x=stats_dict['hold'][metric],
quartilemethod="linear",
boxpoints="all",
jitter=0,
pointpos=1.8,
hoveron="points",
hovertemplate='%{x}<br>Buy & Hold',
fillcolor="rgba(0,0,0,0)",
line=dict(color="rgba(0,0,0,0)"),
name='',
marker=dict(
color=color_schema['orange'],
size=8,
),
),
go.Box(
x=stats_dict['main'][metric],
quartilemethod="linear",
boxpoints="all",
jitter=0,
pointpos=1.8,
hoveron="points",
hovertemplate='%{x}<br>Strategy',
fillcolor="rgba(0,0,0,0)",
line=dict(color="rgba(0,0,0,0)"),
name='',
marker=dict(
color=color_schema['green'],
size=8,
),
),
],
layout=merge_dicts(
default_layout,
dict(
height=max(350, height),
showlegend=False,
margin=dict(l=60, r=20, t=40, b=20),
hovermode="closest",
xaxis=dict(
gridcolor=gridcolor,
title=metric,
side='top'
),
yaxis=dict(
gridcolor=gridcolor
),
)
)
) | [
"def",
"update_metric_stats",
"(",
"window_width",
",",
"stats_json",
",",
"metric",
")",
":",
"stats_dict",
"=",
"json",
".",
"loads",
"(",
"stats_json",
")",
"height",
"=",
"int",
"(",
"9",
"/",
"21",
"*",
"2",
"/",
"3",
"*",
"2",
"/",
"3",
"*",
"window_width",
")",
"return",
"dict",
"(",
"data",
"=",
"[",
"go",
".",
"Box",
"(",
"x",
"=",
"stats_dict",
"[",
"'rand'",
"]",
"[",
"metric",
"]",
",",
"quartilemethod",
"=",
"\"linear\"",
",",
"jitter",
"=",
"0.3",
",",
"pointpos",
"=",
"1.8",
",",
"boxpoints",
"=",
"'all'",
",",
"boxmean",
"=",
"'sd'",
",",
"hoveron",
"=",
"\"points\"",
",",
"hovertemplate",
"=",
"'%{x}<br>Random'",
",",
"name",
"=",
"''",
",",
"marker",
"=",
"dict",
"(",
"color",
"=",
"color_schema",
"[",
"'blue'",
"]",
",",
"opacity",
"=",
"0.5",
",",
"size",
"=",
"8",
",",
")",
",",
")",
",",
"go",
".",
"Box",
"(",
"x",
"=",
"stats_dict",
"[",
"'hold'",
"]",
"[",
"metric",
"]",
",",
"quartilemethod",
"=",
"\"linear\"",
",",
"boxpoints",
"=",
"\"all\"",
",",
"jitter",
"=",
"0",
",",
"pointpos",
"=",
"1.8",
",",
"hoveron",
"=",
"\"points\"",
",",
"hovertemplate",
"=",
"'%{x}<br>Buy & Hold'",
",",
"fillcolor",
"=",
"\"rgba(0,0,0,0)\"",
",",
"line",
"=",
"dict",
"(",
"color",
"=",
"\"rgba(0,0,0,0)\"",
")",
",",
"name",
"=",
"''",
",",
"marker",
"=",
"dict",
"(",
"color",
"=",
"color_schema",
"[",
"'orange'",
"]",
",",
"size",
"=",
"8",
",",
")",
",",
")",
",",
"go",
".",
"Box",
"(",
"x",
"=",
"stats_dict",
"[",
"'main'",
"]",
"[",
"metric",
"]",
",",
"quartilemethod",
"=",
"\"linear\"",
",",
"boxpoints",
"=",
"\"all\"",
",",
"jitter",
"=",
"0",
",",
"pointpos",
"=",
"1.8",
",",
"hoveron",
"=",
"\"points\"",
",",
"hovertemplate",
"=",
"'%{x}<br>Strategy'",
",",
"fillcolor",
"=",
"\"rgba(0,0,0,0)\"",
",",
"line",
"=",
"dict",
"(",
"color",
"=",
"\"rgba(0,0,0,0)\"",
")",
",",
"name",
"=",
"''",
",",
"marker",
"=",
"dict",
"(",
"color",
"=",
"color_schema",
"[",
"'green'",
"]",
",",
"size",
"=",
"8",
",",
")",
",",
")",
",",
"]",
",",
"layout",
"=",
"merge_dicts",
"(",
"default_layout",
",",
"dict",
"(",
"height",
"=",
"max",
"(",
"350",
",",
"height",
")",
",",
"showlegend",
"=",
"False",
",",
"margin",
"=",
"dict",
"(",
"l",
"=",
"60",
",",
"r",
"=",
"20",
",",
"t",
"=",
"40",
",",
"b",
"=",
"20",
")",
",",
"hovermode",
"=",
"\"closest\"",
",",
"xaxis",
"=",
"dict",
"(",
"gridcolor",
"=",
"gridcolor",
",",
"title",
"=",
"metric",
",",
"side",
"=",
"'top'",
")",
",",
"yaxis",
"=",
"dict",
"(",
"gridcolor",
"=",
"gridcolor",
")",
",",
")",
")",
")"
] | https://github.com/polakowo/vectorbt/blob/6638735c131655760474d72b9f045d1dbdbd8fe9/apps/candlestick-patterns/app.py#L1466-L1538 |
|
krintoxi/NoobSec-Toolkit | 38738541cbc03cedb9a3b3ed13b629f781ad64f6 | NoobSecToolkit - MAC OSX/scripts/sshbackdoors/backdoors/shell/pupy/pupy/pupylib/PupyCompleter.py | python | PupyModCompleter.get_last_text | (self, text, line, begidx, endidx) | [] | def get_last_text(self, text, line, begidx, endidx):
try:
return line[0:begidx-1].rsplit(' ',1)[1].strip()
except Exception:
return None | [
"def",
"get_last_text",
"(",
"self",
",",
"text",
",",
"line",
",",
"begidx",
",",
"endidx",
")",
":",
"try",
":",
"return",
"line",
"[",
"0",
":",
"begidx",
"-",
"1",
"]",
".",
"rsplit",
"(",
"' '",
",",
"1",
")",
"[",
"1",
"]",
".",
"strip",
"(",
")",
"except",
"Exception",
":",
"return",
"None"
] | https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/scripts/sshbackdoors/backdoors/shell/pupy/pupy/pupylib/PupyCompleter.py#L146-L150 |
||||
twilio/twilio-python | 6e1e811ea57a1edfadd5161ace87397c563f6915 | twilio/rest/preview/understand/assistant/assistant_initiation_actions.py | python | AssistantInitiationActionsInstance.update | (self, initiation_actions=values.unset) | return self._proxy.update(initiation_actions=initiation_actions, ) | Update the AssistantInitiationActionsInstance
:param dict initiation_actions: The initiation_actions
:returns: The updated AssistantInitiationActionsInstance
:rtype: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsInstance | Update the AssistantInitiationActionsInstance | [
"Update",
"the",
"AssistantInitiationActionsInstance"
] | def update(self, initiation_actions=values.unset):
"""
Update the AssistantInitiationActionsInstance
:param dict initiation_actions: The initiation_actions
:returns: The updated AssistantInitiationActionsInstance
:rtype: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsInstance
"""
return self._proxy.update(initiation_actions=initiation_actions, ) | [
"def",
"update",
"(",
"self",
",",
"initiation_actions",
"=",
"values",
".",
"unset",
")",
":",
"return",
"self",
".",
"_proxy",
".",
"update",
"(",
"initiation_actions",
"=",
"initiation_actions",
",",
")"
] | https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/preview/understand/assistant/assistant_initiation_actions.py#L266-L275 |