nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
Wangler2333/tcp_udp_web_tools-pyqt5
791df73791e3e6f61643f10613c84810cdf2ffc2
tcp_udp_web_tools_all_in_one.py
python
Ui_TCP.click_clear
(self)
pushbutton_clear控件点击触发的槽 :return: None
pushbutton_clear控件点击触发的槽 :return: None
[ "pushbutton_clear控件点击触发的槽", ":", "return", ":", "None" ]
def click_clear(self): """ pushbutton_clear控件点击触发的槽 :return: None """ self.textBrowser_recv.clear()
[ "def", "click_clear", "(", "self", ")", ":", "self", ".", "textBrowser_recv", ".", "clear", "(", ")" ]
https://github.com/Wangler2333/tcp_udp_web_tools-pyqt5/blob/791df73791e3e6f61643f10613c84810cdf2ffc2/tcp_udp_web_tools_all_in_one.py#L320-L325
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/weakref.py
python
finalize.peek
(self)
If alive then return (obj, func, args, kwargs); otherwise return None
If alive then return (obj, func, args, kwargs); otherwise return None
[ "If", "alive", "then", "return", "(", "obj", "func", "args", "kwargs", ")", ";", "otherwise", "return", "None" ]
def peek(self): """If alive then return (obj, func, args, kwargs); otherwise return None""" info = self._registry.get(self) obj = info and info.weakref() if obj is not None: return (obj, info.func, info.args, info.kwargs or {})
[ "def", "peek", "(", "self", ")", ":", "info", "=", "self", ".", "_registry", ".", "get", "(", "self", ")", "obj", "=", "info", "and", "info", ".", "weakref", "(", ")", "if", "obj", "is", "not", "None", ":", "return", "(", "obj", ",", "info", "....
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/weakref.py#L529-L535
martinRenou/ipycanvas
53348e3f63153fc80459c9f1e76ce73dc75dcd49
ipycanvas/canvas.py
python
Canvas.ellipse
(self, x, y, radius_x, radius_y, rotation, start_angle, end_angle, anticlockwise=False)
Add an ellipse centered at ``(x, y)`` with the radii ``radius_x`` and ``radius_y`` to the current path. The path starts at ``start_angle`` and ends at ``end_angle``, and travels in the direction given by ``anticlockwise`` (defaulting to clockwise: ``False``).
Add an ellipse centered at ``(x, y)`` with the radii ``radius_x`` and ``radius_y`` to the current path.
[ "Add", "an", "ellipse", "centered", "at", "(", "x", "y", ")", "with", "the", "radii", "radius_x", "and", "radius_y", "to", "the", "current", "path", "." ]
def ellipse(self, x, y, radius_x, radius_y, rotation, start_angle, end_angle, anticlockwise=False): """Add an ellipse centered at ``(x, y)`` with the radii ``radius_x`` and ``radius_y`` to the current path. The path starts at ``start_angle`` and ends at ``end_angle``, and travels in the direction given by ``anticlockwise`` (defaulting to clockwise: ``False``). """ self._send_canvas_command(COMMANDS['ellipse'], [x, y, radius_x, radius_y, rotation, start_angle, end_angle, anticlockwise])
[ "def", "ellipse", "(", "self", ",", "x", ",", "y", ",", "radius_x", ",", "radius_y", ",", "rotation", ",", "start_angle", ",", "end_angle", ",", "anticlockwise", "=", "False", ")", ":", "self", ".", "_send_canvas_command", "(", "COMMANDS", "[", "'ellipse'"...
https://github.com/martinRenou/ipycanvas/blob/53348e3f63153fc80459c9f1e76ce73dc75dcd49/ipycanvas/canvas.py#L973-L979
HiKapok/X-Detector
1b19e15709635e007494648c4fb519b703a29d84
light_head_rfcn_train.py
python
parse_comma_list
(args)
return [float(s.strip()) for s in args.split(',')]
[]
def parse_comma_list(args): return [float(s.strip()) for s in args.split(',')]
[ "def", "parse_comma_list", "(", "args", ")", ":", "return", "[", "float", "(", "s", ".", "strip", "(", ")", ")", "for", "s", "in", "args", ".", "split", "(", "','", ")", "]" ]
https://github.com/HiKapok/X-Detector/blob/1b19e15709635e007494648c4fb519b703a29d84/light_head_rfcn_train.py#L453-L454
and3rson/clay
c271cecf6b6ea6465abcdd2444171b1a565a60a3
clay/clipboard.py
python
copy
(text)
return False
Copy text to clipboard. Return True on success.
Copy text to clipboard.
[ "Copy", "text", "to", "clipboard", "." ]
def copy(text): """ Copy text to clipboard. Return True on success. """ for cmd in COMMANDS: proc = Popen(cmd, stdin=PIPE) proc.communicate(text.encode('utf-8')) if proc.returncode == 0: return True notification_area.notify( 'Failed to copy text to clipboard. ' 'Please install "xclip" or "xsel".' ) return False
[ "def", "copy", "(", "text", ")", ":", "for", "cmd", "in", "COMMANDS", ":", "proc", "=", "Popen", "(", "cmd", ",", "stdin", "=", "PIPE", ")", "proc", ".", "communicate", "(", "text", ".", "encode", "(", "'utf-8'", ")", ")", "if", "proc", ".", "ret...
https://github.com/and3rson/clay/blob/c271cecf6b6ea6465abcdd2444171b1a565a60a3/clay/clipboard.py#L15-L31
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/tasmota/config_flow.py
python
FlowHandler.async_step_confirm
( self, user_input: dict[str, Any] | None = None )
return self.async_show_form(step_id="confirm")
Confirm the setup.
Confirm the setup.
[ "Confirm", "the", "setup", "." ]
async def async_step_confirm( self, user_input: dict[str, Any] | None = None ) -> FlowResult: """Confirm the setup.""" data = {CONF_DISCOVERY_PREFIX: self._prefix} if user_input is not None: return self.async_create_entry(title="Tasmota", data=data) return self.async_show_form(step_id="confirm")
[ "async", "def", "async_step_confirm", "(", "self", ",", "user_input", ":", "dict", "[", "str", ",", "Any", "]", "|", "None", "=", "None", ")", "->", "FlowResult", ":", "data", "=", "{", "CONF_DISCOVERY_PREFIX", ":", "self", ".", "_prefix", "}", "if", "...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/tasmota/config_flow.py#L85-L95
jkehler/awslambda-psycopg2
c7b1b2f6382bbe5893d95c4e7f4b5ffdf05ab3b4
with_ssl_support/psycopg2/extras.py
python
register_uuid
(oids=None, conn_or_curs=None)
return _ext.UUID
Create the UUID type and an uuid.UUID adapter. :param oids: oid for the PostgreSQL :sql:`uuid` type, or 2-items sequence with oids of the type and the array. If not specified, use PostgreSQL standard oids. :param conn_or_curs: where to register the typecaster. If not specified, register it globally.
Create the UUID type and an uuid.UUID adapter.
[ "Create", "the", "UUID", "type", "and", "an", "uuid", ".", "UUID", "adapter", "." ]
def register_uuid(oids=None, conn_or_curs=None): """Create the UUID type and an uuid.UUID adapter. :param oids: oid for the PostgreSQL :sql:`uuid` type, or 2-items sequence with oids of the type and the array. If not specified, use PostgreSQL standard oids. :param conn_or_curs: where to register the typecaster. If not specified, register it globally. """ import uuid if not oids: oid1 = 2950 oid2 = 2951 elif isinstance(oids, (list, tuple)): oid1, oid2 = oids else: oid1 = oids oid2 = 2951 _ext.UUID = _ext.new_type((oid1, ), "UUID", lambda data, cursor: data and uuid.UUID(data) or None) _ext.UUIDARRAY = _ext.new_array_type((oid2,), "UUID[]", _ext.UUID) _ext.register_type(_ext.UUID, conn_or_curs) _ext.register_type(_ext.UUIDARRAY, conn_or_curs) _ext.register_adapter(uuid.UUID, UUID_adapter) return _ext.UUID
[ "def", "register_uuid", "(", "oids", "=", "None", ",", "conn_or_curs", "=", "None", ")", ":", "import", "uuid", "if", "not", "oids", ":", "oid1", "=", "2950", "oid2", "=", "2951", "elif", "isinstance", "(", "oids", ",", "(", "list", ",", "tuple", ")"...
https://github.com/jkehler/awslambda-psycopg2/blob/c7b1b2f6382bbe5893d95c4e7f4b5ffdf05ab3b4/with_ssl_support/psycopg2/extras.py#L627-L656
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/functions/elementary/hyperbolic.py
python
sinh.as_real_imag
(self, deep=True, **hints)
return (sinh(re)*cos(im), cosh(re)*sin(im))
Returns this function as a complex coordinate.
Returns this function as a complex coordinate.
[ "Returns", "this", "function", "as", "a", "complex", "coordinate", "." ]
def as_real_imag(self, deep=True, **hints): """ Returns this function as a complex coordinate. """ from sympy.functions.elementary.trigonometric import (cos, sin) if self.args[0].is_extended_real: if deep: hints['complex'] = False return (self.expand(deep, **hints), S.Zero) else: return (self, S.Zero) if deep: re, im = self.args[0].expand(deep, **hints).as_real_imag() else: re, im = self.args[0].as_real_imag() return (sinh(re)*cos(im), cosh(re)*sin(im))
[ "def", "as_real_imag", "(", "self", ",", "deep", "=", "True", ",", "*", "*", "hints", ")", ":", "from", "sympy", ".", "functions", ".", "elementary", ".", "trigonometric", "import", "(", "cos", ",", "sin", ")", "if", "self", ".", "args", "[", "0", ...
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/functions/elementary/hyperbolic.py#L179-L194
yhat/ggpy
b6d23c22d52557b983da8ce7a3a6992501dadcd6
ggplot/colors/palettes.py
python
dark_palette
(color, n_colors=6, reverse=False, as_cmap=False)
return blend_palette(colors, n_colors, as_cmap)
Make a palette that blends from a deep gray to `color`. Parameters ---------- color : matplotlib color hex, rgb-tuple, or html color name n_colors : int, optional number of colors in the palette reverse : bool, optional if True, reverse the direction of the blend as_cmap : bool, optional if True, return as a matplotlib colormap instead of list Returns ------- palette : list or colormap
Make a palette that blends from a deep gray to `color`.
[ "Make", "a", "palette", "that", "blends", "from", "a", "deep", "gray", "to", "color", "." ]
def dark_palette(color, n_colors=6, reverse=False, as_cmap=False): """Make a palette that blends from a deep gray to `color`. Parameters ---------- color : matplotlib color hex, rgb-tuple, or html color name n_colors : int, optional number of colors in the palette reverse : bool, optional if True, reverse the direction of the blend as_cmap : bool, optional if True, return as a matplotlib colormap instead of list Returns ------- palette : list or colormap """ gray = "#222222" colors = [color, gray] if reverse else [gray, color] return blend_palette(colors, n_colors, as_cmap)
[ "def", "dark_palette", "(", "color", ",", "n_colors", "=", "6", ",", "reverse", "=", "False", ",", "as_cmap", "=", "False", ")", ":", "gray", "=", "\"#222222\"", "colors", "=", "[", "color", ",", "gray", "]", "if", "reverse", "else", "[", "gray", ","...
https://github.com/yhat/ggpy/blob/b6d23c22d52557b983da8ce7a3a6992501dadcd6/ggplot/colors/palettes.py#L272-L293
WerWolv/EdiZon_CheatsConfigsAndScripts
d16d36c7509c01dca770f402babd83ff2e9ae6e7
Scripts/lib/python3.5/logging/handlers.py
python
SocketHandler.handleError
(self, record)
Handle an error during logging. An error has occurred during logging. Most likely cause - connection lost. Close the socket so that we can retry on the next event.
Handle an error during logging.
[ "Handle", "an", "error", "during", "logging", "." ]
def handleError(self, record): """ Handle an error during logging. An error has occurred during logging. Most likely cause - connection lost. Close the socket so that we can retry on the next event. """ if self.closeOnError and self.sock: self.sock.close() self.sock = None #try to reconnect next time else: logging.Handler.handleError(self, record)
[ "def", "handleError", "(", "self", ",", "record", ")", ":", "if", "self", ".", "closeOnError", "and", "self", ".", "sock", ":", "self", ".", "sock", ".", "close", "(", ")", "self", ".", "sock", "=", "None", "#try to reconnect next time", "else", ":", "...
https://github.com/WerWolv/EdiZon_CheatsConfigsAndScripts/blob/d16d36c7509c01dca770f402babd83ff2e9ae6e7/Scripts/lib/python3.5/logging/handlers.py#L597-L609
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/mpmath/functions/theta.py
python
_djacobi_theta3a
(ctx, z, q, nd)
return (2*ctx.j)**nd * s
case ctx._im(z) != 0 djtheta3(z, q, nd) = (2*j)**nd * Sum(q**(n*n) * n**nd * exp(j*2*n*z), n, -inf, inf) max term for minimum n*abs(log(q).real) + ctx._im(z)
case ctx._im(z) != 0 djtheta3(z, q, nd) = (2*j)**nd * Sum(q**(n*n) * n**nd * exp(j*2*n*z), n, -inf, inf) max term for minimum n*abs(log(q).real) + ctx._im(z)
[ "case", "ctx", ".", "_im", "(", "z", ")", "!", "=", "0", "djtheta3", "(", "z", "q", "nd", ")", "=", "(", "2", "*", "j", ")", "**", "nd", "*", "Sum", "(", "q", "**", "(", "n", "*", "n", ")", "*", "n", "**", "nd", "*", "exp", "(", "j", ...
def _djacobi_theta3a(ctx, z, q, nd): """ case ctx._im(z) != 0 djtheta3(z, q, nd) = (2*j)**nd * Sum(q**(n*n) * n**nd * exp(j*2*n*z), n, -inf, inf) max term for minimum n*abs(log(q).real) + ctx._im(z) """ n = n0 = int(-ctx._im(z)/abs(ctx._re(ctx.log(q)))) e2 = ctx.expj(2*z) e = e0 = ctx.expj(2*n*z) a = q**(n*n) * e s = term = n**nd * a if n != 0: eps1 = ctx.eps*abs(term) else: eps1 = ctx.eps*abs(a) while 1: n += 1 e = e * e2 a = q**(n*n) * e term = n**nd * a if n != 0: aterm = abs(term) else: aterm = abs(a) if aterm < eps1: break s += term e = e0 e2 = ctx.expj(-2*z) n = n0 while 1: n -= 1 e = e * e2 a = q**(n*n) * e term = n**nd * a if n != 0: aterm = abs(term) else: aterm = abs(a) if aterm < eps1: break s += term return (2*ctx.j)**nd * s
[ "def", "_djacobi_theta3a", "(", "ctx", ",", "z", ",", "q", ",", "nd", ")", ":", "n", "=", "n0", "=", "int", "(", "-", "ctx", ".", "_im", "(", "z", ")", "/", "abs", "(", "ctx", ".", "_re", "(", "ctx", ".", "log", "(", "q", ")", ")", ")", ...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/mpmath/functions/theta.py#L865-L908
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
stock/ctp/ApiStruct.py
python
RspQueryAccount.__init__
(self, TradeCode='', BankID='', BankBranchID='', BrokerID='', BrokerBranchID='', TradeDate='', TradeTime='', BankSerial='', TradingDay='', PlateSerial=0, LastFragment=LF_Yes, SessionID=0, CustomerName='', IdCardType=ICT_EID, IdentifiedCardNo='', CustType=CUSTT_Person, BankAccount='', BankPassWord='', AccountID='', Password='', FutureSerial=0, InstallID=0, UserID='', VerifyCertNoFlag=YNI_Yes, CurrencyID='', Digest='', BankAccType=BAT_BankBook, DeviceID='', BankSecuAccType=BAT_BankBook, BrokerIDByBank='', BankSecuAcc='', BankPwdFlag=BPWDF_NoCheck, SecuPwdFlag=BPWDF_NoCheck, OperNo='', RequestID=0, TID=0, BankUseAmount=0.0, BankFetchAmount=0.0)
[]
def __init__(self, TradeCode='', BankID='', BankBranchID='', BrokerID='', BrokerBranchID='', TradeDate='', TradeTime='', BankSerial='', TradingDay='', PlateSerial=0, LastFragment=LF_Yes, SessionID=0, CustomerName='', IdCardType=ICT_EID, IdentifiedCardNo='', CustType=CUSTT_Person, BankAccount='', BankPassWord='', AccountID='', Password='', FutureSerial=0, InstallID=0, UserID='', VerifyCertNoFlag=YNI_Yes, CurrencyID='', Digest='', BankAccType=BAT_BankBook, DeviceID='', BankSecuAccType=BAT_BankBook, BrokerIDByBank='', BankSecuAcc='', BankPwdFlag=BPWDF_NoCheck, SecuPwdFlag=BPWDF_NoCheck, OperNo='', RequestID=0, TID=0, BankUseAmount=0.0, BankFetchAmount=0.0): self.TradeCode = '' #业务功能码, char[7] self.BankID = '' #银行代码, char[4] self.BankBranchID = 'BankBrchID' #银行分支机构代码, char[5] self.BrokerID = '' #期商代码, char[11] self.BrokerBranchID = 'FutureBranchID' #期商分支机构代码, char[31] self.TradeDate = '' #交易日期, char[9] self.TradeTime = '' #交易时间, char[9] self.BankSerial = '' #银行流水号, char[13] self.TradingDay = 'TradeDate' #交易系统日期 , char[9] self.PlateSerial = 'Serial' #银期平台消息流水号, int self.LastFragment = '' #最后分片标志, char self.SessionID = '' #会话号, int self.CustomerName = 'IndividualName' #客户姓名, char[51] self.IdCardType = '' #证件类型, char self.IdentifiedCardNo = '' #证件号码, char[51] self.CustType = '' #客户类型, char self.BankAccount = '' #银行帐号, char[41] self.BankPassWord = 'Password' #银行密码, char[41] self.AccountID = '' #投资者帐号, char[15] self.Password = '' #期货密码, char[41] self.FutureSerial = '' #期货公司流水号, int self.InstallID = '' #安装编号, int self.UserID = '' #用户标识, char[16] self.VerifyCertNoFlag = 'YesNoIndicator' #验证客户证件号码标志, char self.CurrencyID = '' #币种代码, char[4] self.Digest = '' #摘要, char[36] self.BankAccType = '' #银行帐号类型, char self.DeviceID = '' #渠道标志, char[3] self.BankSecuAccType = 'BankAccType' #期货单位帐号类型, char self.BrokerIDByBank = 'BankCodingForFuture' #期货公司银行编码, char[33] self.BankSecuAcc = 'BankAccount' #期货单位帐号, char[41] self.BankPwdFlag = 'PwdFlag' #银行密码标志, char self.SecuPwdFlag = 'PwdFlag' #期货资金密码核对标志, char self.OperNo = '' #交易柜员, char[17] self.RequestID = '' #请求编号, int self.TID = '' #交易ID, int self.BankUseAmount = 'TradeAmount' #银行可用金额, double self.BankFetchAmount = 'TradeAmount'
[ "def", "__init__", "(", "self", ",", "TradeCode", "=", "''", ",", "BankID", "=", "''", ",", "BankBranchID", "=", "''", ",", "BrokerID", "=", "''", ",", "BrokerBranchID", "=", "''", ",", "TradeDate", "=", "''", ",", "TradeTime", "=", "''", ",", "BankS...
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/stock/ctp/ApiStruct.py#L3819-L3857
YaoZeyuan/ZhihuHelp_archived
a0e4a7acd4512452022ce088fff2adc6f8d30195
src/lib/oauth/zhihu_oauth/exception.py
python
NeedCaptchaException.__init__
(self)
登录过程需要验证码
登录过程需要验证码
[ "登录过程需要验证码" ]
def __init__(self): """ 登录过程需要验证码 """ pass
[ "def", "__init__", "(", "self", ")", ":", "pass" ]
https://github.com/YaoZeyuan/ZhihuHelp_archived/blob/a0e4a7acd4512452022ce088fff2adc6f8d30195/src/lib/oauth/zhihu_oauth/exception.py#L101-L105
Cadene/tensorflow-model-zoo.torch
990b10ffc22d4c8eacb2a502f20415b4f70c74c2
models/research/neural_gpu/neural_gpu.py
python
quantize
(t, quant_scale, max_value=1.0)
return res
Quantize a tensor t with each element in [-max_value, max_value].
Quantize a tensor t with each element in [-max_value, max_value].
[ "Quantize", "a", "tensor", "t", "with", "each", "element", "in", "[", "-", "max_value", "max_value", "]", "." ]
def quantize(t, quant_scale, max_value=1.0): """Quantize a tensor t with each element in [-max_value, max_value].""" t = tf.minimum(max_value, tf.maximum(t, -max_value)) big = quant_scale * (t + max_value) + 0.5 with tf.get_default_graph().gradient_override_map({"Floor": "CustomIdG"}): res = (tf.floor(big) / quant_scale) - max_value return res
[ "def", "quantize", "(", "t", ",", "quant_scale", ",", "max_value", "=", "1.0", ")", ":", "t", "=", "tf", ".", "minimum", "(", "max_value", ",", "tf", ".", "maximum", "(", "t", ",", "-", "max_value", ")", ")", "big", "=", "quant_scale", "*", "(", ...
https://github.com/Cadene/tensorflow-model-zoo.torch/blob/990b10ffc22d4c8eacb2a502f20415b4f70c74c2/models/research/neural_gpu/neural_gpu.py#L171-L177
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/returners/__init__.py
python
_fetch_ret_config
(ret)
return str(ret["ret_config"])
Fetches 'ret_config' if available. @see :func:`get_returner_options`
Fetches 'ret_config' if available.
[ "Fetches", "ret_config", "if", "available", "." ]
def _fetch_ret_config(ret): """ Fetches 'ret_config' if available. @see :func:`get_returner_options` """ if not ret: return None if "ret_config" not in ret: return "" return str(ret["ret_config"])
[ "def", "_fetch_ret_config", "(", "ret", ")", ":", "if", "not", "ret", ":", "return", "None", "if", "\"ret_config\"", "not", "in", "ret", ":", "return", "\"\"", "return", "str", "(", "ret", "[", "\"ret_config\"", "]", ")" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/returners/__init__.py#L99-L109
mitre-attack/attack-website
446748b71f412f7125d596a5eae0869559c89f05
modules/util/stixhelpers.py
python
datasource_of
()
return datasource_of
Builds map from data component STIX ID to data source STIX object
Builds map from data component STIX ID to data source STIX object
[ "Builds", "map", "from", "data", "component", "STIX", "ID", "to", "data", "source", "STIX", "object" ]
def datasource_of(): """ Builds map from data component STIX ID to data source STIX object """ datacomponents = relationshipgetters.get_datacomponent_list() datasource_of = {} for datacomponent in datacomponents: if not datasource_of.get(datacomponent['id']): datasource = get_datasource_from_list(datacomponent['x_mitre_data_source_ref']) if datasource: datasource_of[datacomponent['id']] = datasource return datasource_of
[ "def", "datasource_of", "(", ")", ":", "datacomponents", "=", "relationshipgetters", ".", "get_datacomponent_list", "(", ")", "datasource_of", "=", "{", "}", "for", "datacomponent", "in", "datacomponents", ":", "if", "not", "datasource_of", ".", "get", "(", "dat...
https://github.com/mitre-attack/attack-website/blob/446748b71f412f7125d596a5eae0869559c89f05/modules/util/stixhelpers.py#L213-L229
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/lib-tk/ttk.py
python
Button.__init__
(self, master=None, **kw)
Construct a Ttk Button widget with the parent master. STANDARD OPTIONS class, compound, cursor, image, state, style, takefocus, text, textvariable, underline, width WIDGET-SPECIFIC OPTIONS command, default, width
Construct a Ttk Button widget with the parent master.
[ "Construct", "a", "Ttk", "Button", "widget", "with", "the", "parent", "master", "." ]
def __init__(self, master=None, **kw): """Construct a Ttk Button widget with the parent master. STANDARD OPTIONS class, compound, cursor, image, state, style, takefocus, text, textvariable, underline, width WIDGET-SPECIFIC OPTIONS command, default, width """ Widget.__init__(self, master, "ttk::button", kw)
[ "def", "__init__", "(", "self", ",", "master", "=", "None", ",", "*", "*", "kw", ")", ":", "Widget", ".", "__init__", "(", "self", ",", "master", ",", "\"ttk::button\"", ",", "kw", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/lib-tk/ttk.py#L598-L610
TesterlifeRaymond/doraemon
d5cb6e34bd5f2aa97273ce0c0c9303e32beaa333
venv/lib/python3.6/site-packages/pip/_vendor/requests/packages/urllib3/connectionpool.py
python
HTTPConnectionPool._new_conn
(self)
return conn
Return a fresh :class:`HTTPConnection`.
Return a fresh :class:`HTTPConnection`.
[ "Return", "a", "fresh", ":", "class", ":", "HTTPConnection", "." ]
def _new_conn(self): """ Return a fresh :class:`HTTPConnection`. """ self.num_connections += 1 log.info("Starting new HTTP connection (%d): %s", self.num_connections, self.host) conn = self.ConnectionCls(host=self.host, port=self.port, timeout=self.timeout.connect_timeout, strict=self.strict, **self.conn_kw) return conn
[ "def", "_new_conn", "(", "self", ")", ":", "self", ".", "num_connections", "+=", "1", "log", ".", "info", "(", "\"Starting new HTTP connection (%d): %s\"", ",", "self", ".", "num_connections", ",", "self", ".", "host", ")", "conn", "=", "self", ".", "Connect...
https://github.com/TesterlifeRaymond/doraemon/blob/d5cb6e34bd5f2aa97273ce0c0c9303e32beaa333/venv/lib/python3.6/site-packages/pip/_vendor/requests/packages/urllib3/connectionpool.py#L208-L219
gpodder/mygpo
7a028ad621d05d4ca0d58fd22fb92656c8835e43
mygpo/users/views/registration.py
python
ResendActivationView.form_valid
(self, form)
return super(ResendActivationView, self).form_valid(form)
called whene the form was POSTed and its contents were valid
called whene the form was POSTed and its contents were valid
[ "called", "whene", "the", "form", "was", "POSTed", "and", "its", "contents", "were", "valid" ]
def form_valid(self, form): """called whene the form was POSTed and its contents were valid""" try: user = UserProxy.objects.all().by_username_or_email( form.cleaned_data["username"], form.cleaned_data["email"] ) except UserProxy.DoesNotExist: messages.error(self.request, _("User does not exist.")) return HttpResponseRedirect(reverse("resend-activation")) if user.profile.activation_key is None: messages.success( self.request, _("Your account already has been " "activated. Go ahead and log in."), ) send_activation_email(user, self.request) return super(ResendActivationView, self).form_valid(form)
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "try", ":", "user", "=", "UserProxy", ".", "objects", ".", "all", "(", ")", ".", "by_username_or_email", "(", "form", ".", "cleaned_data", "[", "\"username\"", "]", ",", "form", ".", "cleaned_data"...
https://github.com/gpodder/mygpo/blob/7a028ad621d05d4ca0d58fd22fb92656c8835e43/mygpo/users/views/registration.py#L188-L207
jmsdnns/microarmy
09bcd535eae75e96661636e30a0ca0fac60c7192
microarmy/firepower.py
python
parse_responses
(responses)
return aggregate_dict
Quick and dirty.
Quick and dirty.
[ "Quick", "and", "dirty", "." ]
def parse_responses(responses): """Quick and dirty.""" aggregate_dict = { 'num_trans': [], 'elapsed': [], 'tran_rate': [], } for response in responses: try: num_trans = response[4].split('\t')[2].strip()[:-5] elapsed = response[6].split('\t')[2].strip()[:-5] tran_rate = response[9].split('\t')[1].strip()[:-10] except IndexError: raise UnparsableData(response) aggregate_dict['num_trans'].append(num_trans) aggregate_dict['elapsed'].append(elapsed) aggregate_dict['tran_rate'].append(tran_rate) return aggregate_dict
[ "def", "parse_responses", "(", "responses", ")", ":", "aggregate_dict", "=", "{", "'num_trans'", ":", "[", "]", ",", "'elapsed'", ":", "[", "]", ",", "'tran_rate'", ":", "[", "]", ",", "}", "for", "response", "in", "responses", ":", "try", ":", "num_tr...
https://github.com/jmsdnns/microarmy/blob/09bcd535eae75e96661636e30a0ca0fac60c7192/microarmy/firepower.py#L258-L278
yu4u/noise2noise
c25d5a81cd2c7077e801b42e1dd05442fd19d8c2
model.py
python
L0Loss.__init__
(self)
[]
def __init__(self): self.gamma = K.variable(2.)
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "gamma", "=", "K", ".", "variable", "(", "2.", ")" ]
https://github.com/yu4u/noise2noise/blob/c25d5a81cd2c7077e801b42e1dd05442fd19d8c2/model.py#L11-L12
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/physics/mechanics/point.py
python
Point.locatenew
(self, name, value)
return p
Creates a new point with a position defined from this point. Parameters ========== name : str The name for the new point value : Vector The position of the new point relative to this point Examples ======== >>> from sympy.physics.mechanics import ReferenceFrame, Point >>> N = ReferenceFrame('N') >>> P1 = Point('P1') >>> P2 = P1.locatenew('P2', 10 * N.x)
Creates a new point with a position defined from this point.
[ "Creates", "a", "new", "point", "with", "a", "position", "defined", "from", "this", "point", "." ]
def locatenew(self, name, value): """Creates a new point with a position defined from this point. Parameters ========== name : str The name for the new point value : Vector The position of the new point relative to this point Examples ======== >>> from sympy.physics.mechanics import ReferenceFrame, Point >>> N = ReferenceFrame('N') >>> P1 = Point('P1') >>> P2 = P1.locatenew('P2', 10 * N.x) """ if not isinstance(name, str): raise TypeError('Must supply a valid name') if value == 0: value = Vector(0) value = _check_vector(value) p = Point(name) p.set_pos(self, value) self.set_pos(p, -value) return p
[ "def", "locatenew", "(", "self", ",", "name", ",", "value", ")", ":", "if", "not", "isinstance", "(", "name", ",", "str", ")", ":", "raise", "TypeError", "(", "'Must supply a valid name'", ")", "if", "value", "==", "0", ":", "value", "=", "Vector", "("...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/physics/mechanics/point.py#L187-L216
tianzhi0549/FCOS
0eb8ee0b7114a3ca42ad96cd89e0ac63a205461e
fcos_core/structures/bounding_box.py
python
BoxList.resize
(self, size, *args, **kwargs)
return bbox.convert(self.mode)
Returns a resized copy of this bounding box :param size: The requested size in pixels, as a 2-tuple: (width, height).
Returns a resized copy of this bounding box
[ "Returns", "a", "resized", "copy", "of", "this", "bounding", "box" ]
def resize(self, size, *args, **kwargs): """ Returns a resized copy of this bounding box :param size: The requested size in pixels, as a 2-tuple: (width, height). """ ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(size, self.size)) if ratios[0] == ratios[1]: ratio = ratios[0] scaled_box = self.bbox * ratio bbox = BoxList(scaled_box, size, mode=self.mode) # bbox._copy_extra_fields(self) for k, v in self.extra_fields.items(): if not isinstance(v, torch.Tensor): v = v.resize(size, *args, **kwargs) bbox.add_field(k, v) return bbox ratio_width, ratio_height = ratios xmin, ymin, xmax, ymax = self._split_into_xyxy() scaled_xmin = xmin * ratio_width scaled_xmax = xmax * ratio_width scaled_ymin = ymin * ratio_height scaled_ymax = ymax * ratio_height scaled_box = torch.cat( (scaled_xmin, scaled_ymin, scaled_xmax, scaled_ymax), dim=-1 ) bbox = BoxList(scaled_box, size, mode="xyxy") # bbox._copy_extra_fields(self) for k, v in self.extra_fields.items(): if not isinstance(v, torch.Tensor): v = v.resize(size, *args, **kwargs) bbox.add_field(k, v) return bbox.convert(self.mode)
[ "def", "resize", "(", "self", ",", "size", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ratios", "=", "tuple", "(", "float", "(", "s", ")", "/", "float", "(", "s_orig", ")", "for", "s", ",", "s_orig", "in", "zip", "(", "size", ",", "...
https://github.com/tianzhi0549/FCOS/blob/0eb8ee0b7114a3ca42ad96cd89e0ac63a205461e/fcos_core/structures/bounding_box.py#L91-L127
mahmoud/lithoxyl
b4bfa92c54df85b4bd5935fe270e2aa3fb25c412
lithoxyl/logger.py
python
Logger.on_begin
(self, begin_event)
return
Publish *begin_event* to all sinks with ``on_begin()`` hooks.
Publish *begin_event* to all sinks with ``on_begin()`` hooks.
[ "Publish", "*", "begin_event", "*", "to", "all", "sinks", "with", "on_begin", "()", "hooks", "." ]
def on_begin(self, begin_event): "Publish *begin_event* to all sinks with ``on_begin()`` hooks." if self.async_mode: self.event_queue.append(('begin', begin_event)) else: for begin_hook in self._begin_hooks: begin_hook(begin_event) return
[ "def", "on_begin", "(", "self", ",", "begin_event", ")", ":", "if", "self", ".", "async_mode", ":", "self", ".", "event_queue", ".", "append", "(", "(", "'begin'", ",", "begin_event", ")", ")", "else", ":", "for", "begin_hook", "in", "self", ".", "_beg...
https://github.com/mahmoud/lithoxyl/blob/b4bfa92c54df85b4bd5935fe270e2aa3fb25c412/lithoxyl/logger.py#L198-L205
KalleHallden/AutoTimer
2d954216700c4930baa154e28dbddc34609af7ce
env/lib/python2.7/site-packages/objc/_convenience_mapping.py
python
contains_objectForKey_
(self, key)
return res is not None
[]
def contains_objectForKey_(self, key): res = self.objectForKey_(container_wrap(key)) return res is not None
[ "def", "contains_objectForKey_", "(", "self", ",", "key", ")", ":", "res", "=", "self", ".", "objectForKey_", "(", "container_wrap", "(", "key", ")", ")", "return", "res", "is", "not", "None" ]
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/objc/_convenience_mapping.py#L28-L30
feisuzhu/thbattle
ac0dee1b2d86de7664289cf432b157ef25427ba1
tools/THB.app/Contents/Resources/pycparser.egg/pycparser/c_parser.py
python
CParser.p_pointer
(self, p)
pointer : TIMES type_qualifier_list_opt | TIMES type_qualifier_list_opt pointer
pointer : TIMES type_qualifier_list_opt | TIMES type_qualifier_list_opt pointer
[ "pointer", ":", "TIMES", "type_qualifier_list_opt", "|", "TIMES", "type_qualifier_list_opt", "pointer" ]
def p_pointer(self, p): """ pointer : TIMES type_qualifier_list_opt | TIMES type_qualifier_list_opt pointer """ coord = self._coord(p.lineno(1)) # Pointer decls nest from inside out. This is important when different # levels have different qualifiers. For example: # # char * const * p; # # Means "pointer to const pointer to char" # # While: # # char ** const p; # # Means "const pointer to pointer to char" # # So when we construct PtrDecl nestings, the leftmost pointer goes in # as the most nested type. nested_type = c_ast.PtrDecl(quals=p[2] or [], type=None, coord=coord) if len(p) > 3: tail_type = p[3] while tail_type.type is not None: tail_type = tail_type.type tail_type.type = nested_type p[0] = p[3] else: p[0] = nested_type
[ "def", "p_pointer", "(", "self", ",", "p", ")", ":", "coord", "=", "self", ".", "_coord", "(", "p", ".", "lineno", "(", "1", ")", ")", "# Pointer decls nest from inside out. This is important when different", "# levels have different qualifiers. For example:", "#", "#...
https://github.com/feisuzhu/thbattle/blob/ac0dee1b2d86de7664289cf432b157ef25427ba1/tools/THB.app/Contents/Resources/pycparser.egg/pycparser/c_parser.py#L1056-L1084
robotlearn/pyrobolearn
9cd7c060723fda7d2779fa255ac998c2c82b8436
pyrobolearn/optimizers/torch_optimizer.py
python
Adam.reset
(self)
Reset the optimizer.
Reset the optimizer.
[ "Reset", "the", "optimizer", "." ]
def reset(self): """Reset the optimizer.""" self.optimizer = None
[ "def", "reset", "(", "self", ")", ":", "self", ".", "optimizer", "=", "None" ]
https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/optimizers/torch_optimizer.py#L83-L85
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/client/grr_response_client/comms.py
python
GRRHTTPClient.Run
(self)
The main run method of the client. This method does not normally return. Only if there have been more than connection_error_limit failures, the method returns and allows the client to exit.
The main run method of the client.
[ "The", "main", "run", "method", "of", "the", "client", "." ]
def Run(self): """The main run method of the client. This method does not normally return. Only if there have been more than connection_error_limit failures, the method returns and allows the client to exit. """ while True: if self.http_manager.ErrorLimitReached(): return # Check if there is a message from the nanny to be sent. self.client_worker.SendNannyMessage() now = time.time() # Check with the foreman if we need to if (now > self.last_foreman_check + config.CONFIG["Client.foreman_check_frequency"]): # We must not queue messages from the comms thread with blocking=True # or we might deadlock. If the output queue is full, we can't accept # more work from the foreman anyways so it's ok to drop the message. try: self.client_worker.SendReply( rdf_protodict.DataBlob(), session_id=rdfvalue.FlowSessionID(flow_name="Foreman"), require_fastpoll=False, blocking=False) self.last_foreman_check = now except queue.Full: pass try: self.RunOnce() except Exception: # pylint: disable=broad-except # Catch everything, yes, this is terrible but necessary logging.warning("Uncaught exception caught: %s", traceback.format_exc()) if flags.FLAGS.pdb_post_mortem: pdb.post_mortem() # We suicide if our memory is exceeded, and there is no more work to do # right now. Our death should not result in loss of messages since we are # not holding any requests in our input queues. if (self.client_worker.MemoryExceeded() and not self.client_worker.IsActive() and self.client_worker.InQueueSize() == 0 and self.client_worker.OutQueueSize() == 0): logging.warning("Memory exceeded - exiting.") self.client_worker.SendClientAlert("Memory limit exceeded, exiting.") # Make sure this will return True so we don't get more work. # pylint: disable=g-bad-name self.client_worker.MemoryExceeded = lambda: True # pylint: enable=g-bad-name # Now send back the client message. self.RunOnce() # And done for now. sys.exit(-1) self.timer.Wait() self.client_worker.Heartbeat()
[ "def", "Run", "(", "self", ")", ":", "while", "True", ":", "if", "self", ".", "http_manager", ".", "ErrorLimitReached", "(", ")", ":", "return", "# Check if there is a message from the nanny to be sent.", "self", ".", "client_worker", ".", "SendNannyMessage", "(", ...
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/client/grr_response_client/comms.py#L1216-L1274
nosmokingbandit/Watcher3
0217e75158b563bdefc8e01c3be7620008cf3977
lib/transmissionrpc/client.py
python
Client.verify_torrent
(self, ids, timeout=None)
verify torrent(s) with provided id(s)
verify torrent(s) with provided id(s)
[ "verify", "torrent", "(", "s", ")", "with", "provided", "id", "(", "s", ")" ]
def verify_torrent(self, ids, timeout=None): """verify torrent(s) with provided id(s)""" self._request('torrent-verify', {}, ids, True, timeout=timeout)
[ "def", "verify_torrent", "(", "self", ",", "ids", ",", "timeout", "=", "None", ")", ":", "self", ".", "_request", "(", "'torrent-verify'", ",", "{", "}", ",", "ids", ",", "True", ",", "timeout", "=", "timeout", ")" ]
https://github.com/nosmokingbandit/Watcher3/blob/0217e75158b563bdefc8e01c3be7620008cf3977/lib/transmissionrpc/client.py#L528-L530
scikit-learn/scikit-learn
1d1aadd0711b87d2a11c80aad15df6f8cf156712
sklearn/preprocessing/_discretization.py
python
KBinsDiscretizer._validate_n_bins
(self, n_features)
return n_bins
Returns n_bins_, the number of bins per feature.
Returns n_bins_, the number of bins per feature.
[ "Returns", "n_bins_", "the", "number", "of", "bins", "per", "feature", "." ]
def _validate_n_bins(self, n_features): """Returns n_bins_, the number of bins per feature.""" orig_bins = self.n_bins if isinstance(orig_bins, numbers.Number): if not isinstance(orig_bins, numbers.Integral): raise ValueError( "{} received an invalid n_bins type. " "Received {}, expected int.".format( KBinsDiscretizer.__name__, type(orig_bins).__name__ ) ) if orig_bins < 2: raise ValueError( "{} received an invalid number " "of bins. Received {}, expected at least 2.".format( KBinsDiscretizer.__name__, orig_bins ) ) return np.full(n_features, orig_bins, dtype=int) n_bins = check_array(orig_bins, dtype=int, copy=True, ensure_2d=False) if n_bins.ndim > 1 or n_bins.shape[0] != n_features: raise ValueError("n_bins must be a scalar or array of shape (n_features,).") bad_nbins_value = (n_bins < 2) | (n_bins != orig_bins) violating_indices = np.where(bad_nbins_value)[0] if violating_indices.shape[0] > 0: indices = ", ".join(str(i) for i in violating_indices) raise ValueError( "{} received an invalid number " "of bins at indices {}. Number of bins " "must be at least 2, and must be an int.".format( KBinsDiscretizer.__name__, indices ) ) return n_bins
[ "def", "_validate_n_bins", "(", "self", ",", "n_features", ")", ":", "orig_bins", "=", "self", ".", "n_bins", "if", "isinstance", "(", "orig_bins", ",", "numbers", ".", "Number", ")", ":", "if", "not", "isinstance", "(", "orig_bins", ",", "numbers", ".", ...
https://github.com/scikit-learn/scikit-learn/blob/1d1aadd0711b87d2a11c80aad15df6f8cf156712/sklearn/preprocessing/_discretization.py#L315-L352
aws/sagemaker-python-sdk
9d259b316f7f43838c16f35c10e98a110b56735b
src/sagemaker/amazon/amazon_estimator.py
python
get_image_uri
(region_name, repo_name, repo_version=1)
return image_uris.retrieve( framework=repo_name, region=region_name, version=repo_version, )
Deprecated method. Please use sagemaker.image_uris.retrieve(). Args: region_name: name of the region repo_name: name of the repo (e.g. xgboost) repo_version: version of the repo Returns: the image uri
Deprecated method. Please use sagemaker.image_uris.retrieve().
[ "Deprecated", "method", ".", "Please", "use", "sagemaker", ".", "image_uris", ".", "retrieve", "()", "." ]
def get_image_uri(region_name, repo_name, repo_version=1): """Deprecated method. Please use sagemaker.image_uris.retrieve(). Args: region_name: name of the region repo_name: name of the repo (e.g. xgboost) repo_version: version of the repo Returns: the image uri """ renamed_warning("The method get_image_uri") return image_uris.retrieve( framework=repo_name, region=region_name, version=repo_version, )
[ "def", "get_image_uri", "(", "region_name", ",", "repo_name", ",", "repo_version", "=", "1", ")", ":", "renamed_warning", "(", "\"The method get_image_uri\"", ")", "return", "image_uris", ".", "retrieve", "(", "framework", "=", "repo_name", ",", "region", "=", "...
https://github.com/aws/sagemaker-python-sdk/blob/9d259b316f7f43838c16f35c10e98a110b56735b/src/sagemaker/amazon/amazon_estimator.py#L455-L471
cmbruns/pyopenvr
ac4847a8a05cda0d4bcf7c4f243008b2a191c7a5
src/openvr/__init__.py
python
IVRApplications.getApplicationKeyByIndex
(self, applicationIndex)
return bytes(appKeyBuffer.value).decode('utf-8')
Returns the key of the specified application. The index is at least 0 and is less than the return value of GetApplicationCount(). The buffer should be at least k_unMaxApplicationKeyLength in order to fit the key.
Returns the key of the specified application. The index is at least 0 and is less than the return value of GetApplicationCount(). The buffer should be at least k_unMaxApplicationKeyLength in order to fit the key.
[ "Returns", "the", "key", "of", "the", "specified", "application", ".", "The", "index", "is", "at", "least", "0", "and", "is", "less", "than", "the", "return", "value", "of", "GetApplicationCount", "()", ".", "The", "buffer", "should", "be", "at", "least", ...
def getApplicationKeyByIndex(self, applicationIndex): """ Returns the key of the specified application. The index is at least 0 and is less than the return value of GetApplicationCount(). The buffer should be at least k_unMaxApplicationKeyLength in order to fit the key. """ fn = self.function_table.getApplicationKeyByIndex appKeyBufferLen = fn(applicationIndex, None, 0) appKeyBuffer = ctypes.create_string_buffer(appKeyBufferLen) error = fn(applicationIndex, appKeyBuffer, appKeyBufferLen) openvr.error_code.ApplicationError.check_error_value(error) return bytes(appKeyBuffer.value).decode('utf-8')
[ "def", "getApplicationKeyByIndex", "(", "self", ",", "applicationIndex", ")", ":", "fn", "=", "self", ".", "function_table", ".", "getApplicationKeyByIndex", "appKeyBufferLen", "=", "fn", "(", "applicationIndex", ",", "None", ",", "0", ")", "appKeyBuffer", "=", ...
https://github.com/cmbruns/pyopenvr/blob/ac4847a8a05cda0d4bcf7c4f243008b2a191c7a5/src/openvr/__init__.py#L3481-L3492
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/pip/_vendor/ipaddress.py
python
IPv6Address.is_loopback
(self)
return self._ip == 1
Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3.
Test if the address is a loopback address.
[ "Test", "if", "the", "address", "is", "a", "loopback", "address", "." ]
def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3. """ return self._ip == 1
[ "def", "is_loopback", "(", "self", ")", ":", "return", "self", ".", "_ip", "==", "1" ]
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pip/_vendor/ipaddress.py#L2131-L2139
urschrei/pyzotero
ed4175e0f1a62f10984b311864c13ac453fa9ebe
pyzotero/zotero.py
python
Zotero.saved_search
(self, name, conditions)
return req.json()
Create a saved search. conditions is a list of dicts containing search conditions and must contain the following str keys: condition, operator, value
Create a saved search. conditions is a list of dicts containing search conditions and must contain the following str keys: condition, operator, value
[ "Create", "a", "saved", "search", ".", "conditions", "is", "a", "list", "of", "dicts", "containing", "search", "conditions", "and", "must", "contain", "the", "following", "str", "keys", ":", "condition", "operator", "value" ]
def saved_search(self, name, conditions): """Create a saved search. conditions is a list of dicts containing search conditions and must contain the following str keys: condition, operator, value """ self.savedsearch._validate(conditions) payload = [{"name": name, "conditions": conditions}] headers = {"Zotero-Write-Token": token()} headers.update(self.default_headers()) self._check_backoff() req = requests.post( url=build_url( self.endpoint, "/{t}/{u}/searches".format(t=self.library_type, u=self.library_id), ), headers=headers, data=json.dumps(payload), ) self.request = req try: req.raise_for_status() except requests.exceptions.HTTPError: error_handler(self, req) backoff = self.request.headers.get("backoff") or self.request.headers.get( "retry-after" ) if backoff: self._set_backoff(backoff) return req.json()
[ "def", "saved_search", "(", "self", ",", "name", ",", "conditions", ")", ":", "self", ".", "savedsearch", ".", "_validate", "(", "conditions", ")", "payload", "=", "[", "{", "\"name\"", ":", "name", ",", "\"conditions\"", ":", "conditions", "}", "]", "he...
https://github.com/urschrei/pyzotero/blob/ed4175e0f1a62f10984b311864c13ac453fa9ebe/pyzotero/zotero.py#L1004-L1032
entropy1337/infernal-twin
10995cd03312e39a48ade0f114ebb0ae3a711bb8
Modules/build/pip/build/lib.linux-i686-2.7/pip/_vendor/distlib/manifest.py
python
Manifest.__init__
(self, base=None)
Initialise an instance. :param base: The base directory to explore under.
Initialise an instance.
[ "Initialise", "an", "instance", "." ]
def __init__(self, base=None): """ Initialise an instance. :param base: The base directory to explore under. """ self.base = os.path.abspath(os.path.normpath(base or os.getcwd())) self.prefix = self.base + os.sep self.allfiles = None self.files = set()
[ "def", "__init__", "(", "self", ",", "base", "=", "None", ")", ":", "self", ".", "base", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "normpath", "(", "base", "or", "os", ".", "getcwd", "(", ")", ")", ")", "self", ".", ...
https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/build/pip/build/lib.linux-i686-2.7/pip/_vendor/distlib/manifest.py#L35-L44
giantbranch/python-hacker-code
addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d
我手敲的代码(中文注释)/chapter9/pycrypto-2.6.1/lib/Crypto/PublicKey/RSA.py
python
RSAImplementation.__init__
(self, **kwargs)
Create a new RSA key factory. :Keywords: use_fast_math : bool Specify which mathematic library to use: - *None* (default). Use fastest math available. - *True* . Use fast math. - *False* . Use slow math. default_randfunc : callable Specify how to collect random data: - *None* (default). Use Random.new().read(). - not *None* . Use the specified function directly. :Raise RuntimeError: When **use_fast_math** =True but fast math is not available.
Create a new RSA key factory.
[ "Create", "a", "new", "RSA", "key", "factory", "." ]
def __init__(self, **kwargs): """Create a new RSA key factory. :Keywords: use_fast_math : bool Specify which mathematic library to use: - *None* (default). Use fastest math available. - *True* . Use fast math. - *False* . Use slow math. default_randfunc : callable Specify how to collect random data: - *None* (default). Use Random.new().read(). - not *None* . Use the specified function directly. :Raise RuntimeError: When **use_fast_math** =True but fast math is not available. """ use_fast_math = kwargs.get('use_fast_math', None) if use_fast_math is None: # Automatic if _fastmath is not None: self._math = _fastmath else: self._math = _slowmath elif use_fast_math: # Explicitly select fast math if _fastmath is not None: self._math = _fastmath else: raise RuntimeError("fast math module not available") else: # Explicitly select slow math self._math = _slowmath self.error = self._math.error self._default_randfunc = kwargs.get('default_randfunc', None) self._current_randfunc = None
[ "def", "__init__", "(", "self", ",", "*", "*", "kwargs", ")", ":", "use_fast_math", "=", "kwargs", ".", "get", "(", "'use_fast_math'", ",", "None", ")", "if", "use_fast_math", "is", "None", ":", "# Automatic", "if", "_fastmath", "is", "not", "None", ":",...
https://github.com/giantbranch/python-hacker-code/blob/addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d/我手敲的代码(中文注释)/chapter9/pycrypto-2.6.1/lib/Crypto/PublicKey/RSA.py#L415-L452
d2l-ai/d2l-zh
1c2e25a557db446b5691c18e595e5664cc254730
contrib/to-rm-mx-contrib-text/d2lzh/utils.py
python
data_iter_consecutive
(corpus_indices, batch_size, num_steps, ctx=None)
Sample mini-batches in a consecutive order from sequential data.
Sample mini-batches in a consecutive order from sequential data.
[ "Sample", "mini", "-", "batches", "in", "a", "consecutive", "order", "from", "sequential", "data", "." ]
def data_iter_consecutive(corpus_indices, batch_size, num_steps, ctx=None): """Sample mini-batches in a consecutive order from sequential data.""" corpus_indices = nd.array(corpus_indices, ctx=ctx) data_len = len(corpus_indices) batch_len = data_len // batch_size indices = corpus_indices[0 : batch_size * batch_len].reshape(( batch_size, batch_len)) epoch_size = (batch_len - 1) // num_steps for i in range(epoch_size): i = i * num_steps X = indices[:, i : i + num_steps] Y = indices[:, i + 1 : i + num_steps + 1] yield X, Y
[ "def", "data_iter_consecutive", "(", "corpus_indices", ",", "batch_size", ",", "num_steps", ",", "ctx", "=", "None", ")", ":", "corpus_indices", "=", "nd", ".", "array", "(", "corpus_indices", ",", "ctx", "=", "ctx", ")", "data_len", "=", "len", "(", "corp...
https://github.com/d2l-ai/d2l-zh/blob/1c2e25a557db446b5691c18e595e5664cc254730/contrib/to-rm-mx-contrib-text/d2lzh/utils.py#L84-L96
khamidou/kite
c049faf8522c8346c22c70f2a35a35db6b4a155d
src/back/kite/bottle.py
python
run
(app=None, server='wsgiref', host='127.0.0.1', port=8080, interval=1, reloader=False, quiet=False, plugins=None, debug=None, **kargs)
Start a server instance. This method blocks until the server terminates. :param app: WSGI application or target string supported by :func:`load_app`. (default: :func:`default_app`) :param server: Server adapter to use. See :data:`server_names` keys for valid names or pass a :class:`ServerAdapter` subclass. (default: `wsgiref`) :param host: Server address to bind to. Pass ``0.0.0.0`` to listens on all interfaces including the external one. (default: 127.0.0.1) :param port: Server port to bind to. Values below 1024 require root privileges. (default: 8080) :param reloader: Start auto-reloading server? (default: False) :param interval: Auto-reloader interval in seconds (default: 1) :param quiet: Suppress output to stdout and stderr? (default: False) :param options: Options passed to the server adapter.
Start a server instance. This method blocks until the server terminates.
[ "Start", "a", "server", "instance", ".", "This", "method", "blocks", "until", "the", "server", "terminates", "." ]
def run(app=None, server='wsgiref', host='127.0.0.1', port=8080, interval=1, reloader=False, quiet=False, plugins=None, debug=None, **kargs): """ Start a server instance. This method blocks until the server terminates. :param app: WSGI application or target string supported by :func:`load_app`. (default: :func:`default_app`) :param server: Server adapter to use. See :data:`server_names` keys for valid names or pass a :class:`ServerAdapter` subclass. (default: `wsgiref`) :param host: Server address to bind to. Pass ``0.0.0.0`` to listens on all interfaces including the external one. (default: 127.0.0.1) :param port: Server port to bind to. Values below 1024 require root privileges. (default: 8080) :param reloader: Start auto-reloading server? (default: False) :param interval: Auto-reloader interval in seconds (default: 1) :param quiet: Suppress output to stdout and stderr? (default: False) :param options: Options passed to the server adapter. """ if NORUN: return if reloader and not os.environ.get('BOTTLE_CHILD'): try: lockfile = None fd, lockfile = tempfile.mkstemp(prefix='bottle.', suffix='.lock') os.close(fd) # We only need this file to exist. We never write to it while os.path.exists(lockfile): args = [sys.executable] + sys.argv environ = os.environ.copy() environ['BOTTLE_CHILD'] = 'true' environ['BOTTLE_LOCKFILE'] = lockfile p = subprocess.Popen(args, env=environ) while p.poll() is None: # Busy wait... os.utime(lockfile, None) # I am alive! time.sleep(interval) if p.poll() != 3: if os.path.exists(lockfile): os.unlink(lockfile) sys.exit(p.poll()) except KeyboardInterrupt: pass finally: if os.path.exists(lockfile): os.unlink(lockfile) return try: if debug is not None: _debug(debug) app = app or default_app() if isinstance(app, basestring): app = load_app(app) if not callable(app): raise ValueError("Application is not callable: %r" % app) for plugin in plugins or []: app.install(plugin) if server in server_names: server = server_names.get(server) if isinstance(server, basestring): server = load(server) if isinstance(server, type): server = server(host=host, port=port, **kargs) if not isinstance(server, ServerAdapter): raise ValueError("Unknown or unsupported server: %r" % server) server.quiet = server.quiet or quiet if not server.quiet: _stderr("Bottle v%s server starting up (using %s)...\n" % (__version__, repr(server))) _stderr("Listening on http://%s:%d/\n" % (server.host, server.port)) _stderr("Hit Ctrl-C to quit.\n\n") if reloader: lockfile = os.environ.get('BOTTLE_LOCKFILE') bgcheck = FileCheckerThread(lockfile, interval) with bgcheck: server.run(app) if bgcheck.status == 'reload': sys.exit(3) else: server.run(app) except KeyboardInterrupt: pass except (SystemExit, MemoryError): raise except: if not reloader: raise if not getattr(server, 'quiet', quiet): print_exc() time.sleep(interval) sys.exit(3)
[ "def", "run", "(", "app", "=", "None", ",", "server", "=", "'wsgiref'", ",", "host", "=", "'127.0.0.1'", ",", "port", "=", "8080", ",", "interval", "=", "1", ",", "reloader", "=", "False", ",", "quiet", "=", "False", ",", "plugins", "=", "None", ",...
https://github.com/khamidou/kite/blob/c049faf8522c8346c22c70f2a35a35db6b4a155d/src/back/kite/bottle.py#L2932-L3020
alephsecurity/abootool
4117b82d07e6b3a80eeab560d2140ae2dcfe2463
image.py
python
BlobArchive.__init__
(self, path, oem, device, build)
[]
def __init__(self, path, oem, device, build): self.oem = oem self.device = device self.build = build super(BlobArchive, self).__init__(path)
[ "def", "__init__", "(", "self", ",", "path", ",", "oem", ",", "device", ",", "build", ")", ":", "self", ".", "oem", "=", "oem", "self", ".", "device", "=", "device", "self", ".", "build", "=", "build", "super", "(", "BlobArchive", ",", "self", ")",...
https://github.com/alephsecurity/abootool/blob/4117b82d07e6b3a80eeab560d2140ae2dcfe2463/image.py#L385-L389
DxCx/plugin.video.9anime
34358c2f701e5ddf19d3276926374a16f63f7b6a
resources/lib/ui/js2py/legecy_translators/objects.py
python
remove_arrays
(code, count=1)
return res, replacements, count
removes arrays and replaces them with ARRAY_LVALS returns new code and replacement dict *NOTE* has to be called AFTER remove objects
removes arrays and replaces them with ARRAY_LVALS returns new code and replacement dict *NOTE* has to be called AFTER remove objects
[ "removes", "arrays", "and", "replaces", "them", "with", "ARRAY_LVALS", "returns", "new", "code", "and", "replacement", "dict", "*", "NOTE", "*", "has", "to", "be", "called", "AFTER", "remove", "objects" ]
def remove_arrays(code, count=1): """removes arrays and replaces them with ARRAY_LVALS returns new code and replacement dict *NOTE* has to be called AFTER remove objects""" res = '' last = '' replacements = {} for e in bracket_split(code, ['[]']): if e[0]=='[': if is_array(last): name = ARRAY_LVAL % count res += ' ' + name replacements[name] = e count += 1 else: # pseudo array. But pseudo array can contain true array. for example a[['d'][3]] has 2 pseudo and 1 true array cand, new_replacements, count = remove_arrays(e[1:-1], count) res += '[%s]' % cand replacements.update(new_replacements) else: res += e last = e return res, replacements, count
[ "def", "remove_arrays", "(", "code", ",", "count", "=", "1", ")", ":", "res", "=", "''", "last", "=", "''", "replacements", "=", "{", "}", "for", "e", "in", "bracket_split", "(", "code", ",", "[", "'[]'", "]", ")", ":", "if", "e", "[", "0", "]"...
https://github.com/DxCx/plugin.video.9anime/blob/34358c2f701e5ddf19d3276926374a16f63f7b6a/resources/lib/ui/js2py/legecy_translators/objects.py#L117-L138
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/distutils/filelist.py
python
_find_all_simple
(path)
return filter(os.path.isfile, results)
Find all files under 'path'
Find all files under 'path'
[ "Find", "all", "files", "under", "path" ]
def _find_all_simple(path): """ Find all files under 'path' """ results = ( os.path.join(base, file) for base, dirs, files in os.walk(path, followlinks=True) for file in files ) return filter(os.path.isfile, results)
[ "def", "_find_all_simple", "(", "path", ")", ":", "results", "=", "(", "os", ".", "path", ".", "join", "(", "base", ",", "file", ")", "for", "base", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "path", ",", "followlinks", "=", "True", ...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/distutils/filelist.py#L246-L255
phaethon/kamene
bf679a65d456411942ee4a907818ba3d6a183bfe
kamene/layers/bluetooth.py
python
srbt
(peer, pkts, inter=0.1, *args, **kargs)
return a,b
send and receive using a bluetooth socket
send and receive using a bluetooth socket
[ "send", "and", "receive", "using", "a", "bluetooth", "socket" ]
def srbt(peer, pkts, inter=0.1, *args, **kargs): """send and receive using a bluetooth socket""" s = conf.BTsocket(peer=peer) a,b = sndrcv(s,pkts,inter=inter,*args,**kargs) s.close() return a,b
[ "def", "srbt", "(", "peer", ",", "pkts", ",", "inter", "=", "0.1", ",", "*", "args", ",", "*", "*", "kargs", ")", ":", "s", "=", "conf", ".", "BTsocket", "(", "peer", "=", "peer", ")", "a", ",", "b", "=", "sndrcv", "(", "s", ",", "pkts", ",...
https://github.com/phaethon/kamene/blob/bf679a65d456411942ee4a907818ba3d6a183bfe/kamene/layers/bluetooth.py#L197-L202
titusjan/argos
5a9c31a8a9a2ca825bbf821aa1e685740e3682d7
argos/widgets/argostableview.py
python
ArgosTableView.copySelectionToClipboard
(self)
Copies selected cells to clipboard. Only works for ContiguousSelection
Copies selected cells to clipboard.
[ "Copies", "selected", "cells", "to", "clipboard", "." ]
def copySelectionToClipboard(self): """ Copies selected cells to clipboard. Only works for ContiguousSelection """ if not self.model(): logger.warning("Table contains no data. Copy to clipboard aborted.") return if self.selectionMode() not in [QtWidgets.QTableView.SingleSelection, QtWidgets.QTableView.ContiguousSelection]: logger.warning("Copy to clipboard does not work for current selection mode: {}" .format(self.selectionMode())) return selectedIndices = self.selectionModel().selectedIndexes() logger.info("Copying {} selected cells to clipboard.".format(len(selectedIndices))) # selectedIndexes() can return unsorted list so we sort it here to be sure. selectedIndices.sort(key=lambda idx: (idx.row(), idx.column())) # Unflatten indices into a list of list of indicides allIndices = [] allLines = [] lineIndices = [] # indices of current line prevRow = None for selIdx in selectedIndices: if prevRow != selIdx.row() and prevRow is not None: # new line allIndices.append(lineIndices) lineIndices = [] lineIndices.append(selIdx) prevRow = selIdx.row() allIndices.append(lineIndices) del lineIndices # Convert to tab-separated lines so it can be pasted in Excel. lines = [] for lineIndices in allIndices: line = '\t'.join([str(idx.data()) for idx in lineIndices]) lines.append(line) txt = '\n'.join(lines) #print(txt) QtWidgets.QApplication.clipboard().setText(txt)
[ "def", "copySelectionToClipboard", "(", "self", ")", ":", "if", "not", "self", ".", "model", "(", ")", ":", "logger", ".", "warning", "(", "\"Table contains no data. Copy to clipboard aborted.\"", ")", "return", "if", "self", ".", "selectionMode", "(", ")", "not...
https://github.com/titusjan/argos/blob/5a9c31a8a9a2ca825bbf821aa1e685740e3682d7/argos/widgets/argostableview.py#L51-L93
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/lib-tk/Tkinter.py
python
Text.tag_lower
(self, tagName, belowThis=None)
Change the priority of tag TAGNAME such that it is lower than the priority of BELOWTHIS.
Change the priority of tag TAGNAME such that it is lower than the priority of BELOWTHIS.
[ "Change", "the", "priority", "of", "tag", "TAGNAME", "such", "that", "it", "is", "lower", "than", "the", "priority", "of", "BELOWTHIS", "." ]
def tag_lower(self, tagName, belowThis=None): """Change the priority of tag TAGNAME such that it is lower than the priority of BELOWTHIS.""" self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
[ "def", "tag_lower", "(", "self", ",", "tagName", ",", "belowThis", "=", "None", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'tag'", ",", "'lower'", ",", "tagName", ",", "belowThis", ")" ]
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/lib-tk/Tkinter.py#L3071-L3074
guildai/guildai
1665985a3d4d788efc1a3180ca51cc417f71ca78
guild/external/pip/_vendor/pkg_resources/__init__.py
python
ZipProvider._is_current
(self, file_path, zip_path)
return zip_contents == file_contents
Return True if the file_path is current for this zip_path
Return True if the file_path is current for this zip_path
[ "Return", "True", "if", "the", "file_path", "is", "current", "for", "this", "zip_path" ]
def _is_current(self, file_path, zip_path): """ Return True if the file_path is current for this zip_path """ timestamp, size = self._get_date_and_size(self.zipinfo[zip_path]) if not os.path.isfile(file_path): return False stat = os.stat(file_path) if stat.st_size != size or stat.st_mtime != timestamp: return False # check that the contents match zip_contents = self.loader.get_data(zip_path) with open(file_path, 'rb') as f: file_contents = f.read() return zip_contents == file_contents
[ "def", "_is_current", "(", "self", ",", "file_path", ",", "zip_path", ")", ":", "timestamp", ",", "size", "=", "self", ".", "_get_date_and_size", "(", "self", ".", "zipinfo", "[", "zip_path", "]", ")", "if", "not", "os", ".", "path", ".", "isfile", "("...
https://github.com/guildai/guildai/blob/1665985a3d4d788efc1a3180ca51cc417f71ca78/guild/external/pip/_vendor/pkg_resources/__init__.py#L1706-L1720
wucng/TensorExpand
4ea58f64f5c5082b278229b799c9f679536510b7
TensorExpand/图片项目/11、对抗样本/main.py
python
adversary_example
(image_path, cls_target, noise_limit, required_score)
Find and plot adversarial noise for the given image. image_path: File-path to the input-image (must be *.jpg). cls_target: Target class-number (integer between 1-1000). noise_limit: Limit for pixel-values in the noise. required_score: Stop when target-class score reaches this.
Find and plot adversarial noise for the given image.
[ "Find", "and", "plot", "adversarial", "noise", "for", "the", "given", "image", "." ]
def adversary_example(image_path, cls_target, noise_limit, required_score): """ Find and plot adversarial noise for the given image. image_path: File-path to the input-image (must be *.jpg). cls_target: Target class-number (integer between 1-1000). noise_limit: Limit for pixel-values in the noise. required_score: Stop when target-class score reaches this. """ # Find the adversarial noise. image, noisy_image, noise, \ name_source, name_target, \ score_source, score_source_org, score_target = \ find_adversary_noise(image_path=image_path, cls_target=cls_target, noise_limit=noise_limit, required_score=required_score) # Plot the image and the noise. plot_images(image=image, noise=noise, noisy_image=noisy_image, name_source=name_source, name_target=name_target, score_source=score_source, score_source_org=score_source_org, score_target=score_target) # Print some statistics for the noise. msg = "Noise min: {0:.3f}, max: {1:.3f}, mean: {2:.3f}, std: {3:.3f}" print(msg.format(noise.min(), noise.max(), noise.mean(), noise.std()))
[ "def", "adversary_example", "(", "image_path", ",", "cls_target", ",", "noise_limit", ",", "required_score", ")", ":", "# Find the adversarial noise.", "image", ",", "noisy_image", ",", "noise", ",", "name_source", ",", "name_target", ",", "score_source", ",", "scor...
https://github.com/wucng/TensorExpand/blob/4ea58f64f5c5082b278229b799c9f679536510b7/TensorExpand/图片项目/11、对抗样本/main.py#L277-L307
mgear-dev/mgear
06ddc26c5adb5eab07ca470c7fafa77404c8a1de
scripts/mgear/maya/shifter/component/spine_ik_01/__init__.py
python
Component.addAttributes
(self)
Create the anim and setupr rig attributes for the component
Create the anim and setupr rig attributes for the component
[ "Create", "the", "anim", "and", "setupr", "rig", "attributes", "for", "the", "component" ]
def addAttributes(self): """Create the anim and setupr rig attributes for the component""" # Anim ------------------------------------------- self.position_att = self.addAnimParam("position", "Position", "double", self.settings["position"], 0, 1) self.maxstretch_att = self.addAnimParam("maxstretch", "Max Stretch", "double", self.settings["maxstretch"], 1) self.maxsquash_att = self.addAnimParam("maxsquash", "Max Squash", "double", self.settings["maxsquash"], 0, 1) self.softness_att = self.addAnimParam("softness", "Softness", "double", self.settings["softness"], 0, 1) self.lock_ori0_att = self.addAnimParam("lock_ori0", "Lock Ori 0", "double", self.settings["lock_ori"], 0, 1) self.lock_ori1_att = self.addAnimParam("lock_ori1", "Lock Ori 1", "double", self.settings["lock_ori"], 0, 1) self.tan0_att = self.addAnimParam("tan0", "Tangent 0", "double", 1, 0) self.tan1_att = self.addAnimParam("tan1", "Tangent 1", "double", 1, 0) # Volume self.volume_att = self.addAnimParam( "volume", "Volume", "double", 1, 0, 1) if self.settings["autoBend"]: self.sideBend_att = self.addAnimParam( "sideBend", "Side Bend", "double", .5, 0, 2) self.frontBend_att = self.addAnimParam( "frontBend", "Front Bend", "double", .5, 0, 2) # Setup ------------------------------------------ # Eval Fcurve self.st_value = fcurve.getFCurveValues( self.settings["st_profile"], self.settings["division"]) self.sq_value = fcurve.getFCurveValues( self.settings["sq_profile"], self.settings["division"]) self.st_att = [self.addSetupParam("stretch_%s" % i, "Stretch %s" % i, "double", self.st_value[i], -1, 0) for i in range(self.settings["division"])] self.sq_att = [self.addSetupParam("squash_%s" % i, "Squash %s" % i, "double", self.sq_value[i], 0, 1) for i in range(self.settings["division"])]
[ "def", "addAttributes", "(", "self", ")", ":", "# Anim -------------------------------------------", "self", ".", "position_att", "=", "self", ".", "addAnimParam", "(", "\"position\"", ",", "\"Position\"", ",", "\"double\"", ",", "self", ".", "settings", "[", "\"pos...
https://github.com/mgear-dev/mgear/blob/06ddc26c5adb5eab07ca470c7fafa77404c8a1de/scripts/mgear/maya/shifter/component/spine_ik_01/__init__.py#L340-L415
fortharris/Pcode
147962d160a834c219e12cb456abc130826468e4
rope/base/evaluate.py
python
eval_node2
(scope, node)
return evaluator.old_result, evaluator.result
[]
def eval_node2(scope, node): evaluator = StatementEvaluator(scope) ast.walk(node, evaluator) return evaluator.old_result, evaluator.result
[ "def", "eval_node2", "(", "scope", ",", "node", ")", ":", "evaluator", "=", "StatementEvaluator", "(", "scope", ")", "ast", ".", "walk", "(", "node", ",", "evaluator", ")", "return", "evaluator", ".", "old_result", ",", "evaluator", ".", "result" ]
https://github.com/fortharris/Pcode/blob/147962d160a834c219e12cb456abc130826468e4/rope/base/evaluate.py#L28-L31
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-linux/x64/mako/_ast_util.py
python
SourceGenerator.visit_BinOp
(self, node)
[]
def visit_BinOp(self, node): self.write("(") self.visit(node.left) self.write(" %s " % BINOP_SYMBOLS[type(node.op)]) self.visit(node.right) self.write(")")
[ "def", "visit_BinOp", "(", "self", ",", "node", ")", ":", "self", ".", "write", "(", "\"(\"", ")", "self", ".", "visit", "(", "node", ".", "left", ")", "self", ".", "write", "(", "\" %s \"", "%", "BINOP_SYMBOLS", "[", "type", "(", "node", ".", "op"...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/mako/_ast_util.py#L580-L585
CLUEbenchmark/CLUE
5bd39732734afecb490cf18a5212e692dbf2c007
baselines/models/bert/run_classifier.py
python
model_fn_builder
(bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_tpu, use_one_hot_embeddings)
return model_fn
Returns `model_fn` closure for TPUEstimator.
Returns `model_fn` closure for TPUEstimator.
[ "Returns", "model_fn", "closure", "for", "TPUEstimator", "." ]
def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_tpu, use_one_hot_embeddings): """Returns `model_fn` closure for TPUEstimator.""" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument """The `model_fn` for TPUEstimator.""" tf.logging.info("*** Features ***") for name in sorted(features.keys()): tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape)) input_ids = features["input_ids"] input_mask = features["input_mask"] segment_ids = features["segment_ids"] label_ids = features["label_ids"] is_real_example = None if "is_real_example" in features: is_real_example = tf.cast(features["is_real_example"], dtype=tf.float32) else: is_real_example = tf.ones(tf.shape(label_ids), dtype=tf.float32) is_training = (mode == tf.estimator.ModeKeys.TRAIN) (total_loss, per_example_loss, logits, probabilities) = create_model( bert_config, is_training, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() initialized_variable_names = {} scaffold_fn = None if init_checkpoint: (assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) if use_tpu: def tpu_scaffold(): tf.train.init_from_checkpoint(init_checkpoint, assignment_map) return tf.train.Scaffold() scaffold_fn = tpu_scaffold else: tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf.logging.info("**** Trainable Variables ****") for var in tvars: init_string = "" if var.name in initialized_variable_names: init_string = ", *INIT_FROM_CKPT*" tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape, init_string) output_spec = None if mode == tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu) output_spec = tf.contrib.tpu.TPUEstimatorSpec( mode=mode, loss=total_loss, train_op=train_op, scaffold_fn=scaffold_fn) elif mode == tf.estimator.ModeKeys.EVAL: def metric_fn(per_example_loss, label_ids, logits, is_real_example): predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions, weights=is_real_example) loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example) return { "eval_accuracy": accuracy, "eval_loss": loss, } eval_metrics = (metric_fn, [per_example_loss, label_ids, logits, is_real_example]) output_spec = tf.contrib.tpu.TPUEstimatorSpec( mode=mode, loss=total_loss, eval_metrics=eval_metrics, scaffold_fn=scaffold_fn) else: output_spec = tf.contrib.tpu.TPUEstimatorSpec( mode=mode, predictions={"probabilities": probabilities}, scaffold_fn=scaffold_fn) return output_spec return model_fn
[ "def", "model_fn_builder", "(", "bert_config", ",", "num_labels", ",", "init_checkpoint", ",", "learning_rate", ",", "num_train_steps", ",", "num_warmup_steps", ",", "use_tpu", ",", "use_one_hot_embeddings", ")", ":", "def", "model_fn", "(", "features", ",", "labels...
https://github.com/CLUEbenchmark/CLUE/blob/5bd39732734afecb490cf18a5212e692dbf2c007/baselines/models/bert/run_classifier.py#L547-L636
great-expectations/great_expectations
45224cb890aeae725af25905923d0dbbab2d969d
great_expectations/_version.py
python
render_pep440_old
(pieces)
return rendered
TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0]
TAG[.postDISTANCE[.dev0]] .
[ "TAG", "[", ".", "postDISTANCE", "[", ".", "dev0", "]]", "." ]
def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered
[ "def", "render_pep440_old", "(", "pieces", ")", ":", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "if", "pieces", "[", "\"distance\"", "]", "or", "pieces", "[", "\"dirty\"", "]", ":", "rendered", ...
https://github.com/great-expectations/great_expectations/blob/45224cb890aeae725af25905923d0dbbab2d969d/great_expectations/_version.py#L407-L426
CGATOxford/cgat
326aad4694bdfae8ddc194171bb5d73911243947
CGAT/Timeseries/__init__.py
python
drawVennDiagram
(deg_dict, header, out_dir)
Take a dictionary of gene IDs, with keys corresponding to timepoints/differential expression analyses and generate a Venn diagram. Maximum of 5 overlapping sets possible using R package:: VennDiagram.
Take a dictionary of gene IDs, with keys corresponding to timepoints/differential expression analyses and generate a Venn diagram. Maximum of 5 overlapping sets possible using R package:: VennDiagram.
[ "Take", "a", "dictionary", "of", "gene", "IDs", "with", "keys", "corresponding", "to", "timepoints", "/", "differential", "expression", "analyses", "and", "generate", "a", "Venn", "diagram", ".", "Maximum", "of", "5", "overlapping", "sets", "possible", "using", ...
def drawVennDiagram(deg_dict, header, out_dir): ''' Take a dictionary of gene IDs, with keys corresponding to timepoints/differential expression analyses and generate a Venn diagram. Maximum of 5 overlapping sets possible using R package:: VennDiagram. ''' keys = deg_dict.keys() try: keys = sorted(keys, key=lambda x: int(x.split("_")[1].rstrip("-time"))) except IndexError: pass venn_size = len(keys) R('''suppressPackageStartupMessages(library("VennDiagram"))''') n1 = set(deg_dict[keys[0]]) n2 = set(deg_dict[keys[1]]) area1 = len(n1) area2 = len(n2) n12 = len(n1.intersection(n2)) # for Venn > 2 sets if venn_size == 3: n3 = set(deg_dict[keys[2]]) area3 = len(n3) n13 = len(n1.intersection(n3)) n23 = len(n2.intersection(n3)) n123 = len((n1.intersection(n2)).intersection(n3)) cat1, cat2, cat3 = keys R('''png("%(out_dir)s/%(header)s-venn.png", ''' '''width=480, height=480)''' % locals()) R('''draw.triple.venn(%(area1)d, %(area2)d, %(area3)d, ''' '''%(n12)d, %(n23)d, %(n13)d, %(n123)d, ''' '''c('%(cat1)s', '%(cat2)s', '%(cat3)s'), ''' '''col=c('red', 'yellow', 'skyblue'), ''' '''fill=c('red', 'yellow', 'skyblue'), ''' '''margin=0.05, alpha=0.5)''' % locals()) R('''dev.off()''') elif venn_size == 4: n3 = set(deg_dict[keys[2]]) area3 = len(n3) n13 = len(n1.intersection(n3)) n23 = len(n2.intersection(n3)) n123 = len((n1.intersection(n2)).intersection(n3)) n4 = set(deg_dict[keys[3]]) area4 = len(n4) n14 = len(n1.intersection(n4)) n24 = len(n2.intersection(n4)) n34 = len(n3.intersection(n4)) n124 = len((n1.intersection(n2)).intersection(n4)) n134 = len((n1.intersection(n3)).intersection(n4)) n234 = len((n2.intersection(n3)).intersection(n4)) n1234 = len(((n1.intersection(n2)).intersection(n3)).intersection(n4)) cat1, cat2, cat3, cat4 = keys R('''png("%(out_dir)s/%(header)s-venn.png",''' '''width=480, height=480)''' % locals()) R('''draw.quad.venn(%(area1)d, %(area2)d, %(area3)d, %(area4)d,''' '''%(n12)d, %(n13)d, %(n14)d, %(n23)d, %(n24)d, %(n34)d,''' '''%(n123)d, %(n124)d, %(n134)d, %(n234)d, %(n1234)d,''' '''c('%(cat1)s', '%(cat2)s', '%(cat3)s', '%(cat4)s'), ''' '''col=c("red", "yellow", "skyblue", "orange"), ''' '''fill=c("red", "yellow", "skyblue", "orange"), ''' '''margin=0.05, alpha=0.5)''' % locals()) R('''dev.off()''') elif venn_size == 5: n3 = set(deg_dict[keys[2]]) area3 = len(n3) n13 = len(n1.intersection(n3)) n23 = len(n2.intersection(n3)) n123 = len((n1.intersection(n2)).intersection(n3)) n4 = set(deg_dict[keys[3]]) area4 = len(n4) n14 = len(n1.intersection(n4)) n24 = len(n2.intersection(n4)) n34 = len(n3.intersection(n4)) n124 = len((n1.intersection(n2)).intersection(n4)) n134 = len((n1.intersection(n3)).intersection(n4)) n234 = len((n2.intersection(n3)).intersection(n4)) n1234 = len(((n1.intersection(n2)).intersection(n3)).intersection(n4)) n5 = set(deg_dict[keys[4]]) area5 = len(n5) n15 = len(n1.intersection(n5)) n25 = len(n2.intersection(n5)) n35 = len(n3.intersection(n5)) n45 = len(n4.intersection(n5)) n125 = len((n1.intersection(n2)).intersection(n5)) n135 = len((n1.intersection(n3)).intersection(n5)) n145 = len((n1.intersection(n4)).intersection(n5)) n235 = len((n2.intersection(n3)).intersection(n5)) n245 = len((n2.intersection(n4)).intersection(n5)) n345 = len((n3.intersection(n4)).intersection(n5)) n1235 = len(((n1.intersection(n2)).intersection(n3)).intersection(n5)) n1245 = len(((n1.intersection(n2)).intersection(n4)).intersection(n5)) n1345 = len(((n1.intersection(n3)).intersection(n4)).intersection(n5)) n2345 = len(((n2.intersection(n3)).intersection(n4)).intersection(n5)) nstep = ((n1.intersection(n2)).intersection(n3)) n12345 = len((nstep.intersection(n4)).intersection(n5)) cat1, cat2, cat3, cat4, cat5 = keys R('''png("%(out_dir)s/%(header)s-venn.png", ''' '''height=480, width=480)''' % locals()) R('''draw.quintuple.venn(%(area1)d, %(area2)d, %(area3)d, ''' '''%(area4)d, %(area5)d, %(n12)d, %(n13)d, %(n14)d,''' '''%(n15)d, %(n23)d, %(n24)d, %(n25)d, %(n34)d, %(n35)d,''' '''%(n45)d, %(n123)d, %(n124)d, %(n125)d, %(n134)d,''' '''%(n135)d, %(n145)d, %(n234)d, %(n235)d, %(n245)d,''' '''%(n345)d, %(n1234)d, %(n1235)d, %(n1245)d, %(n1345)d,''' '''%(n2345)d, %(n12345)d, ''' '''c('%(cat1)s', '%(cat2)s', '%(cat3)s', '%(cat4)s', '%(cat5)s'),''' '''col=c("red", "yellow", "skyblue", "orange", "purple"),''' '''fill=c("red", "yellow", "skyblue", "orange", "purple"),''' '''alpha=0.05, margin=0.05, cex=rep(0.8, 31))''' % locals()) R('''dev.off()''') elif venn_size > 5: raise ValueError("Illegal venn diagram size, must be <= 5")
[ "def", "drawVennDiagram", "(", "deg_dict", ",", "header", ",", "out_dir", ")", ":", "keys", "=", "deg_dict", ".", "keys", "(", ")", "try", ":", "keys", "=", "sorted", "(", "keys", ",", "key", "=", "lambda", "x", ":", "int", "(", "x", ".", "split", ...
https://github.com/CGATOxford/cgat/blob/326aad4694bdfae8ddc194171bb5d73911243947/CGAT/Timeseries/__init__.py#L686-L809
lad1337/XDM
0c1b7009fe00f06f102a6f67c793478f515e7efe
site-packages/logilab/astng/rebuilder.py
python
TreeRebuilder.visit_tryfinally
(self, node, parent)
return newnode
visit a TryFinally node by returning a fresh instance of it
visit a TryFinally node by returning a fresh instance of it
[ "visit", "a", "TryFinally", "node", "by", "returning", "a", "fresh", "instance", "of", "it" ]
def visit_tryfinally(self, node, parent): """visit a TryFinally node by returning a fresh instance of it""" newnode = new.TryFinally() _lineno_parent(node, newnode, parent) newnode.body = [self.visit(child, newnode) for child in node.body] newnode.finalbody = [self.visit(n, newnode) for n in node.finalbody] newnode.set_line_info(newnode.last_child()) return newnode
[ "def", "visit_tryfinally", "(", "self", ",", "node", ",", "parent", ")", ":", "newnode", "=", "new", ".", "TryFinally", "(", ")", "_lineno_parent", "(", "node", ",", "newnode", ",", "parent", ")", "newnode", ".", "body", "=", "[", "self", ".", "visit",...
https://github.com/lad1337/XDM/blob/0c1b7009fe00f06f102a6f67c793478f515e7efe/site-packages/logilab/astng/rebuilder.py#L752-L759
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/djangosaml2-0.16.11/djangosaml2/views.py
python
metadata
(request, config_loader_path=None, valid_for=None)
return HttpResponse(content=text_type(metadata).encode('utf-8'), content_type="text/xml; charset=utf8")
Returns an XML with the SAML 2.0 metadata for this SP as configured in the settings.py file.
Returns an XML with the SAML 2.0 metadata for this SP as configured in the settings.py file.
[ "Returns", "an", "XML", "with", "the", "SAML", "2", ".", "0", "metadata", "for", "this", "SP", "as", "configured", "in", "the", "settings", ".", "py", "file", "." ]
def metadata(request, config_loader_path=None, valid_for=None): """Returns an XML with the SAML 2.0 metadata for this SP as configured in the settings.py file. """ conf = get_config(config_loader_path, request) metadata = entity_descriptor(conf) return HttpResponse(content=text_type(metadata).encode('utf-8'), content_type="text/xml; charset=utf8")
[ "def", "metadata", "(", "request", ",", "config_loader_path", "=", "None", ",", "valid_for", "=", "None", ")", ":", "conf", "=", "get_config", "(", "config_loader_path", ",", "request", ")", "metadata", "=", "entity_descriptor", "(", "conf", ")", "return", "...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/djangosaml2-0.16.11/djangosaml2/views.py#L473-L480
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
python/fate_arch/federation/pulsar/_federation.py
python
Federation.remote
( self, v, name: str, tag: str, parties: typing.List[Party], gc: GarbageCollectionABC, )
[]
def remote( self, v, name: str, tag: str, parties: typing.List[Party], gc: GarbageCollectionABC, ) -> typing.NoReturn: log_str = f"[pulsar.remote](name={name}, tag={tag}, parties={parties})" _name_dtype_keys = [ _SPLIT_.join([party.role, party.party_id, name, tag, "remote"]) for party in parties ] # tell the receiver what sender is going to send. if _name_dtype_keys[0] not in self._name_dtype_map: party_topic_infos = self._get_party_topic_infos( parties, dtype=NAME_DTYPE_TAG ) channel_infos = self._get_channels( party_topic_infos=party_topic_infos) if isinstance(v, Table): body = {"dtype": FederationDataType.TABLE, "partitions": v.partitions} else: body = {"dtype": FederationDataType.OBJECT} LOGGER.debug( f"[pulsar.remote] _name_dtype_keys: {_name_dtype_keys}, dtype: {body}" ) self._send_obj( name=name, tag=_SPLIT_.join([tag, NAME_DTYPE_TAG]), data=p_dumps(body), channel_infos=channel_infos, ) for k in _name_dtype_keys: if k not in self._name_dtype_map: self._name_dtype_map[k] = body if isinstance(v, Table): total_size = v.count() partitions = v.partitions LOGGER.debug( f"[{log_str}]start to remote RDD, total_size={total_size}, partitions={partitions}" ) party_topic_infos = self._get_party_topic_infos( parties, name, partitions=partitions ) # add gc gc.add_gc_action(tag, v, "__del__", {}) send_func = self._get_partition_send_func( name, tag, partitions, party_topic_infos, mq=self._mq, maximun_message_size=self._max_message_size, conf=self._pulsar_manager.runtime_config, ) # noinspection PyProtectedMember v._rdd.mapPartitionsWithIndex(send_func).count() else: LOGGER.debug(f"[{log_str}]start to remote obj") party_topic_infos = self._get_party_topic_infos(parties, name) channel_infos = self._get_channels( party_topic_infos=party_topic_infos) self._send_obj( name=name, tag=tag, data=p_dumps(v), channel_infos=channel_infos ) LOGGER.debug(f"[{log_str}]finish to remote")
[ "def", "remote", "(", "self", ",", "v", ",", "name", ":", "str", ",", "tag", ":", "str", ",", "parties", ":", "typing", ".", "List", "[", "Party", "]", ",", "gc", ":", "GarbageCollectionABC", ",", ")", "->", "typing", ".", "NoReturn", ":", "log_str...
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/fate_arch/federation/pulsar/_federation.py#L249-L325
GiulioRossetti/cdlib
b2c6311b99725bb2b029556f531d244a2af14a2a
cdlib/algorithms/crisp_partition.py
python
agdl
(g_original: object, number_communities: int, kc: int)
return NodeClustering( coms, g_original, "AGDL", method_parameters={"number_communities": number_communities, "kc": kc}, )
AGDL is a graph-based agglomerative algorithm, for clustering high-dimensional data. The algorithm uses the indegree and outdegree to characterize the affinity between two clusters. **Supported Graph Types** ========== ======== ======== Undirected Directed Weighted ========== ======== ======== Yes Yes Yes ========== ======== ======== :param g_original: a networkx/igraph object :param number_communities: number of communities :param kc: size of the neighbor set for each cluster :return: NodeClustering object :Example: >>> from cdlib import algorithms >>> import networkx as nx >>> G = nx.karate_club_graph() >>> com = algorithms.agdl(g, number_communities=3, kc=4) :References: Zhang, W., Wang, X., Zhao, D., & Tang, X. (2012, October). `Graph degree linkage: Agglomerative clustering on a directed graph. <https://link.springer.com/chapter/10.1007/978-3-642-33718-5_31/>`_ In European Conference on Computer Vision (pp. 428-441). Springer, Berlin, Heidelberg. .. note:: Reference implementation: https://github.com/myungjoon/GDL
AGDL is a graph-based agglomerative algorithm, for clustering high-dimensional data. The algorithm uses the indegree and outdegree to characterize the affinity between two clusters.
[ "AGDL", "is", "a", "graph", "-", "based", "agglomerative", "algorithm", "for", "clustering", "high", "-", "dimensional", "data", ".", "The", "algorithm", "uses", "the", "indegree", "and", "outdegree", "to", "characterize", "the", "affinity", "between", "two", ...
def agdl(g_original: object, number_communities: int, kc: int) -> NodeClustering: """ AGDL is a graph-based agglomerative algorithm, for clustering high-dimensional data. The algorithm uses the indegree and outdegree to characterize the affinity between two clusters. **Supported Graph Types** ========== ======== ======== Undirected Directed Weighted ========== ======== ======== Yes Yes Yes ========== ======== ======== :param g_original: a networkx/igraph object :param number_communities: number of communities :param kc: size of the neighbor set for each cluster :return: NodeClustering object :Example: >>> from cdlib import algorithms >>> import networkx as nx >>> G = nx.karate_club_graph() >>> com = algorithms.agdl(g, number_communities=3, kc=4) :References: Zhang, W., Wang, X., Zhao, D., & Tang, X. (2012, October). `Graph degree linkage: Agglomerative clustering on a directed graph. <https://link.springer.com/chapter/10.1007/978-3-642-33718-5_31/>`_ In European Conference on Computer Vision (pp. 428-441). Springer, Berlin, Heidelberg. .. note:: Reference implementation: https://github.com/myungjoon/GDL """ g = convert_graph_formats(g_original, nx.Graph) communities = Agdl(g, number_communities, kc) nodes = {k: v for k, v in enumerate(g.nodes())} coms = [] for com in communities: coms.append([nodes[n] for n in com]) return NodeClustering( coms, g_original, "AGDL", method_parameters={"number_communities": number_communities, "kc": kc}, )
[ "def", "agdl", "(", "g_original", ":", "object", ",", "number_communities", ":", "int", ",", "kc", ":", "int", ")", "->", "NodeClustering", ":", "g", "=", "convert_graph_formats", "(", "g_original", ",", "nx", ".", "Graph", ")", "communities", "=", "Agdl",...
https://github.com/GiulioRossetti/cdlib/blob/b2c6311b99725bb2b029556f531d244a2af14a2a/cdlib/algorithms/crisp_partition.py#L416-L462
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/PIL/TiffImagePlugin.py
python
ImageFileDirectory_v2.write_string
(self, value)
return b"" + value.encode('ascii', 'replace') + b"\0"
[]
def write_string(self, value): # remerge of https://github.com/python-pillow/Pillow/pull/1416 if sys.version_info[0] == 2: value = value.decode('ascii', 'replace') return b"" + value.encode('ascii', 'replace') + b"\0"
[ "def", "write_string", "(", "self", ",", "value", ")", ":", "# remerge of https://github.com/python-pillow/Pillow/pull/1416", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2", ":", "value", "=", "value", ".", "decode", "(", "'ascii'", ",", "'replace'",...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/PIL/TiffImagePlugin.py#L640-L644
sentinel-hub/sentinelhub-py
d7ad283cf9d4bd4c8c1a8b169cdbe37c5bc8208a
sentinelhub/time_utils.py
python
is_valid_time
(time)
Check if input string represents a valid time/date stamp :param time: a string containing a time/date stamp :type time: str :return: `True` is string is a valid time/date stamp, `False` otherwise :rtype: bool
Check if input string represents a valid time/date stamp
[ "Check", "if", "input", "string", "represents", "a", "valid", "time", "/", "date", "stamp" ]
def is_valid_time(time): """ Check if input string represents a valid time/date stamp :param time: a string containing a time/date stamp :type time: str :return: `True` is string is a valid time/date stamp, `False` otherwise :rtype: bool """ try: dateutil.parser.parse(time) return True except dateutil.parser.ParserError: return False
[ "def", "is_valid_time", "(", "time", ")", ":", "try", ":", "dateutil", ".", "parser", ".", "parse", "(", "time", ")", "return", "True", "except", "dateutil", ".", "parser", ".", "ParserError", ":", "return", "False" ]
https://github.com/sentinel-hub/sentinelhub-py/blob/d7ad283cf9d4bd4c8c1a8b169cdbe37c5bc8208a/sentinelhub/time_utils.py#L10-L22
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/template/engine.py
python
Engine.template_context_processors
(self)
return tuple(import_string(path) for path in context_processors)
[]
def template_context_processors(self): context_processors = _builtin_context_processors context_processors += tuple(self.context_processors) return tuple(import_string(path) for path in context_processors)
[ "def", "template_context_processors", "(", "self", ")", ":", "context_processors", "=", "_builtin_context_processors", "context_processors", "+=", "tuple", "(", "self", ".", "context_processors", ")", "return", "tuple", "(", "import_string", "(", "path", ")", "for", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/template/engine.py#L88-L91
ppizarror/pygame-menu
da5827a1ad0686e8ff2aa536b74bbfba73967bcf
pygame_menu/widgets/core/selection.py
python
Selection.copy
(self)
return copy.deepcopy(self)
Creates a deep copy of the object. :return: Copied selection effect
Creates a deep copy of the object.
[ "Creates", "a", "deep", "copy", "of", "the", "object", "." ]
def copy(self) -> 'Selection': """ Creates a deep copy of the object. :return: Copied selection effect """ return copy.deepcopy(self)
[ "def", "copy", "(", "self", ")", "->", "'Selection'", ":", "return", "copy", ".", "deepcopy", "(", "self", ")" ]
https://github.com/ppizarror/pygame-menu/blob/da5827a1ad0686e8ff2aa536b74bbfba73967bcf/pygame_menu/widgets/core/selection.py#L94-L100
Theano/Theano
8fd9203edfeecebced9344b0c70193be292a9ade
theano/gradient.py
python
consider_constant
(x)
return consider_constant_(x)
DEPRECATED: use zero_grad() or disconnected_grad() instead. Consider an expression constant when computing gradients. The expression itself is unaffected, but when its gradient is computed, or the gradient of another expression that this expression is a subexpression of, it will not be backpropagated through. In other words, the gradient of the expression is truncated to 0. :param x: A Theano expression whose gradient should be truncated. :return: The expression is returned unmodified, but its gradient is now truncated to 0. .. versionadded:: 0.7
DEPRECATED: use zero_grad() or disconnected_grad() instead.
[ "DEPRECATED", ":", "use", "zero_grad", "()", "or", "disconnected_grad", "()", "instead", "." ]
def consider_constant(x): """ DEPRECATED: use zero_grad() or disconnected_grad() instead. Consider an expression constant when computing gradients. The expression itself is unaffected, but when its gradient is computed, or the gradient of another expression that this expression is a subexpression of, it will not be backpropagated through. In other words, the gradient of the expression is truncated to 0. :param x: A Theano expression whose gradient should be truncated. :return: The expression is returned unmodified, but its gradient is now truncated to 0. .. versionadded:: 0.7 """ warnings.warn(( "consider_constant() is deprecated, use zero_grad() or " "disconnected_grad() instead."), stacklevel=3) return consider_constant_(x)
[ "def", "consider_constant", "(", "x", ")", ":", "warnings", ".", "warn", "(", "(", "\"consider_constant() is deprecated, use zero_grad() or \"", "\"disconnected_grad() instead.\"", ")", ",", "stacklevel", "=", "3", ")", "return", "consider_constant_", "(", "x", ")" ]
https://github.com/Theano/Theano/blob/8fd9203edfeecebced9344b0c70193be292a9ade/theano/gradient.py#L2031-L2054
facebookresearch/SpanBERT
0670d8b6a38f6714b85ea7a033f16bd8cc162676
pretraining/fairseq/data/no_nsp_span_bert_dataset.py
python
NoNSPSpanBertDataset.get_dummy_batch
(self, num_tokens, max_positions, tgt_len=12)
return self.collater([ { 'id': i, 'source': source, 'segment_labels': segment_labels, 'lm_target': lm_target, 'pair_targets': pair_targets } for i in range(bsz) ])
Return a dummy batch with a given number of tokens.
Return a dummy batch with a given number of tokens.
[ "Return", "a", "dummy", "batch", "with", "a", "given", "number", "of", "tokens", "." ]
def get_dummy_batch(self, num_tokens, max_positions, tgt_len=12): """Return a dummy batch with a given number of tokens.""" if isinstance(max_positions, float) or isinstance(max_positions, int): tgt_len = min(tgt_len, max_positions) source = self.vocab.dummy_sentence(tgt_len) segment_labels = torch.zeros(tgt_len, dtype=torch.long) pair_targets = torch.zeros((1, self.args.max_pair_targets + 2), dtype=torch.long) lm_target = source bsz = num_tokens // tgt_len return self.collater([ { 'id': i, 'source': source, 'segment_labels': segment_labels, 'lm_target': lm_target, 'pair_targets': pair_targets } for i in range(bsz) ])
[ "def", "get_dummy_batch", "(", "self", ",", "num_tokens", ",", "max_positions", ",", "tgt_len", "=", "12", ")", ":", "if", "isinstance", "(", "max_positions", ",", "float", ")", "or", "isinstance", "(", "max_positions", ",", "int", ")", ":", "tgt_len", "="...
https://github.com/facebookresearch/SpanBERT/blob/0670d8b6a38f6714b85ea7a033f16bd8cc162676/pretraining/fairseq/data/no_nsp_span_bert_dataset.py#L212-L231
peterbrittain/asciimatics
9a490faddf484ee5b9b845316f921f5888b23b18
asciimatics/utilities.py
python
BoxTool.style
(self)
return self._style
The line drawing style used to draw boxes. Possible styles are set in :mod:`asciimatics.constants`. :param style: One of ``ASCII_LINE``, ``SINGLE_LINE``, or ``DOUBLE_LINE``
The line drawing style used to draw boxes. Possible styles are set in :mod:`asciimatics.constants`.
[ "The", "line", "drawing", "style", "used", "to", "draw", "boxes", ".", "Possible", "styles", "are", "set", "in", ":", "mod", ":", "asciimatics", ".", "constants", "." ]
def style(self): """ The line drawing style used to draw boxes. Possible styles are set in :mod:`asciimatics.constants`. :param style: One of ``ASCII_LINE``, ``SINGLE_LINE``, or ``DOUBLE_LINE`` """ return self._style
[ "def", "style", "(", "self", ")", ":", "return", "self", ".", "_style" ]
https://github.com/peterbrittain/asciimatics/blob/9a490faddf484ee5b9b845316f921f5888b23b18/asciimatics/utilities.py#L100-L107
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/data/data_collator.py
python
numpy_default_data_collator
(features: List[InputDataClass])
return batch
[]
def numpy_default_data_collator(features: List[InputDataClass]) -> Dict[str, Any]: import numpy as np if not isinstance(features[0], (dict, BatchEncoding)): features = [vars(f) for f in features] first = features[0] batch = {} # Special handling for labels. # Ensure that tensor is created with the correct type # (it should be automatically the case, but let's make sure of it.) if "label" in first and first["label"] is not None: label = first["label"].item() if isinstance(first["label"], np.ndarray) else first["label"] dtype = np.int64 if isinstance(label, int) else np.float32 batch["labels"] = np.array([f["label"] for f in features], dtype=dtype) elif "label_ids" in first and first["label_ids"] is not None: if isinstance(first["label_ids"], np.ndarray): batch["labels"] = np.stack([f["label_ids"] for f in features]) else: dtype = np.int64 if type(first["label_ids"][0]) is int else np.float32 batch["labels"] = np.array([f["label_ids"] for f in features], dtype=dtype) # Handling of all other possible keys. # Again, we will use the first element to figure out which key/values are not None for this model. for k, v in first.items(): if k not in ("label", "label_ids") and v is not None and not isinstance(v, str): if isinstance(v, np.ndarray): batch[k] = np.stack([f[k] for f in features]) else: batch[k] = np.array([f[k] for f in features]) return batch
[ "def", "numpy_default_data_collator", "(", "features", ":", "List", "[", "InputDataClass", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "import", "numpy", "as", "np", "if", "not", "isinstance", "(", "features", "[", "0", "]", ",", "(", "di...
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/data/data_collator.py#L176-L207
rushter/MLAlgorithms
3c8e16b8de3baf131395ae57edd479e59566a7c6
mla/fm.py
python
FMRegressor.fit
(self, X, y=None)
[]
def fit(self, X, y=None): super(FMRegressor, self).fit(X, y) self.loss = mean_squared_error self.loss_grad = elementwise_grad(mean_squared_error)
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "super", "(", "FMRegressor", ",", "self", ")", ".", "fit", "(", "X", ",", "y", ")", "self", ".", "loss", "=", "mean_squared_error", "self", ".", "loss_grad", "=", "elementwise_gr...
https://github.com/rushter/MLAlgorithms/blob/3c8e16b8de3baf131395ae57edd479e59566a7c6/mla/fm.py#L64-L67
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Tools/gdb/libpython.py
python
PyUnicodeObjectPtr.proxyval
(self, visited)
return result
[]
def proxyval(self, visited): # From unicodeobject.h: # Py_ssize_t length; /* Length of raw Unicode data in buffer */ # Py_UNICODE *str; /* Raw Unicode buffer */ field_length = long(self.field('length')) field_str = self.field('str') # Gather a list of ints from the Py_UNICODE array; these are either # UCS-2 or UCS-4 code points: if self.char_width() > 2: Py_UNICODEs = [int(field_str[i]) for i in safe_range(field_length)] else: # A more elaborate routine if sizeof(Py_UNICODE) is 2 in the # inferior process: we must join surrogate pairs. Py_UNICODEs = [] i = 0 limit = safety_limit(field_length) while i < limit: ucs = int(field_str[i]) i += 1 if ucs < 0xD800 or ucs >= 0xDC00 or i == field_length: Py_UNICODEs.append(ucs) continue # This could be a surrogate pair. ucs2 = int(field_str[i]) if ucs2 < 0xDC00 or ucs2 > 0xDFFF: continue code = (ucs & 0x03FF) << 10 code |= ucs2 & 0x03FF code += 0x00010000 Py_UNICODEs.append(code) i += 1 # Convert the int code points to unicode characters, and generate a # local unicode instance. # This splits surrogate pairs if sizeof(Py_UNICODE) is 2 here (in gdb). result = u''.join([_unichr(ucs) for ucs in Py_UNICODEs]) return result
[ "def", "proxyval", "(", "self", ",", "visited", ")", ":", "# From unicodeobject.h:", "# Py_ssize_t length; /* Length of raw Unicode data in buffer */", "# Py_UNICODE *str; /* Raw Unicode buffer */", "field_length", "=", "long", "(", "self", ".", "field", "(", "'leng...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Tools/gdb/libpython.py#L1060-L1097
HonglinChu/SiamTrackers
8471660b14f970578a43f077b28207d44a27e867
SiamFCpp/SiamFCpp-video_analyst/siamfcpp/data/utils/filter_box.py
python
filter_unreasonable_training_boxes
(im: np.array, bbox, config: Dict)
return filter_flag
r""" Filter too small,too large objects and objects with extreme ratio No input check. Assume that all imput (im, bbox) are valid object Arguments --------- im: np.array image, formate=(H, W, C) bbox: np.array or indexable object bounding box annotation in (x, y, w, h) format
r""" Filter too small,too large objects and objects with extreme ratio No input check. Assume that all imput (im, bbox) are valid object
[ "r", "Filter", "too", "small", "too", "large", "objects", "and", "objects", "with", "extreme", "ratio", "No", "input", "check", ".", "Assume", "that", "all", "imput", "(", "im", "bbox", ")", "are", "valid", "object" ]
def filter_unreasonable_training_boxes(im: np.array, bbox, config: Dict) -> bool: r""" Filter too small,too large objects and objects with extreme ratio No input check. Assume that all imput (im, bbox) are valid object Arguments --------- im: np.array image, formate=(H, W, C) bbox: np.array or indexable object bounding box annotation in (x, y, w, h) format """ eps = 1e-6 im_area = im.shape[0] * im.shape[1] _, _, w, h = bbox bbox_area = w * h bbox_area_rate = bbox_area / im_area bbox_ratio = h / (w + eps) # valid trainng box condition conds = [(config["min_area_rate"] < bbox_area_rate, bbox_area_rate < config["max_area_rate"]), max(bbox_ratio, 1.0 / max(bbox_ratio, eps)) < config["max_ratio"]] # if not all conditions are satisfied, filter the sample filter_flag = not all(conds) return filter_flag
[ "def", "filter_unreasonable_training_boxes", "(", "im", ":", "np", ".", "array", ",", "bbox", ",", "config", ":", "Dict", ")", "->", "bool", ":", "eps", "=", "1e-6", "im_area", "=", "im", ".", "shape", "[", "0", "]", "*", "im", ".", "shape", "[", "...
https://github.com/HonglinChu/SiamTrackers/blob/8471660b14f970578a43f077b28207d44a27e867/SiamFCpp/SiamFCpp-video_analyst/siamfcpp/data/utils/filter_box.py#L9-L36
pypa/bandersnatch
2e3eb53029ddb8f205f85242d724ae492040c1ce
src/bandersnatch/mirror.py
python
BandersnatchMirror.process_package
(self, package: Package)
[]
async def process_package(self, package: Package) -> None: loop = asyncio.get_running_loop() # Don't save anything if our metadata filters all fail. if not package.filter_metadata(self.filters.filter_metadata_plugins()): return None # save the metadata before filtering releases # (dalley): why? the original author does not remember, and it doesn't seem # to make a lot of sense. # https://github.com/pypa/bandersnatch/commit/2a8cf8441b97f28eb817042a65a042d680fa527e#r39676370 if self.json_save: json_saved = await loop.run_in_executor( self.storage_backend.executor, self.save_json_metadata, package.metadata, package.name, ) assert json_saved package.filter_all_releases_files(self.filters.filter_release_file_plugins()) package.filter_all_releases(self.filters.filter_release_plugins()) if self.release_files_save: await self.sync_release_files(package) await loop.run_in_executor( self.storage_backend.executor, self.sync_simple_page, package ) # XMLRPC PyPI Endpoint stores raw_name so we need to provide it await loop.run_in_executor( self.storage_backend.executor, self.record_finished_package, package.raw_name, ) # Cleanup old legacy non PEP 503 Directories created for the Simple API await self.cleanup_non_pep_503_paths(package)
[ "async", "def", "process_package", "(", "self", ",", "package", ":", "Package", ")", "->", "None", ":", "loop", "=", "asyncio", ".", "get_running_loop", "(", ")", "# Don't save anything if our metadata filters all fail.", "if", "not", "package", ".", "filter_metadat...
https://github.com/pypa/bandersnatch/blob/2e3eb53029ddb8f205f85242d724ae492040c1ce/src/bandersnatch/mirror.py#L303-L339
Abjad/abjad
d0646dfbe83db3dc5ab268f76a0950712b87b7fd
abjad/makers.py
python
LeafMaker.tag
(self)
return self._tag
r""" Gets tag. .. container:: example Integer and string elements in ``pitches`` result in notes: >>> maker = abjad.LeafMaker(tag=abjad.Tag("leaf_maker")) >>> pitches = [2, 4, "F#5", "G#5"] >>> duration = abjad.Duration(1, 4) >>> leaves = maker(pitches, duration) >>> staff = abjad.Staff(leaves) >>> abjad.show(staff) # doctest: +SKIP .. docs:: >>> string = abjad.lilypond(staff, tags=True) >>> print(string) \new Staff { %! leaf_maker d'4 %! leaf_maker e'4 %! leaf_maker fs''4 %! leaf_maker gs''4 }
r""" Gets tag.
[ "r", "Gets", "tag", "." ]
def tag(self) -> typing.Optional[Tag]: r""" Gets tag. .. container:: example Integer and string elements in ``pitches`` result in notes: >>> maker = abjad.LeafMaker(tag=abjad.Tag("leaf_maker")) >>> pitches = [2, 4, "F#5", "G#5"] >>> duration = abjad.Duration(1, 4) >>> leaves = maker(pitches, duration) >>> staff = abjad.Staff(leaves) >>> abjad.show(staff) # doctest: +SKIP .. docs:: >>> string = abjad.lilypond(staff, tags=True) >>> print(string) \new Staff { %! leaf_maker d'4 %! leaf_maker e'4 %! leaf_maker fs''4 %! leaf_maker gs''4 } """ return self._tag
[ "def", "tag", "(", "self", ")", "->", "typing", ".", "Optional", "[", "Tag", "]", ":", "return", "self", ".", "_tag" ]
https://github.com/Abjad/abjad/blob/d0646dfbe83db3dc5ab268f76a0950712b87b7fd/abjad/makers.py#L717-L749
deepset-ai/haystack
79fdda8a7cf393d774803608a4874f2a6e63cf6f
haystack/document_stores/weaviate.py
python
WeaviateDocumentStore._check_document
(self, cur_props: List[str], doc: dict)
return [item for item in doc.keys() if item not in cur_props]
Find the properties in the document that don't exist in the existing schema.
Find the properties in the document that don't exist in the existing schema.
[ "Find", "the", "properties", "in", "the", "document", "that", "don", "t", "exist", "in", "the", "existing", "schema", "." ]
def _check_document(self, cur_props: List[str], doc: dict) -> List[str]: """ Find the properties in the document that don't exist in the existing schema. """ return [item for item in doc.keys() if item not in cur_props]
[ "def", "_check_document", "(", "self", ",", "cur_props", ":", "List", "[", "str", "]", ",", "doc", ":", "dict", ")", "->", "List", "[", "str", "]", ":", "return", "[", "item", "for", "item", "in", "doc", ".", "keys", "(", ")", "if", "item", "not"...
https://github.com/deepset-ai/haystack/blob/79fdda8a7cf393d774803608a4874f2a6e63cf6f/haystack/document_stores/weaviate.py#L367-L371
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
tools/find/ast.py
python
_links
(n_str)
return asdl.expr.StatTest(asdl.statAccessor_e.LinkCount, parse_number_predicate(n_str))
[]
def _links(n_str): return asdl.expr.StatTest(asdl.statAccessor_e.LinkCount, parse_number_predicate(n_str))
[ "def", "_links", "(", "n_str", ")", ":", "return", "asdl", ".", "expr", ".", "StatTest", "(", "asdl", ".", "statAccessor_e", ".", "LinkCount", ",", "parse_number_predicate", "(", "n_str", ")", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/tools/find/ast.py#L126-L127
tensorflow/estimator
edb6e18703a0fa00182bcc72a056da6f5ce45e70
tensorflow_estimator/python/estimator/canned/linear.py
python
_sdca_model_fn
(features, labels, mode, head, feature_columns, optimizer)
A model_fn for linear models that use the SDCA optimizer. Args: features: dict of `Tensor`. labels: `Tensor` of shape `[batch_size]`. mode: Defines whether this is training, evaluation or prediction. See `ModeKeys`. head: A `Head` instance. feature_columns: An iterable containing all the feature columns used by the model. optimizer: a `LinearSDCA` instance. Returns: An `EstimatorSpec` instance. Raises: ValueError: mode or params are invalid, or features has the wrong type.
A model_fn for linear models that use the SDCA optimizer.
[ "A", "model_fn", "for", "linear", "models", "that", "use", "the", "SDCA", "optimizer", "." ]
def _sdca_model_fn(features, labels, mode, head, feature_columns, optimizer): """A model_fn for linear models that use the SDCA optimizer. Args: features: dict of `Tensor`. labels: `Tensor` of shape `[batch_size]`. mode: Defines whether this is training, evaluation or prediction. See `ModeKeys`. head: A `Head` instance. feature_columns: An iterable containing all the feature columns used by the model. optimizer: a `LinearSDCA` instance. Returns: An `EstimatorSpec` instance. Raises: ValueError: mode or params are invalid, or features has the wrong type. """ assert feature_column_lib.is_feature_column_v2(feature_columns) if isinstance(head, (binary_class_head.BinaryClassHead, head_lib._BinaryLogisticHeadWithSigmoidCrossEntropyLoss)): # pylint: disable=protected-access loss_type = 'logistic_loss' elif isinstance(head, (regression_head.RegressionHead, head_lib._RegressionHeadWithMeanSquaredErrorLoss)): # pylint: disable=protected-access assert head.logits_dimension == 1 loss_type = 'squared_loss' else: raise ValueError('Unsupported head type: {}'.format(head)) # The default name for LinearModel. linear_model_name = 'linear_model' # Name scope has no effect on variables in LinearModel, as it uses # tf.get_variables() for variable creation. So we modify the model name to # keep the variable names the same for checkpoint backward compatibility in # canned Linear v2. if isinstance( head, (binary_class_head.BinaryClassHead, regression_head.RegressionHead)): linear_model_name = 'linear/linear_model' linear_model = LinearModel( feature_columns=feature_columns, units=1, sparse_combiner='sum', name=linear_model_name) logits = linear_model(features) # We'd like to get all the non-bias variables associated with this # LinearModel. # TODO(rohanj): Figure out how to get shared embedding weights variable # here. bias = linear_model.bias variables = linear_model.variables # Expand (potential) Partitioned variables bias = _get_expanded_variable_list([bias]) variables = _get_expanded_variable_list(variables) variables = [var for var in variables if var not in bias] tf.compat.v1.summary.scalar('bias', bias[0][0]) tf.compat.v1.summary.scalar('fraction_of_zero_weights', _compute_fraction_of_zero(variables)) if mode == ModeKeys.TRAIN: sdca_model, train_op = optimizer.get_train_step( linear_model.layer._state_manager, # pylint: disable=protected-access head._weight_column, # pylint: disable=protected-access loss_type, feature_columns, features, labels, linear_model.bias, tf.compat.v1.train.get_global_step()) update_weights_hook = _SDCAUpdateWeightsHook(sdca_model, train_op) model_fn_ops = head.create_estimator_spec( features=features, mode=mode, labels=labels, train_op_fn=lambda unused_loss_fn: train_op, logits=logits) return model_fn_ops._replace( training_chief_hooks=(model_fn_ops.training_chief_hooks + (update_weights_hook,))) else: return head.create_estimator_spec( features=features, mode=mode, labels=labels, logits=logits)
[ "def", "_sdca_model_fn", "(", "features", ",", "labels", ",", "mode", ",", "head", ",", "feature_columns", ",", "optimizer", ")", ":", "assert", "feature_column_lib", ".", "is_feature_column_v2", "(", "feature_columns", ")", "if", "isinstance", "(", "head", ",",...
https://github.com/tensorflow/estimator/blob/edb6e18703a0fa00182bcc72a056da6f5ce45e70/tensorflow_estimator/python/estimator/canned/linear.py#L450-L539
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/numpy/matrixlib/defmatrix.py
python
matrix.prod
(self, axis=None, dtype=None, out=None)
return N.ndarray.prod(self, axis, dtype, out, keepdims=True)._collapse(axis)
Return the product of the array elements over the given axis. Refer to `prod` for full documentation. See Also -------- prod, ndarray.prod Notes ----- Same as `ndarray.prod`, except, where that returns an `ndarray`, this returns a `matrix` object instead. Examples -------- >>> x = np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.prod() 0 >>> x.prod(0) matrix([[ 0, 45, 120, 231]]) >>> x.prod(1) matrix([[ 0], [ 840], [7920]])
Return the product of the array elements over the given axis.
[ "Return", "the", "product", "of", "the", "array", "elements", "over", "the", "given", "axis", "." ]
def prod(self, axis=None, dtype=None, out=None): """ Return the product of the array elements over the given axis. Refer to `prod` for full documentation. See Also -------- prod, ndarray.prod Notes ----- Same as `ndarray.prod`, except, where that returns an `ndarray`, this returns a `matrix` object instead. Examples -------- >>> x = np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.prod() 0 >>> x.prod(0) matrix([[ 0, 45, 120, 231]]) >>> x.prod(1) matrix([[ 0], [ 840], [7920]]) """ return N.ndarray.prod(self, axis, dtype, out, keepdims=True)._collapse(axis)
[ "def", "prod", "(", "self", ",", "axis", "=", "None", ",", "dtype", "=", "None", ",", "out", "=", "None", ")", ":", "return", "N", ".", "ndarray", ".", "prod", "(", "self", ",", "axis", ",", "dtype", ",", "out", ",", "keepdims", "=", "True", ")...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/numpy/matrixlib/defmatrix.py#L653-L684
zhirongw/lemniscate.pytorch
f7cfe298357cb2b169cd59eb540aca24bed1f9b8
lib/custom_transforms.py
python
RandomGaussianBlurring.__call__
(self, image)
return image
[]
def __call__(self, image): if isinstance(self.sigma, collections.Sequence): sigma = random_num_generator( self.sigma, random_state=self.random_state) else: sigma = self.sigma if random.random() < self.p: image = gaussian_filter(image, sigma=(sigma, sigma, 0)) return image
[ "def", "__call__", "(", "self", ",", "image", ")", ":", "if", "isinstance", "(", "self", ".", "sigma", ",", "collections", ".", "Sequence", ")", ":", "sigma", "=", "random_num_generator", "(", "self", ".", "sigma", ",", "random_state", "=", "self", ".", ...
https://github.com/zhirongw/lemniscate.pytorch/blob/f7cfe298357cb2b169cd59eb540aca24bed1f9b8/lib/custom_transforms.py#L227-L235
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/chart-studio/chart_studio/api/v2/dashboards.py
python
retrieve
(fid)
return request("get", url)
Retrieve a dashboard from Plotly.
Retrieve a dashboard from Plotly.
[ "Retrieve", "a", "dashboard", "from", "Plotly", "." ]
def retrieve(fid): """Retrieve a dashboard from Plotly.""" url = build_url(RESOURCE, id=fid) return request("get", url)
[ "def", "retrieve", "(", "fid", ")", ":", "url", "=", "build_url", "(", "RESOURCE", ",", "id", "=", "fid", ")", "return", "request", "(", "\"get\"", ",", "url", ")" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/chart-studio/chart_studio/api/v2/dashboards.py#L26-L29
modelop/hadrian
7c63e539d79e6e3cad959792d313dfc8b0c523ea
titus/titus/pfaast.py
python
SymbolTable.__call__
(self, name)
Get a symbol's type from this scope or a parent's and raise a ``KeyError`` if not defined :type name: string :param name: name of the symbol :rtype: titus.datatype.AvroType :return: the symbol's type if defined, raise a ``KeyError`` otherwise
Get a symbol's type from this scope or a parent's and raise a ``KeyError`` if not defined
[ "Get", "a", "symbol", "s", "type", "from", "this", "scope", "or", "a", "parent", "s", "and", "raise", "a", "KeyError", "if", "not", "defined" ]
def __call__(self, name): """Get a symbol's type from this scope or a parent's and raise a ``KeyError`` if not defined :type name: string :param name: name of the symbol :rtype: titus.datatype.AvroType :return: the symbol's type if defined, raise a ``KeyError`` otherwise """ out = self.get(name) if out is None: raise KeyError("no symbol named \"{0}\"".format(name)) else: return out
[ "def", "__call__", "(", "self", ",", "name", ")", ":", "out", "=", "self", ".", "get", "(", "name", ")", "if", "out", "is", "None", ":", "raise", "KeyError", "(", "\"no symbol named \\\"{0}\\\"\"", ".", "format", "(", "name", ")", ")", "else", ":", "...
https://github.com/modelop/hadrian/blob/7c63e539d79e6e3cad959792d313dfc8b0c523ea/titus/titus/pfaast.py#L181-L193
hubblestack/hubble
763142474edcecdec5fd25591dc29c3536e8f969
hubblestack/files/hubblestack_nova/misc.py
python
check_all_users_home_directory
(max_system_uid)
return True if not error else str(error)
Ensure all users' home directories exist
Ensure all users' home directories exist
[ "Ensure", "all", "users", "home", "directories", "exist" ]
def check_all_users_home_directory(max_system_uid): """ Ensure all users' home directories exist """ max_system_uid = int(max_system_uid) users_uids_dirs = _execute_shell_command("cat /etc/passwd | awk -F: '{ print $1 \" \" $3 \" \" $6 \" \" $7}'", python_shell=True).strip() users_uids_dirs = users_uids_dirs.split('\n') if users_uids_dirs else [] error = [] for user_data in users_uids_dirs: user_uid_dir = user_data.strip().split(" ") if len(user_uid_dir) < 4: user_uid_dir = user_uid_dir + [''] * (4 - len(user_uid_dir)) if user_uid_dir[1].isdigit(): if not _is_valid_home_directory(user_uid_dir[2], True) and int(user_uid_dir[1]) >= max_system_uid and user_uid_dir[0] != "nfsnobody" \ and 'nologin' not in user_uid_dir[3] and 'false' not in user_uid_dir[3]: error += ["Either home directory " + user_uid_dir[2] + " of user " + user_uid_dir[0] + " is invalid or does not exist."] else: error += ["User " + user_uid_dir[0] + " has invalid uid " + user_uid_dir[1]] return True if not error else str(error)
[ "def", "check_all_users_home_directory", "(", "max_system_uid", ")", ":", "max_system_uid", "=", "int", "(", "max_system_uid", ")", "users_uids_dirs", "=", "_execute_shell_command", "(", "\"cat /etc/passwd | awk -F: '{ print $1 \\\" \\\" $3 \\\" \\\" $6 \\\" \\\" $7}'\"", ",", "p...
https://github.com/hubblestack/hubble/blob/763142474edcecdec5fd25591dc29c3536e8f969/hubblestack/files/hubblestack_nova/misc.py#L593-L612
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
medusa/config.py
python
change_NZB_DIR
(nzb_dir)
return True
Change NZB Folder :param nzb_dir: New NZB Folder location :return: True on success, False on failure
Change NZB Folder
[ "Change", "NZB", "Folder" ]
def change_NZB_DIR(nzb_dir): """ Change NZB Folder :param nzb_dir: New NZB Folder location :return: True on success, False on failure """ if not nzb_dir: app._NZB_DIR = '' return True app_nzb_dir = os.path.normpath(app._NZB_DIR) if app._NZB_DIR else None if app_nzb_dir != os.path.normpath(nzb_dir): if helpers.make_dir(nzb_dir): app._NZB_DIR = os.path.normpath(nzb_dir) log.info(u'Changed NZB folder to {nzb_dir}', {'nzb_dir': nzb_dir}) else: return False return True
[ "def", "change_NZB_DIR", "(", "nzb_dir", ")", ":", "if", "not", "nzb_dir", ":", "app", ".", "_NZB_DIR", "=", "''", "return", "True", "app_nzb_dir", "=", "os", ".", "path", ".", "normpath", "(", "app", ".", "_NZB_DIR", ")", "if", "app", ".", "_NZB_DIR",...
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/medusa/config.py#L145-L165
baowenbo/DAIN
9d9c0d7b3718dfcda9061c85efec472478a3aa86
MegaDepth/util/png.py
python
encode
(buf, width, height)
return b''.join( [ SIGNATURE ] + chunk(b'IHDR', struct.pack("!2I5B", width, height, bit_depth, COLOR_TYPE_RGB, 0, 0, 0)) + chunk(b'IDAT', zlib.compress(b''.join(raw_data()), 9)) + chunk(b'IEND', b'') )
buf: must be bytes or a bytearray in py3, a regular string in py2. formatted RGBRGB...
buf: must be bytes or a bytearray in py3, a regular string in py2. formatted RGBRGB...
[ "buf", ":", "must", "be", "bytes", "or", "a", "bytearray", "in", "py3", "a", "regular", "string", "in", "py2", ".", "formatted", "RGBRGB", "..." ]
def encode(buf, width, height): """ buf: must be bytes or a bytearray in py3, a regular string in py2. formatted RGBRGB... """ assert (width * height * 3 == len(buf)) bpp = 3 def raw_data(): # reverse the vertical line order and add null bytes at the start row_bytes = width * bpp for row_start in range((height - 1) * width * bpp, -1, -row_bytes): yield b'\x00' yield buf[row_start:row_start + row_bytes] def chunk(tag, data): return [ struct.pack("!I", len(data)), tag, data, struct.pack("!I", 0xFFFFFFFF & zlib.crc32(data, zlib.crc32(tag))) ] SIGNATURE = b'\x89PNG\r\n\x1a\n' COLOR_TYPE_RGB = 2 COLOR_TYPE_RGBA = 6 bit_depth = 8 return b''.join( [ SIGNATURE ] + chunk(b'IHDR', struct.pack("!2I5B", width, height, bit_depth, COLOR_TYPE_RGB, 0, 0, 0)) + chunk(b'IDAT', zlib.compress(b''.join(raw_data()), 9)) + chunk(b'IEND', b'') )
[ "def", "encode", "(", "buf", ",", "width", ",", "height", ")", ":", "assert", "(", "width", "*", "height", "*", "3", "==", "len", "(", "buf", ")", ")", "bpp", "=", "3", "def", "raw_data", "(", ")", ":", "# reverse the vertical line order and add null byt...
https://github.com/baowenbo/DAIN/blob/9d9c0d7b3718dfcda9061c85efec472478a3aa86/MegaDepth/util/png.py#L4-L33
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_deployment_status.py
python
V1DeploymentStatus.ready_replicas
(self, ready_replicas)
Sets the ready_replicas of this V1DeploymentStatus. Total number of ready pods targeted by this deployment. # noqa: E501 :param ready_replicas: The ready_replicas of this V1DeploymentStatus. # noqa: E501 :type: int
Sets the ready_replicas of this V1DeploymentStatus.
[ "Sets", "the", "ready_replicas", "of", "this", "V1DeploymentStatus", "." ]
def ready_replicas(self, ready_replicas): """Sets the ready_replicas of this V1DeploymentStatus. Total number of ready pods targeted by this deployment. # noqa: E501 :param ready_replicas: The ready_replicas of this V1DeploymentStatus. # noqa: E501 :type: int """ self._ready_replicas = ready_replicas
[ "def", "ready_replicas", "(", "self", ",", "ready_replicas", ")", ":", "self", ".", "_ready_replicas", "=", "ready_replicas" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_deployment_status.py#L194-L203
suavecode/SUAVE
4f83c467c5662b6cc611ce2ab6c0bdd25fd5c0a5
trunk/SUAVE/Attributes/Gases/Air.py
python
Air.compute_absolute_viscosity
(self,T=300.,p=101325.)
return C1*(T**(1.5))/(T + S)
Compute the absolute (dynamic) viscosity Assumptions: Ideal gas Source: https://www.cfd-online.com/Wiki/Sutherland's_law Inputs: T [K] - Temperature Outputs: absolute viscosity [kg/(m-s)] Properties Used: None
Compute the absolute (dynamic) viscosity Assumptions: Ideal gas
[ "Compute", "the", "absolute", "(", "dynamic", ")", "viscosity", "Assumptions", ":", "Ideal", "gas" ]
def compute_absolute_viscosity(self,T=300.,p=101325.): """Compute the absolute (dynamic) viscosity Assumptions: Ideal gas Source: https://www.cfd-online.com/Wiki/Sutherland's_law Inputs: T [K] - Temperature Outputs: absolute viscosity [kg/(m-s)] Properties Used: None """ S = 110.4 # constant in deg K (Sutherland's Formula) C1 = 1.458e-6 # kg/m-s-sqrt(K), constant (Sutherland's Formula) return C1*(T**(1.5))/(T + S)
[ "def", "compute_absolute_viscosity", "(", "self", ",", "T", "=", "300.", ",", "p", "=", "101325.", ")", ":", "S", "=", "110.4", "# constant in deg K (Sutherland's Formula)", "C1", "=", "1.458e-6", "# kg/m-s-sqrt(K), constant (Sutherland's Formula)", "return", "C1", "*...
https://github.com/suavecode/SUAVE/blob/4f83c467c5662b6cc611ce2ab6c0bdd25fd5c0a5/trunk/SUAVE/Attributes/Gases/Air.py#L176-L198
deanishe/alfred-fixum
34cc2232789af5373befcffe8cd50536c88b20bf
src/workflow/workflow.py
python
Workflow.reset
(self)
Delete workflow settings, cache and data. File :attr:`settings <settings_path>` and directories :attr:`cache <cachedir>` and :attr:`data <datadir>` are deleted.
Delete workflow settings, cache and data.
[ "Delete", "workflow", "settings", "cache", "and", "data", "." ]
def reset(self): """Delete workflow settings, cache and data. File :attr:`settings <settings_path>` and directories :attr:`cache <cachedir>` and :attr:`data <datadir>` are deleted. """ self.clear_cache() self.clear_data() self.clear_settings()
[ "def", "reset", "(", "self", ")", ":", "self", ".", "clear_cache", "(", ")", "self", ".", "clear_data", "(", ")", "self", ".", "clear_settings", "(", ")" ]
https://github.com/deanishe/alfred-fixum/blob/34cc2232789af5373befcffe8cd50536c88b20bf/src/workflow/workflow.py#L2629-L2638
deepjyoti30/ytmdl
0227541f303739a01e27a6d74499229d9bf44f84
ytmdl/core.py
python
download
(link, yt_title, args)
return path
Download the song by using the passed link. The song will be saved with the passed title. Return the saved path of the song.
Download the song by using the passed link.
[ "Download", "the", "song", "by", "using", "the", "passed", "link", "." ]
def download(link, yt_title, args) -> str: """Download the song by using the passed link. The song will be saved with the passed title. Return the saved path of the song. """ logger.info('Downloading {}{}{} in {}{}kbps{}'.format( Fore.LIGHTMAGENTA_EX, yt_title, Style.RESET_ALL, Fore.LIGHTYELLOW_EX, defaults.DEFAULT.SONG_QUALITY, Style.RESET_ALL )) path = yt.dw(link, args.proxy, yt_title, args.format, no_progress=args.quiet) if type(path) is not str: # Probably an error occured raise DownloadError(link, path) logger.info('Downloaded!') return path
[ "def", "download", "(", "link", ",", "yt_title", ",", "args", ")", "->", "str", ":", "logger", ".", "info", "(", "'Downloading {}{}{} in {}{}kbps{}'", ".", "format", "(", "Fore", ".", "LIGHTMAGENTA_EX", ",", "yt_title", ",", "Style", ".", "RESET_ALL", ",", ...
https://github.com/deepjyoti30/ytmdl/blob/0227541f303739a01e27a6d74499229d9bf44f84/ytmdl/core.py#L103-L125
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/mailbox.py
python
_singlefileMailbox._post_message_hook
(self, f)
return
Called after writing each message to file f.
Called after writing each message to file f.
[ "Called", "after", "writing", "each", "message", "to", "file", "f", "." ]
def _post_message_hook(self, f): """Called after writing each message to file f.""" return
[ "def", "_post_message_hook", "(", "self", ",", "f", ")", ":", "return" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/mailbox.py#L684-L686
postgres/pgadmin4
374c5e952fa594d749fadf1f88076c1cba8c5f64
web/pgadmin/dashboard/__init__.py
python
config
(sid=None)
return get_data(sid, None, 'config.sql')
This function returns server config information :param sid: server id :return:
This function returns server config information :param sid: server id :return:
[ "This", "function", "returns", "server", "config", "information", ":", "param", "sid", ":", "server", "id", ":", "return", ":" ]
def config(sid=None): """ This function returns server config information :param sid: server id :return: """ return get_data(sid, None, 'config.sql')
[ "def", "config", "(", "sid", "=", "None", ")", ":", "return", "get_data", "(", "sid", ",", "None", ",", "'config.sql'", ")" ]
https://github.com/postgres/pgadmin4/blob/374c5e952fa594d749fadf1f88076c1cba8c5f64/web/pgadmin/dashboard/__init__.py#L463-L469
pypa/pip
7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4
src/pip/_vendor/distlib/locators.py
python
AggregatingLocator.__init__
(self, *locators, **kwargs)
Initialise an instance. :param locators: The list of locators to search. :param kwargs: Passed to the superclass constructor, except for: * merge - if False (the default), the first successful search from any of the locators is returned. If True, the results from all locators are merged (this can be slow).
Initialise an instance.
[ "Initialise", "an", "instance", "." ]
def __init__(self, *locators, **kwargs): """ Initialise an instance. :param locators: The list of locators to search. :param kwargs: Passed to the superclass constructor, except for: * merge - if False (the default), the first successful search from any of the locators is returned. If True, the results from all locators are merged (this can be slow). """ self.merge = kwargs.pop('merge', False) self.locators = locators super(AggregatingLocator, self).__init__(**kwargs)
[ "def", "__init__", "(", "self", ",", "*", "locators", ",", "*", "*", "kwargs", ")", ":", "self", ".", "merge", "=", "kwargs", ".", "pop", "(", "'merge'", ",", "False", ")", "self", ".", "locators", "=", "locators", "super", "(", "AggregatingLocator", ...
https://github.com/pypa/pip/blob/7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4/src/pip/_vendor/distlib/locators.py#L970-L984
youtify/youtify
82cbc4a4ca6283f14f7179d4aeba30ed1ee1fea8
dropbox/oauth.py
python
OAuthServer.authorize_token
(self, token, user)
return self.data_store.authorize_request_token(token, user)
Authorize a request token.
Authorize a request token.
[ "Authorize", "a", "request", "token", "." ]
def authorize_token(self, token, user): """Authorize a request token.""" return self.data_store.authorize_request_token(token, user)
[ "def", "authorize_token", "(", "self", ",", "token", ",", "user", ")", ":", "return", "self", ".", "data_store", ".", "authorize_request_token", "(", "token", ",", "user", ")" ]
https://github.com/youtify/youtify/blob/82cbc4a4ca6283f14f7179d4aeba30ed1ee1fea8/dropbox/oauth.py#L437-L439
ustayready/CredKing
68b612e4cdf01d2b65b14ab2869bb8a5531056ee
plugins/gmail/requests/cookies.py
python
RequestsCookieJar.__setstate__
(self, state)
Unlike a normal CookieJar, this class is pickleable.
Unlike a normal CookieJar, this class is pickleable.
[ "Unlike", "a", "normal", "CookieJar", "this", "class", "is", "pickleable", "." ]
def __setstate__(self, state): """Unlike a normal CookieJar, this class is pickleable.""" self.__dict__.update(state) if '_cookies_lock' not in self.__dict__: self._cookies_lock = threading.RLock()
[ "def", "__setstate__", "(", "self", ",", "state", ")", ":", "self", ".", "__dict__", ".", "update", "(", "state", ")", "if", "'_cookies_lock'", "not", "in", "self", ".", "__dict__", ":", "self", ".", "_cookies_lock", "=", "threading", ".", "RLock", "(", ...
https://github.com/ustayready/CredKing/blob/68b612e4cdf01d2b65b14ab2869bb8a5531056ee/plugins/gmail/requests/cookies.py#L409-L413
SebKuzminsky/pycam
55e3129f518e470040e79bb00515b4bfcf36c172
pycam/Utils/threading.py
python
ProcessStatistics.__init__
(self, timeout=120)
[]
def __init__(self, timeout=120): self.processes = {} self.queues = {} self.workers = {} self.timeout = timeout
[ "def", "__init__", "(", "self", ",", "timeout", "=", "120", ")", ":", "self", ".", "processes", "=", "{", "}", "self", ".", "queues", "=", "{", "}", "self", ".", "workers", "=", "{", "}", "self", ".", "timeout", "=", "timeout" ]
https://github.com/SebKuzminsky/pycam/blob/55e3129f518e470040e79bb00515b4bfcf36c172/pycam/Utils/threading.py#L691-L695
rigetti/pyquil
36987ecb78d5dc85d299dd62395b7669a1cedd5a
pyquil/api/_quantum_computer.py
python
QuantumComputer.qubit_topology
(self)
return self.compiler.quantum_processor.qubit_topology()
Return a NetworkX graph representation of this QuantumComputer's quantum_processor's qubit connectivity. See :py:func:`AbstractQuantumProcessor.qubit_topology` for more.
Return a NetworkX graph representation of this QuantumComputer's quantum_processor's qubit connectivity.
[ "Return", "a", "NetworkX", "graph", "representation", "of", "this", "QuantumComputer", "s", "quantum_processor", "s", "qubit", "connectivity", "." ]
def qubit_topology(self) -> nx.graph: """ Return a NetworkX graph representation of this QuantumComputer's quantum_processor's qubit connectivity. See :py:func:`AbstractQuantumProcessor.qubit_topology` for more. """ return self.compiler.quantum_processor.qubit_topology()
[ "def", "qubit_topology", "(", "self", ")", "->", "nx", ".", "graph", ":", "return", "self", ".", "compiler", ".", "quantum_processor", ".", "qubit_topology", "(", ")" ]
https://github.com/rigetti/pyquil/blob/36987ecb78d5dc85d299dd62395b7669a1cedd5a/pyquil/api/_quantum_computer.py#L117-L124
kdexd/virtex
2baba8a4f3a4d80d617b3bc59e4be25b1052db57
virtex/utils/metrics.py
python
TopkAccuracy.reset
(self)
r"""Reset counters; to be used at the start of new epoch/validation.
r"""Reset counters; to be used at the start of new epoch/validation.
[ "r", "Reset", "counters", ";", "to", "be", "used", "at", "the", "start", "of", "new", "epoch", "/", "validation", "." ]
def reset(self): r"""Reset counters; to be used at the start of new epoch/validation.""" self.num_total = 0.0 self.num_correct = 0.0
[ "def", "reset", "(", "self", ")", ":", "self", ".", "num_total", "=", "0.0", "self", ".", "num_correct", "=", "0.0" ]
https://github.com/kdexd/virtex/blob/2baba8a4f3a4d80d617b3bc59e4be25b1052db57/virtex/utils/metrics.py#L41-L44
polakowo/vectorbt
6638735c131655760474d72b9f045d1dbdbd8fe9
vectorbt/generic/nb.py
python
bshift_1d_nb
(a: tp.Array1d, n: int = 1, fill_value: tp.Scalar = np.nan)
return _bshift_1d_nb
Shift backward by `n` positions. Numba equivalent to `pd.Series(a).shift(n)`. !!! warning This operation looks ahead.
Shift backward by `n` positions.
[ "Shift", "backward", "by", "n", "positions", "." ]
def bshift_1d_nb(a: tp.Array1d, n: int = 1, fill_value: tp.Scalar = np.nan) -> tp.Array1d: """Shift backward by `n` positions. Numba equivalent to `pd.Series(a).shift(n)`. !!! warning This operation looks ahead.""" nb_enabled = not isinstance(a, np.ndarray) if nb_enabled: a_dtype = as_dtype(a.dtype) if isinstance(fill_value, Omitted): fill_value_dtype = np.asarray(fill_value.value).dtype else: fill_value_dtype = as_dtype(fill_value) else: a_dtype = a.dtype fill_value_dtype = np.array(fill_value).dtype dtype = np.promote_types(a_dtype, fill_value_dtype) def _bshift_1d_nb(a, n, fill_value): out = np.empty_like(a, dtype=dtype) out[-n:] = fill_value out[:-n] = a[n:] return out if not nb_enabled: return _bshift_1d_nb(a, n, fill_value) return _bshift_1d_nb
[ "def", "bshift_1d_nb", "(", "a", ":", "tp", ".", "Array1d", ",", "n", ":", "int", "=", "1", ",", "fill_value", ":", "tp", ".", "Scalar", "=", "np", ".", "nan", ")", "->", "tp", ".", "Array1d", ":", "nb_enabled", "=", "not", "isinstance", "(", "a"...
https://github.com/polakowo/vectorbt/blob/6638735c131655760474d72b9f045d1dbdbd8fe9/vectorbt/generic/nb.py#L173-L201
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/kubernetesmod.py
python
show_deployment
(name, namespace="default", **kwargs)
Return the kubernetes deployment defined by name and namespace CLI Example: .. code-block:: bash salt '*' kubernetes.show_deployment my-nginx default salt '*' kubernetes.show_deployment name=my-nginx namespace=default
Return the kubernetes deployment defined by name and namespace
[ "Return", "the", "kubernetes", "deployment", "defined", "by", "name", "and", "namespace" ]
def show_deployment(name, namespace="default", **kwargs): """ Return the kubernetes deployment defined by name and namespace CLI Example: .. code-block:: bash salt '*' kubernetes.show_deployment my-nginx default salt '*' kubernetes.show_deployment name=my-nginx namespace=default """ cfg = _setup_conn(**kwargs) try: api_instance = kubernetes.client.ExtensionsV1beta1Api() api_response = api_instance.read_namespaced_deployment(name, namespace) return api_response.to_dict() except (ApiException, HTTPError) as exc: if isinstance(exc, ApiException) and exc.status == 404: return None else: log.exception( "Exception when calling " "ExtensionsV1beta1Api->read_namespaced_deployment" ) raise CommandExecutionError(exc) finally: _cleanup(**cfg)
[ "def", "show_deployment", "(", "name", ",", "namespace", "=", "\"default\"", ",", "*", "*", "kwargs", ")", ":", "cfg", "=", "_setup_conn", "(", "*", "*", "kwargs", ")", "try", ":", "api_instance", "=", "kubernetes", ".", "client", ".", "ExtensionsV1beta1Ap...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/kubernetesmod.py#L597-L624
freewym/espresso
6671c507350295269e38add57dbe601dcb8e6ecf
espresso/data/asr_dataset.py
python
AsrDataset.collater
(self, samples, pad_to_length=None)
return res
Merge a list of samples to form a mini-batch. Args: samples (List[dict]): samples to collate pad_to_length (dict, optional): a dictionary of {"source": source_pad_to_length, "target": target_pad_to_length} to indicate the max length to pad to in source and target respectively. Returns: dict: a mini-batch with the following keys: - `id` (LongTensor): example IDs in the original input order - `utt_id` (List[str]): list of utterance ids - `nsentences` (int): batch size - `ntokens` (int): total number of tokens in the batch - `net_input` (dict): the input to the Model, containing keys: - `src_tokens` (FloatTensor): a padded 3D Tensor of features in the source of shape `(bsz, src_len, feat_dim)`. Padding will appear on the left if *left_pad_source* is ``True``. - `src_lengths` (IntTensor): 1D Tensor of the unpadded lengths of each source sequence of shape `(bsz)` - `prev_output_tokens` (LongTensor): a padded 2D Tensor of tokens in the target sentence, shifted right by one position for teacher forcing, of shape `(bsz, tgt_len)`. This key will not be present if *input_feeding* is ``False``. Padding will appear on the left if *left_pad_target* is ``True``. - `src_lang_id` (LongTensor): a long Tensor which contains source language IDs of each sample in the batch - `target` (LongTensor): a padded 2D Tensor of tokens in the target sentence of shape `(bsz, tgt_len)`. Padding will appear on the left if *left_pad_target* is ``True``. - `text` (List[str]): list of original text - `tgt_lang_id` (LongTensor): a long Tensor which contains target language IDs of each sample in the batch
Merge a list of samples to form a mini-batch.
[ "Merge", "a", "list", "of", "samples", "to", "form", "a", "mini", "-", "batch", "." ]
def collater(self, samples, pad_to_length=None): """Merge a list of samples to form a mini-batch. Args: samples (List[dict]): samples to collate pad_to_length (dict, optional): a dictionary of {"source": source_pad_to_length, "target": target_pad_to_length} to indicate the max length to pad to in source and target respectively. Returns: dict: a mini-batch with the following keys: - `id` (LongTensor): example IDs in the original input order - `utt_id` (List[str]): list of utterance ids - `nsentences` (int): batch size - `ntokens` (int): total number of tokens in the batch - `net_input` (dict): the input to the Model, containing keys: - `src_tokens` (FloatTensor): a padded 3D Tensor of features in the source of shape `(bsz, src_len, feat_dim)`. Padding will appear on the left if *left_pad_source* is ``True``. - `src_lengths` (IntTensor): 1D Tensor of the unpadded lengths of each source sequence of shape `(bsz)` - `prev_output_tokens` (LongTensor): a padded 2D Tensor of tokens in the target sentence, shifted right by one position for teacher forcing, of shape `(bsz, tgt_len)`. This key will not be present if *input_feeding* is ``False``. Padding will appear on the left if *left_pad_target* is ``True``. - `src_lang_id` (LongTensor): a long Tensor which contains source language IDs of each sample in the batch - `target` (LongTensor): a padded 2D Tensor of tokens in the target sentence of shape `(bsz, tgt_len)`. Padding will appear on the left if *left_pad_target* is ``True``. - `text` (List[str]): list of original text - `tgt_lang_id` (LongTensor): a long Tensor which contains target language IDs of each sample in the batch """ res = collate( samples, pad_idx=self.dictionary.pad(), eos_idx=self.dictionary.eos(), left_pad_source=self.left_pad_source, left_pad_target=self.left_pad_target, input_feeding=self.input_feeding, pad_to_length=pad_to_length, pad_to_multiple=self.pad_to_multiple, src_bucketed=(self.buckets is not None), ) if self.src_lang_id is not None or self.tgt_lang_id is not None: src_tokens = res["net_input"]["src_tokens"] bsz = src_tokens.size(0) if self.src_lang_id is not None: res["net_input"]["src_lang_id"] = ( torch.LongTensor([[self.src_lang_id]]).expand(bsz, 1).to(src_tokens) ) if self.tgt_lang_id is not None: res["tgt_lang_id"] = ( torch.LongTensor([[self.tgt_lang_id]]).expand(bsz, 1).to(src_tokens) ) return res
[ "def", "collater", "(", "self", ",", "samples", ",", "pad_to_length", "=", "None", ")", ":", "res", "=", "collate", "(", "samples", ",", "pad_idx", "=", "self", ".", "dictionary", ".", "pad", "(", ")", ",", "eos_idx", "=", "self", ".", "dictionary", ...
https://github.com/freewym/espresso/blob/6671c507350295269e38add57dbe601dcb8e6ecf/espresso/data/asr_dataset.py#L291-L352
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/analyses/identifier/functions/atoi.py
python
atoi.__init__
(self)
[]
def __init__(self): super(atoi, self).__init__() self.skips_whitespace = False self.allows_negative = True
[ "def", "__init__", "(", "self", ")", ":", "super", "(", "atoi", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "skips_whitespace", "=", "False", "self", ".", "allows_negative", "=", "True" ]
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/analyses/identifier/functions/atoi.py#L9-L12
allegro/ralph
1e4a9e1800d5f664abaef2624b8bf7512df279ce
src/ralph/data_center/admin.py
python
DataCenterAssetChangeList.get_ordering
(self, request, queryset)
return ordering
Adds extra ordering params for ordering by location.
Adds extra ordering params for ordering by location.
[ "Adds", "extra", "ordering", "params", "for", "ordering", "by", "location", "." ]
def get_ordering(self, request, queryset): """Adds extra ordering params for ordering by location.""" # NOTE(romcheg): slot_no is added by Django Admin automatically. location_fields = [ 'rack__server_room__data_center__name', 'rack__server_room__name', 'rack__name', 'position', ] ordering = super(DataCenterAssetChangeList, self).get_ordering( request, queryset ) params = self.params if ORDER_VAR in params: order_params = params[ORDER_VAR].split('.') for insert_index, p in enumerate(order_params): try: none, pfx, idx = p.rpartition('-') if self.list_display[int(idx)] == 'show_location': ordering[insert_index:insert_index] = [ '{}{}'.format(pfx, field) for field in location_fields ] except (IndexError, ValueError): continue # Invalid ordering specified, skip it. return ordering
[ "def", "get_ordering", "(", "self", ",", "request", ",", "queryset", ")", ":", "# NOTE(romcheg): slot_no is added by Django Admin automatically.", "location_fields", "=", "[", "'rack__server_room__data_center__name'", ",", "'rack__server_room__name'", ",", "'rack__name'", ",", ...
https://github.com/allegro/ralph/blob/1e4a9e1800d5f664abaef2624b8bf7512df279ce/src/ralph/data_center/admin.py#L328-L359
scrapy/scrapy
b04cfa48328d5d5749dca6f50fa34e0cfc664c89
scrapy/core/downloader/handlers/http10.py
python
HTTP10DownloadHandler.__init__
(self, settings, crawler=None)
[]
def __init__(self, settings, crawler=None): self.HTTPClientFactory = load_object(settings['DOWNLOADER_HTTPCLIENTFACTORY']) self.ClientContextFactory = load_object(settings['DOWNLOADER_CLIENTCONTEXTFACTORY']) self._settings = settings self._crawler = crawler
[ "def", "__init__", "(", "self", ",", "settings", ",", "crawler", "=", "None", ")", ":", "self", ".", "HTTPClientFactory", "=", "load_object", "(", "settings", "[", "'DOWNLOADER_HTTPCLIENTFACTORY'", "]", ")", "self", ".", "ClientContextFactory", "=", "load_object...
https://github.com/scrapy/scrapy/blob/b04cfa48328d5d5749dca6f50fa34e0cfc664c89/scrapy/core/downloader/handlers/http10.py#L10-L14
spyder-ide/spyder
55da47c032dfcf519600f67f8b30eab467f965e7
spyder/plugins/outlineexplorer/widgets.py
python
OutlineExplorerTreeWidget.clicked
(self, item)
Click event
Click event
[ "Click", "event" ]
def clicked(self, item): """Click event""" if isinstance(item, FileRootItem): self.root_item_selected(item) self.activated(item)
[ "def", "clicked", "(", "self", ",", "item", ")", ":", "if", "isinstance", "(", "item", ",", "FileRootItem", ")", ":", "self", ".", "root_item_selected", "(", "item", ")", "self", ".", "activated", "(", "item", ")" ]
https://github.com/spyder-ide/spyder/blob/55da47c032dfcf519600f67f8b30eab467f965e7/spyder/plugins/outlineexplorer/widgets.py#L819-L823
cakebread/yolk
ee8c9f529a542d9c5eff4fe69b9c7906c802e4d8
yolk/cli.py
python
Yolk.pypi_search
(self)
return 0
Search PyPI by metadata keyword e.g. yolk -S name=yolk AND license=GPL @param spec: Cheese Shop search spec @type spec: list of strings spec examples: ["name=yolk"] ["license=GPL"] ["name=yolk", "AND", "license=GPL"] @returns: 0 on success or 1 if mal-formed search spec
Search PyPI by metadata keyword e.g. yolk -S name=yolk AND license=GPL
[ "Search", "PyPI", "by", "metadata", "keyword", "e", ".", "g", ".", "yolk", "-", "S", "name", "=", "yolk", "AND", "license", "=", "GPL" ]
def pypi_search(self): """ Search PyPI by metadata keyword e.g. yolk -S name=yolk AND license=GPL @param spec: Cheese Shop search spec @type spec: list of strings spec examples: ["name=yolk"] ["license=GPL"] ["name=yolk", "AND", "license=GPL"] @returns: 0 on success or 1 if mal-formed search spec """ spec = self.pkg_spec #Add remainging cli arguments to options.pypi_search search_arg = self.options.pypi_search spec.insert(0, search_arg.strip()) (spec, operator) = self.parse_search_spec(spec) if not spec: return 1 for pkg in self.pypi.search(spec, operator): if pkg['summary']: summary = pkg['summary'].encode('utf-8') else: summary = "" print("""%s (%s): %s """ % (pkg['name'].encode('utf-8'), pkg["version"], summary)) return 0
[ "def", "pypi_search", "(", "self", ")", ":", "spec", "=", "self", ".", "pkg_spec", "#Add remainging cli arguments to options.pypi_search", "search_arg", "=", "self", ".", "options", ".", "pypi_search", "spec", ".", "insert", "(", "0", ",", "search_arg", ".", "st...
https://github.com/cakebread/yolk/blob/ee8c9f529a542d9c5eff4fe69b9c7906c802e4d8/yolk/cli.py#L801-L834
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/tke/v20180525/models.py
python
SyncPrometheusTemplateRequest.__init__
(self)
r""" :param TemplateId: 实例id :type TemplateId: str :param Targets: 同步目标 :type Targets: list of PrometheusTemplateSyncTarget
r""" :param TemplateId: 实例id :type TemplateId: str :param Targets: 同步目标 :type Targets: list of PrometheusTemplateSyncTarget
[ "r", ":", "param", "TemplateId", ":", "实例id", ":", "type", "TemplateId", ":", "str", ":", "param", "Targets", ":", "同步目标", ":", "type", "Targets", ":", "list", "of", "PrometheusTemplateSyncTarget" ]
def __init__(self): r""" :param TemplateId: 实例id :type TemplateId: str :param Targets: 同步目标 :type Targets: list of PrometheusTemplateSyncTarget """ self.TemplateId = None self.Targets = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "TemplateId", "=", "None", "self", ".", "Targets", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/tke/v20180525/models.py#L9778-L9786