nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
sequence
function
stringlengths
18
4.83M
function_tokens
sequence
url
stringlengths
83
304
Pagure/pagure
512f23f5cd1f965276969747792edeb1215cba68
pagure/lib/notify.py
python
_fullname_to_url
(fullname)
return fullname
For forked projects, fullname is 'forks/user/...' but URL is 'fork/user/...'. This is why we can't have nice things.
For forked projects, fullname is 'forks/user/...' but URL is 'fork/user/...'. This is why we can't have nice things.
[ "For", "forked", "projects", "fullname", "is", "forks", "/", "user", "/", "...", "but", "URL", "is", "fork", "/", "user", "/", "...", ".", "This", "is", "why", "we", "can", "t", "have", "nice", "things", "." ]
def _fullname_to_url(fullname): """For forked projects, fullname is 'forks/user/...' but URL is 'fork/user/...'. This is why we can't have nice things. """ if fullname.startswith("forks/"): fullname = fullname.replace("forks", "fork", 1) return fullname
[ "def", "_fullname_to_url", "(", "fullname", ")", ":", "if", "fullname", ".", "startswith", "(", "\"forks/\"", ")", ":", "fullname", "=", "fullname", ".", "replace", "(", "\"forks\"", ",", "\"fork\"", ",", "1", ")", "return", "fullname" ]
https://github.com/Pagure/pagure/blob/512f23f5cd1f965276969747792edeb1215cba68/pagure/lib/notify.py#L393-L399
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/mlab.py
python
rec_drop_fields
(rec, names)
return newrec
Return a new numpy record array with fields in *names* dropped.
Return a new numpy record array with fields in *names* dropped.
[ "Return", "a", "new", "numpy", "record", "array", "with", "fields", "in", "*", "names", "*", "dropped", "." ]
def rec_drop_fields(rec, names): """ Return a new numpy record array with fields in *names* dropped. """ names = set(names) newdtype = np.dtype([(name, rec.dtype[name]) for name in rec.dtype.names if name not in names]) newrec = np.recarray(rec.shape, dtype=newdtype) for field in newdtype.names: newrec[field] = rec[field] return newrec
[ "def", "rec_drop_fields", "(", "rec", ",", "names", ")", ":", "names", "=", "set", "(", "names", ")", "newdtype", "=", "np", ".", "dtype", "(", "[", "(", "name", ",", "rec", ".", "dtype", "[", "name", "]", ")", "for", "name", "in", "rec", ".", "dtype", ".", "names", "if", "name", "not", "in", "names", "]", ")", "newrec", "=", "np", ".", "recarray", "(", "rec", ".", "shape", ",", "dtype", "=", "newdtype", ")", "for", "field", "in", "newdtype", ".", "names", ":", "newrec", "[", "field", "]", "=", "rec", "[", "field", "]", "return", "newrec" ]
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/mlab.py#L2360-L2374
JBakamovic/cxxd
142c19649b036bd6f6bdcd4684de735ea11a6c94
services/source_code_model/indexer/symbol_database.py
python
SymbolDatabase.__del__
(self)
[]
def __del__(self): if self.db_connection: try: self.db_connection.close() except: logging.error(sys.exc_info())
[ "def", "__del__", "(", "self", ")", ":", "if", "self", ".", "db_connection", ":", "try", ":", "self", ".", "db_connection", ".", "close", "(", ")", "except", ":", "logging", ".", "error", "(", "sys", ".", "exc_info", "(", ")", ")" ]
https://github.com/JBakamovic/cxxd/blob/142c19649b036bd6f6bdcd4684de735ea11a6c94/services/source_code_model/indexer/symbol_database.py#L25-L30
MrH0wl/Cloudmare
65e5bc9888f9d362ab2abfb103ea6c1e869d67aa
thirdparty/xlsxwriter/chart.py
python
Chart.__init__
(self, options=None)
Constructor.
Constructor.
[ "Constructor", "." ]
def __init__(self, options=None): """ Constructor. """ super(Chart, self).__init__() self.subtype = None self.sheet_type = 0x0200 self.orientation = 0x0 self.series = [] self.embedded = 0 self.id = -1 self.series_index = 0 self.style_id = 2 self.axis_ids = [] self.axis2_ids = [] self.cat_has_num_fmt = 0 self.requires_category = False self.legend = {} self.cat_axis_position = 'b' self.val_axis_position = 'l' self.formula_ids = {} self.formula_data = [] self.horiz_cat_axis = 0 self.horiz_val_axis = 1 self.protection = 0 self.chartarea = {} self.plotarea = {} self.x_axis = {} self.y_axis = {} self.y2_axis = {} self.x2_axis = {} self.chart_name = '' self.show_blanks = 'gap' self.show_hidden = 0 self.show_crosses = 1 self.width = 480 self.height = 288 self.x_scale = 1 self.y_scale = 1 self.x_offset = 0 self.y_offset = 0 self.table = None self.cross_between = 'between' self.default_marker = None self.series_gap_1 = None self.series_gap_2 = None self.series_overlap_1 = None self.series_overlap_2 = None self.drop_lines = None self.hi_low_lines = None self.up_down_bars = None self.smooth_allowed = False self.title_font = None self.title_name = None self.title_formula = None self.title_data_id = None self.title_layout = None self.title_overlay = None self.title_none = False self.date_category = False self.date_1904 = False self.remove_timezone = False self.label_positions = {} self.label_position_default = '' self.already_inserted = False self.combined = None self.is_secondary = False self.warn_sheetname = True self._set_default_properties()
[ "def", "__init__", "(", "self", ",", "options", "=", "None", ")", ":", "super", "(", "Chart", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "subtype", "=", "None", "self", ".", "sheet_type", "=", "0x0200", "self", ".", "orientation", "=", "0x0", "self", ".", "series", "=", "[", "]", "self", ".", "embedded", "=", "0", "self", ".", "id", "=", "-", "1", "self", ".", "series_index", "=", "0", "self", ".", "style_id", "=", "2", "self", ".", "axis_ids", "=", "[", "]", "self", ".", "axis2_ids", "=", "[", "]", "self", ".", "cat_has_num_fmt", "=", "0", "self", ".", "requires_category", "=", "False", "self", ".", "legend", "=", "{", "}", "self", ".", "cat_axis_position", "=", "'b'", "self", ".", "val_axis_position", "=", "'l'", "self", ".", "formula_ids", "=", "{", "}", "self", ".", "formula_data", "=", "[", "]", "self", ".", "horiz_cat_axis", "=", "0", "self", ".", "horiz_val_axis", "=", "1", "self", ".", "protection", "=", "0", "self", ".", "chartarea", "=", "{", "}", "self", ".", "plotarea", "=", "{", "}", "self", ".", "x_axis", "=", "{", "}", "self", ".", "y_axis", "=", "{", "}", "self", ".", "y2_axis", "=", "{", "}", "self", ".", "x2_axis", "=", "{", "}", "self", ".", "chart_name", "=", "''", "self", ".", "show_blanks", "=", "'gap'", "self", ".", "show_hidden", "=", "0", "self", ".", "show_crosses", "=", "1", "self", ".", "width", "=", "480", "self", ".", "height", "=", "288", "self", ".", "x_scale", "=", "1", "self", ".", "y_scale", "=", "1", "self", ".", "x_offset", "=", "0", "self", ".", "y_offset", "=", "0", "self", ".", "table", "=", "None", "self", ".", "cross_between", "=", "'between'", "self", ".", "default_marker", "=", "None", "self", ".", "series_gap_1", "=", "None", "self", ".", "series_gap_2", "=", "None", "self", ".", "series_overlap_1", "=", "None", "self", ".", "series_overlap_2", "=", "None", "self", ".", "drop_lines", "=", "None", "self", ".", "hi_low_lines", "=", "None", "self", ".", "up_down_bars", "=", "None", "self", ".", "smooth_allowed", "=", "False", "self", ".", "title_font", "=", "None", "self", ".", "title_name", "=", "None", "self", ".", "title_formula", "=", "None", "self", ".", "title_data_id", "=", "None", "self", ".", "title_layout", "=", "None", "self", ".", "title_overlay", "=", "None", "self", ".", "title_none", "=", "False", "self", ".", "date_category", "=", "False", "self", ".", "date_1904", "=", "False", "self", ".", "remove_timezone", "=", "False", "self", ".", "label_positions", "=", "{", "}", "self", ".", "label_position_default", "=", "''", "self", ".", "already_inserted", "=", "False", "self", ".", "combined", "=", "None", "self", ".", "is_secondary", "=", "False", "self", ".", "warn_sheetname", "=", "True", "self", ".", "_set_default_properties", "(", ")" ]
https://github.com/MrH0wl/Cloudmare/blob/65e5bc9888f9d362ab2abfb103ea6c1e869d67aa/thirdparty/xlsxwriter/chart.py#L34-L105
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Centos_5.9/paramiko/auth_handler.py
python
AuthHandler._disconnect_service_not_available
(self)
[]
def _disconnect_service_not_available(self): m = Message() m.add_byte(chr(MSG_DISCONNECT)) m.add_int(DISCONNECT_SERVICE_NOT_AVAILABLE) m.add_string('Service not available') m.add_string('en') self.transport._send_message(m) self.transport.close()
[ "def", "_disconnect_service_not_available", "(", "self", ")", ":", "m", "=", "Message", "(", ")", "m", ".", "add_byte", "(", "chr", "(", "MSG_DISCONNECT", ")", ")", "m", ".", "add_int", "(", "DISCONNECT_SERVICE_NOT_AVAILABLE", ")", "m", ".", "add_string", "(", "'Service not available'", ")", "m", ".", "add_string", "(", "'en'", ")", "self", ".", "transport", ".", "_send_message", "(", "m", ")", "self", ".", "transport", ".", "close", "(", ")" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Centos_5.9/paramiko/auth_handler.py#L126-L133
CenterForOpenScience/osf.io
cc02691be017e61e2cd64f19b848b2f4c18dcc84
framework/utils.py
python
iso8601format
(dt)
return dt.strftime('%Y-%m-%dT%H:%M:%SZ') if dt else ''
Given a datetime object, return an associated ISO-8601 string
Given a datetime object, return an associated ISO-8601 string
[ "Given", "a", "datetime", "object", "return", "an", "associated", "ISO", "-", "8601", "string" ]
def iso8601format(dt): """Given a datetime object, return an associated ISO-8601 string""" return dt.strftime('%Y-%m-%dT%H:%M:%SZ') if dt else ''
[ "def", "iso8601format", "(", "dt", ")", ":", "return", "dt", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%SZ'", ")", "if", "dt", "else", "''" ]
https://github.com/CenterForOpenScience/osf.io/blob/cc02691be017e61e2cd64f19b848b2f4c18dcc84/framework/utils.py#L10-L12
cobbler/cobbler
eed8cdca3e970c8aa1d199e80b8c8f19b3f940cc
cobbler/actions/check.py
python
CobblerCheck.check_yum
(self, status)
Check if the yum-stack is available. On Debian based distros this will always return without checking. :param status: The status list with possible problems.
Check if the yum-stack is available. On Debian based distros this will always return without checking.
[ "Check", "if", "the", "yum", "-", "stack", "is", "available", ".", "On", "Debian", "based", "distros", "this", "will", "always", "return", "without", "checking", "." ]
def check_yum(self, status): """ Check if the yum-stack is available. On Debian based distros this will always return without checking. :param status: The status list with possible problems. """ # FIXME: Replace this with calls which check for the path of these tools. if self.checked_family == "debian": return if not os.path.exists("/usr/bin/createrepo"): status.append("createrepo package is not installed, needed for cobbler import and cobbler reposync, " "install createrepo?") if not os.path.exists("/usr/bin/dnf") and not os.path.exists("/usr/bin/reposync"): status.append("reposync not installed, install yum-utils") if os.path.exists("/usr/bin/dnf") and not os.path.exists("/usr/bin/reposync"): status.append("reposync is not installed, install yum-utils or dnf-plugins-core") if not os.path.exists("/usr/bin/dnf") and not os.path.exists("/usr/bin/yumdownloader"): status.append("yumdownloader is not installed, install yum-utils") if os.path.exists("/usr/bin/dnf") and not os.path.exists("/usr/bin/yumdownloader"): status.append("yumdownloader is not installed, install yum-utils or dnf-plugins-core")
[ "def", "check_yum", "(", "self", ",", "status", ")", ":", "# FIXME: Replace this with calls which check for the path of these tools.", "if", "self", ".", "checked_family", "==", "\"debian\"", ":", "return", "if", "not", "os", ".", "path", ".", "exists", "(", "\"/usr/bin/createrepo\"", ")", ":", "status", ".", "append", "(", "\"createrepo package is not installed, needed for cobbler import and cobbler reposync, \"", "\"install createrepo?\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "\"/usr/bin/dnf\"", ")", "and", "not", "os", ".", "path", ".", "exists", "(", "\"/usr/bin/reposync\"", ")", ":", "status", ".", "append", "(", "\"reposync not installed, install yum-utils\"", ")", "if", "os", ".", "path", ".", "exists", "(", "\"/usr/bin/dnf\"", ")", "and", "not", "os", ".", "path", ".", "exists", "(", "\"/usr/bin/reposync\"", ")", ":", "status", ".", "append", "(", "\"reposync is not installed, install yum-utils or dnf-plugins-core\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "\"/usr/bin/dnf\"", ")", "and", "not", "os", ".", "path", ".", "exists", "(", "\"/usr/bin/yumdownloader\"", ")", ":", "status", ".", "append", "(", "\"yumdownloader is not installed, install yum-utils\"", ")", "if", "os", ".", "path", ".", "exists", "(", "\"/usr/bin/dnf\"", ")", "and", "not", "os", ".", "path", ".", "exists", "(", "\"/usr/bin/yumdownloader\"", ")", ":", "status", ".", "append", "(", "\"yumdownloader is not installed, install yum-utils or dnf-plugins-core\"", ")" ]
https://github.com/cobbler/cobbler/blob/eed8cdca3e970c8aa1d199e80b8c8f19b3f940cc/cobbler/actions/check.py#L185-L209
marinho/geraldo
868ebdce67176d9b6205cddc92476f642c783fff
site/newsite/site-geraldo/django/contrib/auth/models.py
python
UserManager.make_random_password
(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
return ''.join([choice(allowed_chars) for i in range(length)])
Generates a random password with the given length and given allowed_chars
Generates a random password with the given length and given allowed_chars
[ "Generates", "a", "random", "password", "with", "the", "given", "length", "and", "given", "allowed_chars" ]
def make_random_password(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'): "Generates a random password with the given length and given allowed_chars" # Note that default value of allowed_chars does not have "I" or letters # that look like it -- just to avoid confusion. from random import choice return ''.join([choice(allowed_chars) for i in range(length)])
[ "def", "make_random_password", "(", "self", ",", "length", "=", "10", ",", "allowed_chars", "=", "'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'", ")", ":", "# Note that default value of allowed_chars does not have \"I\" or letters", "# that look like it -- just to avoid confusion.", "from", "random", "import", "choice", "return", "''", ".", "join", "(", "[", "choice", "(", "allowed_chars", ")", "for", "i", "in", "range", "(", "length", ")", "]", ")" ]
https://github.com/marinho/geraldo/blob/868ebdce67176d9b6205cddc92476f642c783fff/site/newsite/site-geraldo/django/contrib/auth/models.py#L124-L129
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/boto_apigateway.py
python
delete_api
(name, description=None, region=None, key=None, keyid=None, profile=None)
Delete all REST API Service with the given name and an optional API description Returns {deleted: True, count: deleted_count} if apis were deleted, and returns {deleted: False} if error or not found. CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api myapi_name salt myminion boto_apigateway.delete_api myapi_name description='api description'
Delete all REST API Service with the given name and an optional API description
[ "Delete", "all", "REST", "API", "Service", "with", "the", "given", "name", "and", "an", "optional", "API", "description" ]
def delete_api(name, description=None, region=None, key=None, keyid=None, profile=None): """ Delete all REST API Service with the given name and an optional API description Returns {deleted: True, count: deleted_count} if apis were deleted, and returns {deleted: False} if error or not found. CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api myapi_name salt myminion boto_apigateway.delete_api myapi_name description='api description' """ try: conn_params = dict(region=region, key=key, keyid=keyid, profile=profile) r = _find_apis_by_name(name, description=description, **conn_params) apis = r.get("restapi") if apis: conn = _get_conn(**conn_params) for api in apis: conn.delete_rest_api(restApiId=api["id"]) return {"deleted": True, "count": len(apis)} else: return {"deleted": False} except ClientError as e: return {"deleted": False, "error": __utils__["boto3.get_error"](e)}
[ "def", "delete_api", "(", "name", ",", "description", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn_params", "=", "dict", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "r", "=", "_find_apis_by_name", "(", "name", ",", "description", "=", "description", ",", "*", "*", "conn_params", ")", "apis", "=", "r", ".", "get", "(", "\"restapi\"", ")", "if", "apis", ":", "conn", "=", "_get_conn", "(", "*", "*", "conn_params", ")", "for", "api", "in", "apis", ":", "conn", ".", "delete_rest_api", "(", "restApiId", "=", "api", "[", "\"id\"", "]", ")", "return", "{", "\"deleted\"", ":", "True", ",", "\"count\"", ":", "len", "(", "apis", ")", "}", "else", ":", "return", "{", "\"deleted\"", ":", "False", "}", "except", "ClientError", "as", "e", ":", "return", "{", "\"deleted\"", ":", "False", ",", "\"error\"", ":", "__utils__", "[", "\"boto3.get_error\"", "]", "(", "e", ")", "}" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/boto_apigateway.py#L280-L308
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/lib2to3/fixes/fix_operator.py
python
FixOperator._repeat
(self, node, results)
return self._handle_rename(node, results, "mul")
[]
def _repeat(self, node, results): return self._handle_rename(node, results, "mul")
[ "def", "_repeat", "(", "self", ",", "node", ",", "results", ")", ":", "return", "self", ".", "_handle_rename", "(", "node", ",", "results", ",", "\"mul\"", ")" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/lib2to3/fixes/fix_operator.py#L58-L59
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/plugins/attack/db/sqlmap/plugins/dbms/postgresql/connector.py
python
Connector.__init__
(self)
[]
def __init__(self): GenericConnector.__init__(self)
[ "def", "__init__", "(", "self", ")", ":", "GenericConnector", ".", "__init__", "(", "self", ")" ]
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/plugins/attack/db/sqlmap/plugins/dbms/postgresql/connector.py#L31-L32
w3h/isf
6faf0a3df185465ec17369c90ccc16e2a03a1870
lib/thirdparty/Crypto/Util/number.py
python
bytes_to_long
(s)
return acc
bytes_to_long(string) : long Convert a byte string to a long integer. This is (essentially) the inverse of long_to_bytes().
bytes_to_long(string) : long Convert a byte string to a long integer.
[ "bytes_to_long", "(", "string", ")", ":", "long", "Convert", "a", "byte", "string", "to", "a", "long", "integer", "." ]
def bytes_to_long(s): """bytes_to_long(string) : long Convert a byte string to a long integer. This is (essentially) the inverse of long_to_bytes(). """ acc = 0L unpack = struct.unpack length = len(s) if length % 4: extra = (4 - length % 4) s = b('\000') * extra + s length = length + extra for i in range(0, length, 4): acc = (acc << 32) + unpack('>I', s[i:i+4])[0] return acc
[ "def", "bytes_to_long", "(", "s", ")", ":", "acc", "=", "0L", "unpack", "=", "struct", ".", "unpack", "length", "=", "len", "(", "s", ")", "if", "length", "%", "4", ":", "extra", "=", "(", "4", "-", "length", "%", "4", ")", "s", "=", "b", "(", "'\\000'", ")", "*", "extra", "+", "s", "length", "=", "length", "+", "extra", "for", "i", "in", "range", "(", "0", ",", "length", ",", "4", ")", ":", "acc", "=", "(", "acc", "<<", "32", ")", "+", "unpack", "(", "'>I'", ",", "s", "[", "i", ":", "i", "+", "4", "]", ")", "[", "0", "]", "return", "acc" ]
https://github.com/w3h/isf/blob/6faf0a3df185465ec17369c90ccc16e2a03a1870/lib/thirdparty/Crypto/Util/number.py#L417-L432
spyder-ide/spyder
55da47c032dfcf519600f67f8b30eab467f965e7
spyder/plugins/shortcuts/plugin.py
python
Shortcuts.reset_shortcuts
(self)
Reset shrotcuts.
Reset shrotcuts.
[ "Reset", "shrotcuts", "." ]
def reset_shortcuts(self): """Reset shrotcuts.""" if self._conf: self._conf.reset_shortcuts()
[ "def", "reset_shortcuts", "(", "self", ")", ":", "if", "self", ".", "_conf", ":", "self", ".", "_conf", ".", "reset_shortcuts", "(", ")" ]
https://github.com/spyder-ide/spyder/blob/55da47c032dfcf519600f67f8b30eab467f965e7/spyder/plugins/shortcuts/plugin.py#L127-L130
Qirky/FoxDot
76318f9630bede48ff3994146ed644affa27bfa4
FoxDot/lib/TimeVar.py
python
TimeVar.__eq__
(self, other)
return other == self.now()
[]
def __eq__(self, other): return other == self.now()
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "return", "other", "==", "self", ".", "now", "(", ")" ]
https://github.com/Qirky/FoxDot/blob/76318f9630bede48ff3994146ed644affa27bfa4/FoxDot/lib/TimeVar.py#L447-L448
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/gpsd/sensor.py
python
GpsdSensor.native_value
(self)
return None
Return the state of GPSD.
Return the state of GPSD.
[ "Return", "the", "state", "of", "GPSD", "." ]
def native_value(self): """Return the state of GPSD.""" if self.agps_thread.data_stream.mode == 3: return "3D Fix" if self.agps_thread.data_stream.mode == 2: return "2D Fix" return None
[ "def", "native_value", "(", "self", ")", ":", "if", "self", ".", "agps_thread", ".", "data_stream", ".", "mode", "==", "3", ":", "return", "\"3D Fix\"", "if", "self", ".", "agps_thread", ".", "data_stream", ".", "mode", "==", "2", ":", "return", "\"2D Fix\"", "return", "None" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/gpsd/sensor.py#L97-L103
zatosource/zato
2a9d273f06f9d776fbfeb53e73855af6e40fa208
code/zato-server/src/zato/server/pubsub/__init__.py
python
PubSub.get_non_gd_topic_depth
(self, topic_name:'str')
Returns of non-GD messages for a given topic by its name.
Returns of non-GD messages for a given topic by its name.
[ "Returns", "of", "non", "-", "GD", "messages", "for", "a", "given", "topic", "by", "its", "name", "." ]
def get_non_gd_topic_depth(self, topic_name:'str') -> 'int': """ Returns of non-GD messages for a given topic by its name. """ with self.lock: return self.sync_backlog.get_topic_depth(self._get_topic_id_by_name(topic_name))
[ "def", "get_non_gd_topic_depth", "(", "self", ",", "topic_name", ":", "'str'", ")", "->", "'int'", ":", "with", "self", ".", "lock", ":", "return", "self", ".", "sync_backlog", ".", "get_topic_depth", "(", "self", ".", "_get_topic_id_by_name", "(", "topic_name", ")", ")" ]
https://github.com/zatosource/zato/blob/2a9d273f06f9d776fbfeb53e73855af6e40fa208/code/zato-server/src/zato/server/pubsub/__init__.py#L496-L500
PaddlePaddle/PARL
5fb7a5d2b5d0f0dac57fdf4acb9e79485c7efa96
parl/algorithms/fluid/ddpg.py
python
DDPG.predict
(self, obs)
return self.model.policy(obs)
use actor model of self.model to predict the action
use actor model of self.model to predict the action
[ "use", "actor", "model", "of", "self", ".", "model", "to", "predict", "the", "action" ]
def predict(self, obs): """ use actor model of self.model to predict the action """ return self.model.policy(obs)
[ "def", "predict", "(", "self", ",", "obs", ")", ":", "return", "self", ".", "model", ".", "policy", "(", "obs", ")" ]
https://github.com/PaddlePaddle/PARL/blob/5fb7a5d2b5d0f0dac57fdf4acb9e79485c7efa96/parl/algorithms/fluid/ddpg.py#L55-L58
dropbox/securitybot
8cc4846602011db396df621d2e84e5808a6f3441
securitybot/bot.py
python
SecurityBot.valid_user
(self, username)
Validates a username to be valid.
Validates a username to be valid.
[ "Validates", "a", "username", "to", "be", "valid", "." ]
def valid_user(self, username): # type: (str) -> bool ''' Validates a username to be valid. ''' if len(username.split()) != 1: return False try: self.user_lookup_by_name(username) return True except SecurityBotException as e: logging.warn('{}'.format(e)) return False
[ "def", "valid_user", "(", "self", ",", "username", ")", ":", "# type: (str) -> bool", "if", "len", "(", "username", ".", "split", "(", ")", ")", "!=", "1", ":", "return", "False", "try", ":", "self", ".", "user_lookup_by_name", "(", "username", ")", "return", "True", "except", "SecurityBotException", "as", "e", ":", "logging", ".", "warn", "(", "'{}'", ".", "format", "(", "e", ")", ")", "return", "False" ]
https://github.com/dropbox/securitybot/blob/8cc4846602011db396df621d2e84e5808a6f3441/securitybot/bot.py#L218-L230
eliben/pycparser
7999dde25706e8a2b4bc63634b058d79bdb6417f
pycparser/c_generator.py
python
CGenerator._is_simple_node
(self, n)
return isinstance(n, (c_ast.Constant, c_ast.ID, c_ast.ArrayRef, c_ast.StructRef, c_ast.FuncCall))
Returns True for nodes that are "simple" - i.e. nodes that always have higher precedence than operators.
Returns True for nodes that are "simple" - i.e. nodes that always have higher precedence than operators.
[ "Returns", "True", "for", "nodes", "that", "are", "simple", "-", "i", ".", "e", ".", "nodes", "that", "always", "have", "higher", "precedence", "than", "operators", "." ]
def _is_simple_node(self, n): """ Returns True for nodes that are "simple" - i.e. nodes that always have higher precedence than operators. """ return isinstance(n, (c_ast.Constant, c_ast.ID, c_ast.ArrayRef, c_ast.StructRef, c_ast.FuncCall))
[ "def", "_is_simple_node", "(", "self", ",", "n", ")", ":", "return", "isinstance", "(", "n", ",", "(", "c_ast", ".", "Constant", ",", "c_ast", ".", "ID", ",", "c_ast", ".", "ArrayRef", ",", "c_ast", ".", "StructRef", ",", "c_ast", ".", "FuncCall", ")", ")" ]
https://github.com/eliben/pycparser/blob/7999dde25706e8a2b4bc63634b058d79bdb6417f/pycparser/c_generator.py#L497-L502
nerdvegas/rez
d392c65bf63b4bca8106f938cec49144ba54e770
src/rez/vendor/pika/adapters/utils/selector_ioloop_adapter.py
python
AbstractSelectorIOLoop.READ
(self)
The value of the I/O loop's READ flag; READ/WRITE/ERROR may be used with bitwise operators as expected. Implementation note: the implementations can simply replace these READ/WRITE/ERROR properties with class-level attributes
The value of the I/O loop's READ flag; READ/WRITE/ERROR may be used with bitwise operators as expected.
[ "The", "value", "of", "the", "I", "/", "O", "loop", "s", "READ", "flag", ";", "READ", "/", "WRITE", "/", "ERROR", "may", "be", "used", "with", "bitwise", "operators", "as", "expected", "." ]
def READ(self): # pylint: disable=C0103 """The value of the I/O loop's READ flag; READ/WRITE/ERROR may be used with bitwise operators as expected. Implementation note: the implementations can simply replace these READ/WRITE/ERROR properties with class-level attributes """
[ "def", "READ", "(", "self", ")", ":", "# pylint: disable=C0103" ]
https://github.com/nerdvegas/rez/blob/d392c65bf63b4bca8106f938cec49144ba54e770/src/rez/vendor/pika/adapters/utils/selector_ioloop_adapter.py#L30-L37
lepture/authlib
2284f751a47474da7d127303e0d8f34d9046c310
authlib/integrations/base_client/sync_app.py
python
OAuth1Mixin.create_authorization_url
(self, redirect_uri=None, **kwargs)
return {'url': url, 'request_token': request_token, 'state': state}
Generate the authorization url and state for HTTP redirect. :param redirect_uri: Callback or redirect URI for authorization. :param kwargs: Extra parameters to include. :return: dict
Generate the authorization url and state for HTTP redirect.
[ "Generate", "the", "authorization", "url", "and", "state", "for", "HTTP", "redirect", "." ]
def create_authorization_url(self, redirect_uri=None, **kwargs): """Generate the authorization url and state for HTTP redirect. :param redirect_uri: Callback or redirect URI for authorization. :param kwargs: Extra parameters to include. :return: dict """ if not self.authorize_url: raise RuntimeError('Missing "authorize_url" value') if self.authorize_params: kwargs.update(self.authorize_params) with self._get_oauth_client() as client: client.redirect_uri = redirect_uri params = self.request_token_params or {} request_token = client.fetch_request_token(self.request_token_url, **params) log.debug('Fetch request token: {!r}'.format(request_token)) url = client.create_authorization_url(self.authorize_url, **kwargs) state = request_token['oauth_token'] return {'url': url, 'request_token': request_token, 'state': state}
[ "def", "create_authorization_url", "(", "self", ",", "redirect_uri", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "authorize_url", ":", "raise", "RuntimeError", "(", "'Missing \"authorize_url\" value'", ")", "if", "self", ".", "authorize_params", ":", "kwargs", ".", "update", "(", "self", ".", "authorize_params", ")", "with", "self", ".", "_get_oauth_client", "(", ")", "as", "client", ":", "client", ".", "redirect_uri", "=", "redirect_uri", "params", "=", "self", ".", "request_token_params", "or", "{", "}", "request_token", "=", "client", ".", "fetch_request_token", "(", "self", ".", "request_token_url", ",", "*", "*", "params", ")", "log", ".", "debug", "(", "'Fetch request token: {!r}'", ".", "format", "(", "request_token", ")", ")", "url", "=", "client", ".", "create_authorization_url", "(", "self", ".", "authorize_url", ",", "*", "*", "kwargs", ")", "state", "=", "request_token", "[", "'oauth_token'", "]", "return", "{", "'url'", ":", "url", ",", "'request_token'", ":", "request_token", ",", "'state'", ":", "state", "}" ]
https://github.com/lepture/authlib/blob/2284f751a47474da7d127303e0d8f34d9046c310/authlib/integrations/base_client/sync_app.py#L130-L150
geopy/geopy
af0eedcfeb4e3eec88f19e2f822e7f14ac3468eb
geopy/geocoders/here.py
python
HereV7.reverse
( self, query, *, language=None, limit=None, exactly_one=True, timeout=DEFAULT_SENTINEL )
return self._call_geocoder(url, callback, timeout=timeout)
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param str language: Affects the language of the response, must be a BCP 47 compliant language code, e.g. ``en-US``. :param int limit: Maximum number of results to be returned. This will be reset to one if ``exactly_one`` is True. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
[ "Return", "an", "address", "by", "location", "point", "." ]
def reverse( self, query, *, language=None, limit=None, exactly_one=True, timeout=DEFAULT_SENTINEL ): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param str language: Affects the language of the response, must be a BCP 47 compliant language code, e.g. ``en-US``. :param int limit: Maximum number of results to be returned. This will be reset to one if ``exactly_one`` is True. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = { 'at': self._coerce_point_to_string(query, output_format="%(lat)s,%(lon)s"), 'apiKey': self.apikey, } if language: params['lang'] = language if limit: params['limit'] = limit if exactly_one: params['limit'] = 1 url = "%s?%s" % (self.reverse_api, urlencode(params)) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
[ "def", "reverse", "(", "self", ",", "query", ",", "*", ",", "language", "=", "None", ",", "limit", "=", "None", ",", "exactly_one", "=", "True", ",", "timeout", "=", "DEFAULT_SENTINEL", ")", ":", "params", "=", "{", "'at'", ":", "self", ".", "_coerce_point_to_string", "(", "query", ",", "output_format", "=", "\"%(lat)s,%(lon)s\"", ")", ",", "'apiKey'", ":", "self", ".", "apikey", ",", "}", "if", "language", ":", "params", "[", "'lang'", "]", "=", "language", "if", "limit", ":", "params", "[", "'limit'", "]", "=", "limit", "if", "exactly_one", ":", "params", "[", "'limit'", "]", "=", "1", "url", "=", "\"%s?%s\"", "%", "(", "self", ".", "reverse_api", ",", "urlencode", "(", "params", ")", ")", "logger", ".", "debug", "(", "\"%s.reverse: %s\"", ",", "self", ".", "__class__", ".", "__name__", ",", "url", ")", "callback", "=", "partial", "(", "self", ".", "_parse_json", ",", "exactly_one", "=", "exactly_one", ")", "return", "self", ".", "_call_geocoder", "(", "url", ",", "callback", ",", "timeout", "=", "timeout", ")" ]
https://github.com/geopy/geopy/blob/af0eedcfeb4e3eec88f19e2f822e7f14ac3468eb/geopy/geocoders/here.py#L561-L612
fkie/multimaster_fkie
3d23df29d25d71a75c66bbd3cc6e9cbb255724d8
fkie_node_manager/src/fkie_node_manager/launch_list_model.py
python
PathItem.data
(self, role)
The view asks us for all sorts of information about our data... :param role: the art of the data :type role: :class:`QtCore.Qt.DisplayRole` <https://srinikom.github.io/pyside-docs/PySide/QtCore/Qt.html> :see: http://www.pyside.org/docs/pyside-1.0.1/PySide/QtCore/Qt.html
The view asks us for all sorts of information about our data...
[ "The", "view", "asks", "us", "for", "all", "sorts", "of", "information", "about", "our", "data", "..." ]
def data(self, role): ''' The view asks us for all sorts of information about our data... :param role: the art of the data :type role: :class:`QtCore.Qt.DisplayRole` <https://srinikom.github.io/pyside-docs/PySide/QtCore/Qt.html> :see: http://www.pyside.org/docs/pyside-1.0.1/PySide/QtCore/Qt.html ''' if role == Qt.DisplayRole: # return the displayed item name if self.id == PathItem.RECENT_FILE or self.id == PathItem.RECENT_PROFILE: return "%s [%s]" % (self.name, self.package_name) # .decode(sys.getfilesystemencoding()) elif self.id == PathItem.REMOTE_DAEMON: return "//%s" % self.name else: return "%s" % self.name elif role == Qt.ToolTipRole: # return the tooltip of the item result = "%s" % self.path if self.id == PathItem.RECENT_FILE or self.id == PathItem.RECENT_PROFILE: result = "%s\nPress 'Delete' to remove the entry from the history list\nShift+'double click' goes to the file location" % self.path return result elif role == Qt.EditRole: return "%s" % self.name else: # We don't care about anything else, so return default value return QStandardItem.data(self, role)
[ "def", "data", "(", "self", ",", "role", ")", ":", "if", "role", "==", "Qt", ".", "DisplayRole", ":", "# return the displayed item name", "if", "self", ".", "id", "==", "PathItem", ".", "RECENT_FILE", "or", "self", ".", "id", "==", "PathItem", ".", "RECENT_PROFILE", ":", "return", "\"%s [%s]\"", "%", "(", "self", ".", "name", ",", "self", ".", "package_name", ")", "# .decode(sys.getfilesystemencoding())", "elif", "self", ".", "id", "==", "PathItem", ".", "REMOTE_DAEMON", ":", "return", "\"//%s\"", "%", "self", ".", "name", "else", ":", "return", "\"%s\"", "%", "self", ".", "name", "elif", "role", "==", "Qt", ".", "ToolTipRole", ":", "# return the tooltip of the item", "result", "=", "\"%s\"", "%", "self", ".", "path", "if", "self", ".", "id", "==", "PathItem", ".", "RECENT_FILE", "or", "self", ".", "id", "==", "PathItem", ".", "RECENT_PROFILE", ":", "result", "=", "\"%s\\nPress 'Delete' to remove the entry from the history list\\nShift+'double click' goes to the file location\"", "%", "self", ".", "path", "return", "result", "elif", "role", "==", "Qt", ".", "EditRole", ":", "return", "\"%s\"", "%", "self", ".", "name", "else", ":", "# We don't care about anything else, so return default value", "return", "QStandardItem", ".", "data", "(", "self", ",", "role", ")" ]
https://github.com/fkie/multimaster_fkie/blob/3d23df29d25d71a75c66bbd3cc6e9cbb255724d8/fkie_node_manager/src/fkie_node_manager/launch_list_model.py#L191-L217
algorhythms/LintCode
2520762a1cfbd486081583136396a2b2cac6e4fb
Maximal Square.py
python
Solution.maxSquare_error
(self, matrix)
return ret
stack :param matrix: a matrix of 0 and 1 :return: an integer
stack :param matrix: a matrix of 0 and 1 :return: an integer
[ "stack", ":", "param", "matrix", ":", "a", "matrix", "of", "0", "and", "1", ":", "return", ":", "an", "integer" ]
def maxSquare_error(self, matrix): """ stack :param matrix: a matrix of 0 and 1 :return: an integer """ M = len(matrix) N = len(matrix[0]) h = [[0 for _ in xrange(N+1)] for _ in xrange(M+1)] for i in xrange(1, M+1): for j in xrange(1, N+1): if matrix[i-1][j-1] == 1: h[i][j] = h[i-1][j]+1 else: h[i][j] = 0 ret = 0 for i in xrange(M): stk = [] # col index, inc_stk for j in xrange(N): while stk and h[i+1][stk[-1]+1] >= h[i+1][j+1]: stk.pop() idx = -1 if stk: idx = stk[-1] cur_square = min(j-idx, h[i+1][j+1]) cur_square *= cur_square ret = max(ret, cur_square) stk.append(j) return ret
[ "def", "maxSquare_error", "(", "self", ",", "matrix", ")", ":", "M", "=", "len", "(", "matrix", ")", "N", "=", "len", "(", "matrix", "[", "0", "]", ")", "h", "=", "[", "[", "0", "for", "_", "in", "xrange", "(", "N", "+", "1", ")", "]", "for", "_", "in", "xrange", "(", "M", "+", "1", ")", "]", "for", "i", "in", "xrange", "(", "1", ",", "M", "+", "1", ")", ":", "for", "j", "in", "xrange", "(", "1", ",", "N", "+", "1", ")", ":", "if", "matrix", "[", "i", "-", "1", "]", "[", "j", "-", "1", "]", "==", "1", ":", "h", "[", "i", "]", "[", "j", "]", "=", "h", "[", "i", "-", "1", "]", "[", "j", "]", "+", "1", "else", ":", "h", "[", "i", "]", "[", "j", "]", "=", "0", "ret", "=", "0", "for", "i", "in", "xrange", "(", "M", ")", ":", "stk", "=", "[", "]", "# col index, inc_stk", "for", "j", "in", "xrange", "(", "N", ")", ":", "while", "stk", "and", "h", "[", "i", "+", "1", "]", "[", "stk", "[", "-", "1", "]", "+", "1", "]", ">=", "h", "[", "i", "+", "1", "]", "[", "j", "+", "1", "]", ":", "stk", ".", "pop", "(", ")", "idx", "=", "-", "1", "if", "stk", ":", "idx", "=", "stk", "[", "-", "1", "]", "cur_square", "=", "min", "(", "j", "-", "idx", ",", "h", "[", "i", "+", "1", "]", "[", "j", "+", "1", "]", ")", "cur_square", "*=", "cur_square", "ret", "=", "max", "(", "ret", ",", "cur_square", ")", "stk", ".", "append", "(", "j", ")", "return", "ret" ]
https://github.com/algorhythms/LintCode/blob/2520762a1cfbd486081583136396a2b2cac6e4fb/Maximal Square.py#L44-L73
freqtrade/freqtrade
13651fd3be8d5ce8dcd7c94b920bda4e00b75aca
freqtrade/optimize/hyperopt_loss_calmar.py
python
CalmarHyperOptLoss.hyperopt_loss_function
( results: DataFrame, trade_count: int, min_date: datetime, max_date: datetime, config: Dict, processed: Dict[str, DataFrame], backtest_stats: Dict[str, Any], *args, **kwargs )
return -calmar_ratio
Objective function, returns smaller number for more optimal results. Uses Calmar Ratio calculation.
Objective function, returns smaller number for more optimal results.
[ "Objective", "function", "returns", "smaller", "number", "for", "more", "optimal", "results", "." ]
def hyperopt_loss_function( results: DataFrame, trade_count: int, min_date: datetime, max_date: datetime, config: Dict, processed: Dict[str, DataFrame], backtest_stats: Dict[str, Any], *args, **kwargs ) -> float: """ Objective function, returns smaller number for more optimal results. Uses Calmar Ratio calculation. """ total_profit = backtest_stats["profit_total"] days_period = (max_date - min_date).days # adding slippage of 0.1% per trade total_profit = total_profit - 0.0005 expected_returns_mean = total_profit.sum() / days_period * 100 # calculate max drawdown try: _, _, _, _, _, max_drawdown = calculate_max_drawdown( results, value_col="profit_abs" ) except ValueError: max_drawdown = 0 if max_drawdown != 0: calmar_ratio = expected_returns_mean / max_drawdown * msqrt(365) else: # Define high (negative) calmar ratio to be clear that this is NOT optimal. calmar_ratio = -20.0 # print(expected_returns_mean, max_drawdown, calmar_ratio) return -calmar_ratio
[ "def", "hyperopt_loss_function", "(", "results", ":", "DataFrame", ",", "trade_count", ":", "int", ",", "min_date", ":", "datetime", ",", "max_date", ":", "datetime", ",", "config", ":", "Dict", ",", "processed", ":", "Dict", "[", "str", ",", "DataFrame", "]", ",", "backtest_stats", ":", "Dict", "[", "str", ",", "Any", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "float", ":", "total_profit", "=", "backtest_stats", "[", "\"profit_total\"", "]", "days_period", "=", "(", "max_date", "-", "min_date", ")", ".", "days", "# adding slippage of 0.1% per trade", "total_profit", "=", "total_profit", "-", "0.0005", "expected_returns_mean", "=", "total_profit", ".", "sum", "(", ")", "/", "days_period", "*", "100", "# calculate max drawdown", "try", ":", "_", ",", "_", ",", "_", ",", "_", ",", "_", ",", "max_drawdown", "=", "calculate_max_drawdown", "(", "results", ",", "value_col", "=", "\"profit_abs\"", ")", "except", "ValueError", ":", "max_drawdown", "=", "0", "if", "max_drawdown", "!=", "0", ":", "calmar_ratio", "=", "expected_returns_mean", "/", "max_drawdown", "*", "msqrt", "(", "365", ")", "else", ":", "# Define high (negative) calmar ratio to be clear that this is NOT optimal.", "calmar_ratio", "=", "-", "20.0", "# print(expected_returns_mean, max_drawdown, calmar_ratio)", "return", "-", "calmar_ratio" ]
https://github.com/freqtrade/freqtrade/blob/13651fd3be8d5ce8dcd7c94b920bda4e00b75aca/freqtrade/optimize/hyperopt_loss_calmar.py#L25-L63
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/google-api-python-client/apiclient/errors.py
python
UnexpectedBodyError.__init__
(self, expected, provided)
Constructor for an UnexpectedMethodError.
Constructor for an UnexpectedMethodError.
[ "Constructor", "for", "an", "UnexpectedMethodError", "." ]
def __init__(self, expected, provided): """Constructor for an UnexpectedMethodError.""" super(UnexpectedBodyError, self).__init__( 'Expected: [%s] - Provided: [%s]' % (expected, provided))
[ "def", "__init__", "(", "self", ",", "expected", ",", "provided", ")", ":", "super", "(", "UnexpectedBodyError", ",", "self", ")", ".", "__init__", "(", "'Expected: [%s] - Provided: [%s]'", "%", "(", "expected", ",", "provided", ")", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/google-api-python-client/apiclient/errors.py#L120-L123
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/linkers/linkers.py
python
DynamicLinker.build_rpath_args
(self, env: 'Environment', build_dir: str, from_dir: str, rpath_paths: T.Tuple[str, ...], build_rpath: str, install_rpath: str)
return ([], set())
[]
def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str, rpath_paths: T.Tuple[str, ...], build_rpath: str, install_rpath: str) -> T.Tuple[T.List[str], T.Set[bytes]]: return ([], set())
[ "def", "build_rpath_args", "(", "self", ",", "env", ":", "'Environment'", ",", "build_dir", ":", "str", ",", "from_dir", ":", "str", ",", "rpath_paths", ":", "T", ".", "Tuple", "[", "str", ",", "...", "]", ",", "build_rpath", ":", "str", ",", "install_rpath", ":", "str", ")", "->", "T", ".", "Tuple", "[", "T", ".", "List", "[", "str", "]", ",", "T", ".", "Set", "[", "bytes", "]", "]", ":", "return", "(", "[", "]", ",", "set", "(", ")", ")" ]
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/linkers/linkers.py#L520-L523
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/boto-2.46.1/boto/sns/connection.py
python
SNSConnection.delete_endpoint
(self, endpoint_arn=None)
return self._make_request(action='DeleteEndpoint', params=params)
The `DeleteEndpoint` action, which is idempotent, deletes the endpoint from SNS. For more information, see `Using Amazon SNS Mobile Push Notifications`_. :type endpoint_arn: string :param endpoint_arn: EndpointArn of endpoint to delete.
The `DeleteEndpoint` action, which is idempotent, deletes the endpoint from SNS. For more information, see `Using Amazon SNS Mobile Push Notifications`_.
[ "The", "DeleteEndpoint", "action", "which", "is", "idempotent", "deletes", "the", "endpoint", "from", "SNS", ".", "For", "more", "information", "see", "Using", "Amazon", "SNS", "Mobile", "Push", "Notifications", "_", "." ]
def delete_endpoint(self, endpoint_arn=None): """ The `DeleteEndpoint` action, which is idempotent, deletes the endpoint from SNS. For more information, see `Using Amazon SNS Mobile Push Notifications`_. :type endpoint_arn: string :param endpoint_arn: EndpointArn of endpoint to delete. """ params = {} if endpoint_arn is not None: params['EndpointArn'] = endpoint_arn return self._make_request(action='DeleteEndpoint', params=params)
[ "def", "delete_endpoint", "(", "self", ",", "endpoint_arn", "=", "None", ")", ":", "params", "=", "{", "}", "if", "endpoint_arn", "is", "not", "None", ":", "params", "[", "'EndpointArn'", "]", "=", "endpoint_arn", "return", "self", ".", "_make_request", "(", "action", "=", "'DeleteEndpoint'", ",", "params", "=", "params", ")" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/boto-2.46.1/boto/sns/connection.py#L684-L697
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
thirdparty_libs/geopy/point.py
python
Point.from_sequence
(cls, seq)
return cls(*args)
Create and return a new Point instance from any iterable with 0 to 3 elements. The elements, if present, must be latitude, longitude, and altitude, respectively.
Create and return a new Point instance from any iterable with 0 to 3 elements. The elements, if present, must be latitude, longitude, and altitude, respectively.
[ "Create", "and", "return", "a", "new", "Point", "instance", "from", "any", "iterable", "with", "0", "to", "3", "elements", ".", "The", "elements", "if", "present", "must", "be", "latitude", "longitude", "and", "altitude", "respectively", "." ]
def from_sequence(cls, seq): """ Create and return a new Point instance from any iterable with 0 to 3 elements. The elements, if present, must be latitude, longitude, and altitude, respectively. """ args = tuple(islice(seq, 4)) return cls(*args)
[ "def", "from_sequence", "(", "cls", ",", "seq", ")", ":", "args", "=", "tuple", "(", "islice", "(", "seq", ",", "4", ")", ")", "return", "cls", "(", "*", "args", ")" ]
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/thirdparty_libs/geopy/point.py#L284-L292
pyvisa/pyvisa
ae8c8b1180851ee4d120bc3527923c944b9623d6
pyvisa/events.py
python
Event.context
(self)
return c
Access the VISA context used to retrieve attributes. This is equivalent to the session on a resource.
Access the VISA context used to retrieve attributes.
[ "Access", "the", "VISA", "context", "used", "to", "retrieve", "attributes", "." ]
def context(self) -> VISAEventContext: """Access the VISA context used to retrieve attributes. This is equivalent to the session on a resource. """ c = self._context if c is None: raise errors.InvalidSession() return c
[ "def", "context", "(", "self", ")", "->", "VISAEventContext", ":", "c", "=", "self", ".", "_context", "if", "c", "is", "None", ":", "raise", "errors", ".", "InvalidSession", "(", ")", "return", "c" ]
https://github.com/pyvisa/pyvisa/blob/ae8c8b1180851ee4d120bc3527923c944b9623d6/pyvisa/events.py#L97-L106
minerllabs/minerl
0123527c334c96ebb3f0cf313df1552fa4302691
minerl/herobraine/hero/handlers/agent/observations/lifestats.py
python
_SaturationObservation.__init__
(self)
[]
def __init__(self): super().__init__(hero_keys=['saturation'], univ_keys=['saturation'], space=spaces.Box(low=0, high=mc.MAX_FOOD_SATURATION, shape=(), dtype=np.float), default_if_missing=5.0)
[ "def", "__init__", "(", "self", ")", ":", "super", "(", ")", ".", "__init__", "(", "hero_keys", "=", "[", "'saturation'", "]", ",", "univ_keys", "=", "[", "'saturation'", "]", ",", "space", "=", "spaces", ".", "Box", "(", "low", "=", "0", ",", "high", "=", "mc", ".", "MAX_FOOD_SATURATION", ",", "shape", "=", "(", ")", ",", "dtype", "=", "np", ".", "float", ")", ",", "default_if_missing", "=", "5.0", ")" ]
https://github.com/minerllabs/minerl/blob/0123527c334c96ebb3f0cf313df1552fa4302691/minerl/herobraine/hero/handlers/agent/observations/lifestats.py#L105-L108
nadineproject/nadine
c41c8ef7ffe18f1853029c97eecc329039b4af6c
doors/hid_control.py
python
HIDDoorController.lock_door
(self)
[]
def lock_door(self): xml = door_command("lockDoor") self.__send_xml(xml)
[ "def", "lock_door", "(", "self", ")", ":", "xml", "=", "door_command", "(", "\"lockDoor\"", ")", "self", ".", "__send_xml", "(", "xml", ")" ]
https://github.com/nadineproject/nadine/blob/c41c8ef7ffe18f1853029c97eecc329039b4af6c/doors/hid_control.py#L190-L192
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/analyses/decompiler/optimization_passes/multi_simplifier.py
python
MultiSimplifierAILEngine._ail_handle_Sub
(self, expr)
return expr
[]
def _ail_handle_Sub(self, expr): operand_0 = self._expr(expr.operands[0]) operand_1 = self._expr(expr.operands[1]) # x + x = 2*x if type(operand_0) in [Expr.Convert, Expr.Register]: if isinstance(operand_1, (Expr.Convert, Expr.Register)): if operand_0 == operand_1: count = Expr.Const(expr.idx, None, 0, 8) new_expr = Expr.BinaryOp(expr.idx, 'Mul', [operand_1, count], expr.signed, **expr.tags) return new_expr # 2*x - x = x if Expr.BinaryOp in [type(operand_0), type(operand_1)]: if isinstance(operand_1, Expr.BinaryOp) and operand_1.op == 'Mul' and \ (not isinstance(operand_0, Expr.BinaryOp) or \ (isinstance(operand_0, Expr.BinaryOp) and operand_0.op != 'Mul')): x0 = operand_0 x1_index = 0 if isinstance(operand_1.operands[1], Expr.Const) else 1 x1 = operand_1.operands[x1_index] const_x1 = operand_1.operands[1-x1_index] if x0 == x1: new_const = Expr.Const(const_x1.idx, None, const_x1.value-1, const_x1.bits) new_expr = Expr.BinaryOp(expr.idx, 'Mul', [x0, new_const], expr.signed, **expr.tags) return new_expr elif isinstance(operand_0, Expr.BinaryOp) and operand_0.op == 'Mul' and \ (not isinstance(operand_1, Expr.BinaryOp) or \ (isinstance(operand_1, Expr.BinaryOp) and operand_1.op != 'Mul')): x1 = operand_1 x0_index = 0 if isinstance(operand_0.operands[1], Expr.Const) else 1 x0 = operand_0.operands[x0_index] const_x0 = operand_0.operands[1-x0_index] if x0 == x1: new_const = Expr.Const(const_x0.idx, None, const_x0.value-1, const_x0.bits) new_expr = Expr.BinaryOp(expr.idx, 'Mul', [x1, new_const], expr.signed, **expr.tags) return new_expr # 3*x - 2*x = x elif isinstance(operand_0, Expr.BinaryOp) and isinstance(operand_1, Expr.BinaryOp) and \ operand_0.op == 'Mul' and operand_1.op == 'Mul': if Expr.Const in [type(operand_0.operands[0]), type(operand_0.operands[1])] \ and Expr.Const in [type(operand_1.operands[0]), type(operand_1.operands[1])]: x0_index = 0 if isinstance(operand_0.operands[1], Expr.Const) else 1 x0 = operand_0.operands[x0_index] const_x0 = operand_0.operands[1-x0_index] x1_index = 0 if isinstance(operand_1.operands[1], Expr.Const) else 1 x1 = operand_1.operands[x1_index] const_x1 = operand_1.operands[1-x1_index] if x0 == x1: new_const = Expr.Const(const_x1.idx, None, const_x0.value-const_x1.value, const_x1.bits) new_expr = Expr.BinaryOp(expr.idx, 'Mul', [x0, new_const], expr.signed, **expr.tags) return new_expr if (operand_0, operand_1) != (expr.operands[0], expr.operands[1]): return Expr.BinaryOp(expr.idx, 'Sub', [operand_0, operand_1], expr.signed, **expr.tags) return expr
[ "def", "_ail_handle_Sub", "(", "self", ",", "expr", ")", ":", "operand_0", "=", "self", ".", "_expr", "(", "expr", ".", "operands", "[", "0", "]", ")", "operand_1", "=", "self", ".", "_expr", "(", "expr", ".", "operands", "[", "1", "]", ")", "# x + x = 2*x", "if", "type", "(", "operand_0", ")", "in", "[", "Expr", ".", "Convert", ",", "Expr", ".", "Register", "]", ":", "if", "isinstance", "(", "operand_1", ",", "(", "Expr", ".", "Convert", ",", "Expr", ".", "Register", ")", ")", ":", "if", "operand_0", "==", "operand_1", ":", "count", "=", "Expr", ".", "Const", "(", "expr", ".", "idx", ",", "None", ",", "0", ",", "8", ")", "new_expr", "=", "Expr", ".", "BinaryOp", "(", "expr", ".", "idx", ",", "'Mul'", ",", "[", "operand_1", ",", "count", "]", ",", "expr", ".", "signed", ",", "*", "*", "expr", ".", "tags", ")", "return", "new_expr", "# 2*x - x = x", "if", "Expr", ".", "BinaryOp", "in", "[", "type", "(", "operand_0", ")", ",", "type", "(", "operand_1", ")", "]", ":", "if", "isinstance", "(", "operand_1", ",", "Expr", ".", "BinaryOp", ")", "and", "operand_1", ".", "op", "==", "'Mul'", "and", "(", "not", "isinstance", "(", "operand_0", ",", "Expr", ".", "BinaryOp", ")", "or", "(", "isinstance", "(", "operand_0", ",", "Expr", ".", "BinaryOp", ")", "and", "operand_0", ".", "op", "!=", "'Mul'", ")", ")", ":", "x0", "=", "operand_0", "x1_index", "=", "0", "if", "isinstance", "(", "operand_1", ".", "operands", "[", "1", "]", ",", "Expr", ".", "Const", ")", "else", "1", "x1", "=", "operand_1", ".", "operands", "[", "x1_index", "]", "const_x1", "=", "operand_1", ".", "operands", "[", "1", "-", "x1_index", "]", "if", "x0", "==", "x1", ":", "new_const", "=", "Expr", ".", "Const", "(", "const_x1", ".", "idx", ",", "None", ",", "const_x1", ".", "value", "-", "1", ",", "const_x1", ".", "bits", ")", "new_expr", "=", "Expr", ".", "BinaryOp", "(", "expr", ".", "idx", ",", "'Mul'", ",", "[", "x0", ",", "new_const", "]", ",", "expr", ".", "signed", ",", "*", "*", "expr", ".", "tags", ")", "return", "new_expr", "elif", "isinstance", "(", "operand_0", ",", "Expr", ".", "BinaryOp", ")", "and", "operand_0", ".", "op", "==", "'Mul'", "and", "(", "not", "isinstance", "(", "operand_1", ",", "Expr", ".", "BinaryOp", ")", "or", "(", "isinstance", "(", "operand_1", ",", "Expr", ".", "BinaryOp", ")", "and", "operand_1", ".", "op", "!=", "'Mul'", ")", ")", ":", "x1", "=", "operand_1", "x0_index", "=", "0", "if", "isinstance", "(", "operand_0", ".", "operands", "[", "1", "]", ",", "Expr", ".", "Const", ")", "else", "1", "x0", "=", "operand_0", ".", "operands", "[", "x0_index", "]", "const_x0", "=", "operand_0", ".", "operands", "[", "1", "-", "x0_index", "]", "if", "x0", "==", "x1", ":", "new_const", "=", "Expr", ".", "Const", "(", "const_x0", ".", "idx", ",", "None", ",", "const_x0", ".", "value", "-", "1", ",", "const_x0", ".", "bits", ")", "new_expr", "=", "Expr", ".", "BinaryOp", "(", "expr", ".", "idx", ",", "'Mul'", ",", "[", "x1", ",", "new_const", "]", ",", "expr", ".", "signed", ",", "*", "*", "expr", ".", "tags", ")", "return", "new_expr", "# 3*x - 2*x = x", "elif", "isinstance", "(", "operand_0", ",", "Expr", ".", "BinaryOp", ")", "and", "isinstance", "(", "operand_1", ",", "Expr", ".", "BinaryOp", ")", "and", "operand_0", ".", "op", "==", "'Mul'", "and", "operand_1", ".", "op", "==", "'Mul'", ":", "if", "Expr", ".", "Const", "in", "[", "type", "(", "operand_0", ".", "operands", "[", "0", "]", ")", ",", "type", "(", "operand_0", ".", "operands", "[", "1", "]", ")", "]", "and", "Expr", ".", "Const", "in", "[", "type", "(", "operand_1", ".", "operands", "[", "0", "]", ")", ",", "type", "(", "operand_1", ".", "operands", "[", "1", "]", ")", "]", ":", "x0_index", "=", "0", "if", "isinstance", "(", "operand_0", ".", "operands", "[", "1", "]", ",", "Expr", ".", "Const", ")", "else", "1", "x0", "=", "operand_0", ".", "operands", "[", "x0_index", "]", "const_x0", "=", "operand_0", ".", "operands", "[", "1", "-", "x0_index", "]", "x1_index", "=", "0", "if", "isinstance", "(", "operand_1", ".", "operands", "[", "1", "]", ",", "Expr", ".", "Const", ")", "else", "1", "x1", "=", "operand_1", ".", "operands", "[", "x1_index", "]", "const_x1", "=", "operand_1", ".", "operands", "[", "1", "-", "x1_index", "]", "if", "x0", "==", "x1", ":", "new_const", "=", "Expr", ".", "Const", "(", "const_x1", ".", "idx", ",", "None", ",", "const_x0", ".", "value", "-", "const_x1", ".", "value", ",", "const_x1", ".", "bits", ")", "new_expr", "=", "Expr", ".", "BinaryOp", "(", "expr", ".", "idx", ",", "'Mul'", ",", "[", "x0", ",", "new_const", "]", ",", "expr", ".", "signed", ",", "*", "*", "expr", ".", "tags", ")", "return", "new_expr", "if", "(", "operand_0", ",", "operand_1", ")", "!=", "(", "expr", ".", "operands", "[", "0", "]", ",", "expr", ".", "operands", "[", "1", "]", ")", ":", "return", "Expr", ".", "BinaryOp", "(", "expr", ".", "idx", ",", "'Sub'", ",", "[", "operand_0", ",", "operand_1", "]", ",", "expr", ".", "signed", ",", "*", "*", "expr", ".", "tags", ")", "return", "expr" ]
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/analyses/decompiler/optimization_passes/multi_simplifier.py#L72-L130
rhiever/TwitterFollowBot
601a01ea2a745695566af704e215d85a24cb4a28
TwitterFollowBot/__init__.py
python
TwitterBot.bot_setup
(self, config_file="config.txt")
Reads in the bot configuration file and sets up the bot. Defaults to config.txt if no configuration file is specified. If you want to modify the bot configuration, edit your config.txt.
Reads in the bot configuration file and sets up the bot.
[ "Reads", "in", "the", "bot", "configuration", "file", "and", "sets", "up", "the", "bot", "." ]
def bot_setup(self, config_file="config.txt"): """ Reads in the bot configuration file and sets up the bot. Defaults to config.txt if no configuration file is specified. If you want to modify the bot configuration, edit your config.txt. """ with open(config_file, "r") as in_file: for line in in_file: line = line.split(":") parameter = line[0].strip() value = line[1].strip() if parameter in ["USERS_KEEP_FOLLOWING", "USERS_KEEP_UNMUTED", "USERS_KEEP_MUTED"]: if value != "": self.BOT_CONFIG[parameter] = set([int(x) for x in value.split(",")]) else: self.BOT_CONFIG[parameter] = set() elif parameter in ["FOLLOW_BACKOFF_MIN_SECONDS", "FOLLOW_BACKOFF_MAX_SECONDS"]: self.BOT_CONFIG[parameter] = int(value) else: self.BOT_CONFIG[parameter] = value # make sure that the config file specifies all required parameters required_parameters = ["OAUTH_TOKEN", "OAUTH_SECRET", "CONSUMER_KEY", "CONSUMER_SECRET", "TWITTER_HANDLE", "ALREADY_FOLLOWED_FILE", "FOLLOWERS_FILE", "FOLLOWS_FILE"] missing_parameters = [] for required_parameter in required_parameters: if (required_parameter not in self.BOT_CONFIG or self.BOT_CONFIG[required_parameter] == ""): missing_parameters.append(required_parameter) if len(missing_parameters) > 0: self.BOT_CONFIG = {} raise Exception("Please edit %s to include the following parameters: %s.\n\n" "The bot cannot run unless these parameters are specified." % (config_file, ", ".join(missing_parameters))) # make sure all of the sync files exist locally for sync_file in [self.BOT_CONFIG["ALREADY_FOLLOWED_FILE"], self.BOT_CONFIG["FOLLOWS_FILE"], self.BOT_CONFIG["FOLLOWERS_FILE"]]: if not os.path.isfile(sync_file): with open(sync_file, "w") as out_file: out_file.write("") # check how old the follower sync files are and recommend updating them # if they are old if (time.time() - os.path.getmtime(self.BOT_CONFIG["FOLLOWS_FILE"]) > 86400 or time.time() - os.path.getmtime(self.BOT_CONFIG["FOLLOWERS_FILE"]) > 86400): print("Warning: Your Twitter follower sync files are more than a day old. " "It is highly recommended that you sync them by calling sync_follows() " "before continuing.", file=sys.stderr) # create an authorized connection to the Twitter API self.TWITTER_CONNECTION = Twitter(auth=OAuth(self.BOT_CONFIG["OAUTH_TOKEN"], self.BOT_CONFIG["OAUTH_SECRET"], self.BOT_CONFIG["CONSUMER_KEY"], self.BOT_CONFIG["CONSUMER_SECRET"]))
[ "def", "bot_setup", "(", "self", ",", "config_file", "=", "\"config.txt\"", ")", ":", "with", "open", "(", "config_file", ",", "\"r\"", ")", "as", "in_file", ":", "for", "line", "in", "in_file", ":", "line", "=", "line", ".", "split", "(", "\":\"", ")", "parameter", "=", "line", "[", "0", "]", ".", "strip", "(", ")", "value", "=", "line", "[", "1", "]", ".", "strip", "(", ")", "if", "parameter", "in", "[", "\"USERS_KEEP_FOLLOWING\"", ",", "\"USERS_KEEP_UNMUTED\"", ",", "\"USERS_KEEP_MUTED\"", "]", ":", "if", "value", "!=", "\"\"", ":", "self", ".", "BOT_CONFIG", "[", "parameter", "]", "=", "set", "(", "[", "int", "(", "x", ")", "for", "x", "in", "value", ".", "split", "(", "\",\"", ")", "]", ")", "else", ":", "self", ".", "BOT_CONFIG", "[", "parameter", "]", "=", "set", "(", ")", "elif", "parameter", "in", "[", "\"FOLLOW_BACKOFF_MIN_SECONDS\"", ",", "\"FOLLOW_BACKOFF_MAX_SECONDS\"", "]", ":", "self", ".", "BOT_CONFIG", "[", "parameter", "]", "=", "int", "(", "value", ")", "else", ":", "self", ".", "BOT_CONFIG", "[", "parameter", "]", "=", "value", "# make sure that the config file specifies all required parameters", "required_parameters", "=", "[", "\"OAUTH_TOKEN\"", ",", "\"OAUTH_SECRET\"", ",", "\"CONSUMER_KEY\"", ",", "\"CONSUMER_SECRET\"", ",", "\"TWITTER_HANDLE\"", ",", "\"ALREADY_FOLLOWED_FILE\"", ",", "\"FOLLOWERS_FILE\"", ",", "\"FOLLOWS_FILE\"", "]", "missing_parameters", "=", "[", "]", "for", "required_parameter", "in", "required_parameters", ":", "if", "(", "required_parameter", "not", "in", "self", ".", "BOT_CONFIG", "or", "self", ".", "BOT_CONFIG", "[", "required_parameter", "]", "==", "\"\"", ")", ":", "missing_parameters", ".", "append", "(", "required_parameter", ")", "if", "len", "(", "missing_parameters", ")", ">", "0", ":", "self", ".", "BOT_CONFIG", "=", "{", "}", "raise", "Exception", "(", "\"Please edit %s to include the following parameters: %s.\\n\\n\"", "\"The bot cannot run unless these parameters are specified.\"", "%", "(", "config_file", ",", "\", \"", ".", "join", "(", "missing_parameters", ")", ")", ")", "# make sure all of the sync files exist locally", "for", "sync_file", "in", "[", "self", ".", "BOT_CONFIG", "[", "\"ALREADY_FOLLOWED_FILE\"", "]", ",", "self", ".", "BOT_CONFIG", "[", "\"FOLLOWS_FILE\"", "]", ",", "self", ".", "BOT_CONFIG", "[", "\"FOLLOWERS_FILE\"", "]", "]", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "sync_file", ")", ":", "with", "open", "(", "sync_file", ",", "\"w\"", ")", "as", "out_file", ":", "out_file", ".", "write", "(", "\"\"", ")", "# check how old the follower sync files are and recommend updating them", "# if they are old", "if", "(", "time", ".", "time", "(", ")", "-", "os", ".", "path", ".", "getmtime", "(", "self", ".", "BOT_CONFIG", "[", "\"FOLLOWS_FILE\"", "]", ")", ">", "86400", "or", "time", ".", "time", "(", ")", "-", "os", ".", "path", ".", "getmtime", "(", "self", ".", "BOT_CONFIG", "[", "\"FOLLOWERS_FILE\"", "]", ")", ">", "86400", ")", ":", "print", "(", "\"Warning: Your Twitter follower sync files are more than a day old. \"", "\"It is highly recommended that you sync them by calling sync_follows() \"", "\"before continuing.\"", ",", "file", "=", "sys", ".", "stderr", ")", "# create an authorized connection to the Twitter API", "self", ".", "TWITTER_CONNECTION", "=", "Twitter", "(", "auth", "=", "OAuth", "(", "self", ".", "BOT_CONFIG", "[", "\"OAUTH_TOKEN\"", "]", ",", "self", ".", "BOT_CONFIG", "[", "\"OAUTH_SECRET\"", "]", ",", "self", ".", "BOT_CONFIG", "[", "\"CONSUMER_KEY\"", "]", ",", "self", ".", "BOT_CONFIG", "[", "\"CONSUMER_SECRET\"", "]", ")", ")" ]
https://github.com/rhiever/TwitterFollowBot/blob/601a01ea2a745695566af704e215d85a24cb4a28/TwitterFollowBot/__init__.py#L69-L133
TensorVision/TensorVision
d971ed2b7d8fe1c0caf407eb7bdaebc0838e5801
tensorvision/utils.py
python
load_segmentation_mask
(hypes, gt_image_path)
return gt
Load a segmentation mask from an image. The mask is an integer array with shape (height, width). The integer values range from 0 to N-1, where N is the total number of classes. This requires hypes to have an entry 'classes'. This entry has to be a list of dictionaries with key `colors`. This key is a list of HTML color strings in RGB format. ``` "classes": [ {"name": "road", "colors": ["#ff0000", "#ff1000"], "output": "#00ff007f"}, {"name": "background", "colors": ["default", "#ff0000"], "output": "#ff00007f"}, {"name": "ignore", "colors": ["#000000"]} ], ``` The string `default` in the color list may only be in one class. If there are colors which are not mapped to any other class, the class with "default" gets assigned. The index of the dictionary in the list is the value of the integer matrix which is returned. Parameters ---------- hypes : dict Hyperparameters gt_image_path : str Path to an image file. Returns ------- numpy array The ground truth mask. Note ---- This function always loads the ground truth image in RGB mode. If the image is not in RGB mode it will get converted to RGB. This is important to know for the colors in hypes['classes'].
Load a segmentation mask from an image.
[ "Load", "a", "segmentation", "mask", "from", "an", "image", "." ]
def load_segmentation_mask(hypes, gt_image_path): """ Load a segmentation mask from an image. The mask is an integer array with shape (height, width). The integer values range from 0 to N-1, where N is the total number of classes. This requires hypes to have an entry 'classes'. This entry has to be a list of dictionaries with key `colors`. This key is a list of HTML color strings in RGB format. ``` "classes": [ {"name": "road", "colors": ["#ff0000", "#ff1000"], "output": "#00ff007f"}, {"name": "background", "colors": ["default", "#ff0000"], "output": "#ff00007f"}, {"name": "ignore", "colors": ["#000000"]} ], ``` The string `default` in the color list may only be in one class. If there are colors which are not mapped to any other class, the class with "default" gets assigned. The index of the dictionary in the list is the value of the integer matrix which is returned. Parameters ---------- hypes : dict Hyperparameters gt_image_path : str Path to an image file. Returns ------- numpy array The ground truth mask. Note ---- This function always loads the ground truth image in RGB mode. If the image is not in RGB mode it will get converted to RGB. This is important to know for the colors in hypes['classes']. """ img = scipy.misc.imread(gt_image_path, mode='RGB') # map colors to classes color2class_dict, default_class = get_color2class(hypes) # Create gt image which is a matrix of classes gt = np.zeros((img.shape[0], img.shape[1]), dtype=int) # only one channel assigned = np.zeros((img.shape[0], img.shape[1]), dtype=int) for color, class_label in color2class_dict.items(): affected_pixels = np.all(img == color, axis=2) gt += affected_pixels * class_label assigned += affected_pixels remaining_pixels = np.logical_not(assigned) if np.any(remaining_pixels): if default_class is None: print("[ERROR] Some pixels did not get assigned a class. ") print("No 'default' class was assigned either.") print("The pixel colors are:") for i, row in enumerate(img): for j, pixel in enumerate(row): pixel_color = tuple(pixel) if remaining_pixels[i][j]: print(" %s" % str(pixel_color)) sys.exit(-1) else: gt += remaining_pixels * default_class return gt
[ "def", "load_segmentation_mask", "(", "hypes", ",", "gt_image_path", ")", ":", "img", "=", "scipy", ".", "misc", ".", "imread", "(", "gt_image_path", ",", "mode", "=", "'RGB'", ")", "# map colors to classes", "color2class_dict", ",", "default_class", "=", "get_color2class", "(", "hypes", ")", "# Create gt image which is a matrix of classes", "gt", "=", "np", ".", "zeros", "(", "(", "img", ".", "shape", "[", "0", "]", ",", "img", ".", "shape", "[", "1", "]", ")", ",", "dtype", "=", "int", ")", "# only one channel", "assigned", "=", "np", ".", "zeros", "(", "(", "img", ".", "shape", "[", "0", "]", ",", "img", ".", "shape", "[", "1", "]", ")", ",", "dtype", "=", "int", ")", "for", "color", ",", "class_label", "in", "color2class_dict", ".", "items", "(", ")", ":", "affected_pixels", "=", "np", ".", "all", "(", "img", "==", "color", ",", "axis", "=", "2", ")", "gt", "+=", "affected_pixels", "*", "class_label", "assigned", "+=", "affected_pixels", "remaining_pixels", "=", "np", ".", "logical_not", "(", "assigned", ")", "if", "np", ".", "any", "(", "remaining_pixels", ")", ":", "if", "default_class", "is", "None", ":", "print", "(", "\"[ERROR] Some pixels did not get assigned a class. \"", ")", "print", "(", "\"No 'default' class was assigned either.\"", ")", "print", "(", "\"The pixel colors are:\"", ")", "for", "i", ",", "row", "in", "enumerate", "(", "img", ")", ":", "for", "j", ",", "pixel", "in", "enumerate", "(", "row", ")", ":", "pixel_color", "=", "tuple", "(", "pixel", ")", "if", "remaining_pixels", "[", "i", "]", "[", "j", "]", ":", "print", "(", "\" %s\"", "%", "str", "(", "pixel_color", ")", ")", "sys", ".", "exit", "(", "-", "1", ")", "else", ":", "gt", "+=", "remaining_pixels", "*", "default_class", "return", "gt" ]
https://github.com/TensorVision/TensorVision/blob/d971ed2b7d8fe1c0caf407eb7bdaebc0838e5801/tensorvision/utils.py#L578-L653
meetbill/zabbix_manager
739e5b51facf19cc6bda2b50f29108f831cf833e
ZabbixTool/lib_zabbix/w_lib/zabbix_api_lib.py
python
ZabbixAPISubClass.universal
(self, **opts)
return opts
[]
def universal(self, **opts): return opts
[ "def", "universal", "(", "self", ",", "*", "*", "opts", ")", ":", "return", "opts" ]
https://github.com/meetbill/zabbix_manager/blob/739e5b51facf19cc6bda2b50f29108f831cf833e/ZabbixTool/lib_zabbix/w_lib/zabbix_api_lib.py#L347-L348
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/utils/timezone.py
python
override.__init__
(self, timezone)
[]
def __init__(self, timezone): self.timezone = timezone
[ "def", "__init__", "(", "self", ",", "timezone", ")", ":", "self", ".", "timezone", "=", "timezone" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/utils/timezone.py#L263-L264
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
python/federatedml/ensemble/basic_algorithms/decision_tree/tree_core/criterion.py
python
XgboostCriterion.node_weight
(self, sum_grad, sum_hess)
return self.truncate(-(self._g_alpha_cmp(sum_grad, self.reg_alpha)) / (sum_hess + self.reg_lambda))
[]
def node_weight(self, sum_grad, sum_hess): return self.truncate(-(self._g_alpha_cmp(sum_grad, self.reg_alpha)) / (sum_hess + self.reg_lambda))
[ "def", "node_weight", "(", "self", ",", "sum_grad", ",", "sum_hess", ")", ":", "return", "self", ".", "truncate", "(", "-", "(", "self", ".", "_g_alpha_cmp", "(", "sum_grad", ",", "self", ".", "reg_alpha", ")", ")", "/", "(", "sum_hess", "+", "self", ".", "reg_lambda", ")", ")" ]
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/federatedml/ensemble/basic_algorithms/decision_tree/tree_core/criterion.py#L76-L77
KunpengLi1994/VSRN
777ae74326fdb6abe69dbd3911d0e545322520d1
coco-caption/pycocoevalcap/bleu/bleu_scorer.py
python
cook_refs
(refs, eff=None, n=4)
return (reflen, maxcounts)
Takes a list of reference sentences for a single segment and returns an object that encapsulates everything that BLEU needs to know about them.
Takes a list of reference sentences for a single segment and returns an object that encapsulates everything that BLEU needs to know about them.
[ "Takes", "a", "list", "of", "reference", "sentences", "for", "a", "single", "segment", "and", "returns", "an", "object", "that", "encapsulates", "everything", "that", "BLEU", "needs", "to", "know", "about", "them", "." ]
def cook_refs(refs, eff=None, n=4): ## lhuang: oracle will call with "average" '''Takes a list of reference sentences for a single segment and returns an object that encapsulates everything that BLEU needs to know about them.''' reflen = [] maxcounts = {} for ref in refs: rl, counts = precook(ref, n) reflen.append(rl) for (ngram,count) in counts.items(): maxcounts[ngram] = max(maxcounts.get(ngram,0), count) # Calculate effective reference sentence length. if eff == "shortest": reflen = min(reflen) elif eff == "average": reflen = float(sum(reflen))/len(reflen) ## lhuang: N.B.: leave reflen computaiton to the very end!! ## lhuang: N.B.: in case of "closest", keep a list of reflens!! (bad design) return (reflen, maxcounts)
[ "def", "cook_refs", "(", "refs", ",", "eff", "=", "None", ",", "n", "=", "4", ")", ":", "## lhuang: oracle will call with \"average\"", "reflen", "=", "[", "]", "maxcounts", "=", "{", "}", "for", "ref", "in", "refs", ":", "rl", ",", "counts", "=", "precook", "(", "ref", ",", "n", ")", "reflen", ".", "append", "(", "rl", ")", "for", "(", "ngram", ",", "count", ")", "in", "counts", ".", "items", "(", ")", ":", "maxcounts", "[", "ngram", "]", "=", "max", "(", "maxcounts", ".", "get", "(", "ngram", ",", "0", ")", ",", "count", ")", "# Calculate effective reference sentence length.", "if", "eff", "==", "\"shortest\"", ":", "reflen", "=", "min", "(", "reflen", ")", "elif", "eff", "==", "\"average\"", ":", "reflen", "=", "float", "(", "sum", "(", "reflen", ")", ")", "/", "len", "(", "reflen", ")", "## lhuang: N.B.: leave reflen computaiton to the very end!!", "## lhuang: N.B.: in case of \"closest\", keep a list of reflens!! (bad design)", "return", "(", "reflen", ",", "maxcounts", ")" ]
https://github.com/KunpengLi1994/VSRN/blob/777ae74326fdb6abe69dbd3911d0e545322520d1/coco-caption/pycocoevalcap/bleu/bleu_scorer.py#L35-L58
robhagemans/pcbasic
c3a043b46af66623a801e18a38175be077251ada
pcbasic/basic/interpreter.py
python
Interpreter._add_common_vars
(self, common_scalars, common_arrays)
COMMON: define variables to be preserved on CHAIN.
COMMON: define variables to be preserved on CHAIN.
[ "COMMON", ":", "define", "variables", "to", "be", "preserved", "on", "CHAIN", "." ]
def _add_common_vars(self, common_scalars, common_arrays): """COMMON: define variables to be preserved on CHAIN.""" common_vars = list(self._parse_common_args(self._program_code)) common_scalars.update( self._memory.complete_name(name) for name, brackets in common_vars if not brackets ) common_arrays.update( self._memory.complete_name(name) for name, brackets in common_vars if brackets )
[ "def", "_add_common_vars", "(", "self", ",", "common_scalars", ",", "common_arrays", ")", ":", "common_vars", "=", "list", "(", "self", ".", "_parse_common_args", "(", "self", ".", "_program_code", ")", ")", "common_scalars", ".", "update", "(", "self", ".", "_memory", ".", "complete_name", "(", "name", ")", "for", "name", ",", "brackets", "in", "common_vars", "if", "not", "brackets", ")", "common_arrays", ".", "update", "(", "self", ".", "_memory", ".", "complete_name", "(", "name", ")", "for", "name", ",", "brackets", "in", "common_vars", "if", "brackets", ")" ]
https://github.com/robhagemans/pcbasic/blob/c3a043b46af66623a801e18a38175be077251ada/pcbasic/basic/interpreter.py#L605-L615
CalebBell/thermo
572a47d1b03d49fe609b8d5f826fa6a7cde00828
thermo/eos.py
python
GCEOS.dbeta_dP_g
(self)
return V_inv*(self.d2V_dTdP_g - dV_dT*dV_dP*V_inv)
r'''Derivative of isobaric expansion coefficient with respect to pressure for the gas phase, [1/(Pa*K)]. .. math:: \frac{\partial \beta_g}{\partial P} = \frac{\frac{\partial^{2}} {\partial T\partial P} V{\left (T,P \right )_g}}{V{\left (T, P \right )_g}} - \frac{\frac{\partial}{\partial P} V{\left (T,P \right )_g} \frac{\partial}{\partial T} V{\left (T,P \right )_g}} {V^{2}{\left (T,P \right )_g}}
r'''Derivative of isobaric expansion coefficient with respect to pressure for the gas phase, [1/(Pa*K)].
[ "r", "Derivative", "of", "isobaric", "expansion", "coefficient", "with", "respect", "to", "pressure", "for", "the", "gas", "phase", "[", "1", "/", "(", "Pa", "*", "K", ")", "]", "." ]
def dbeta_dP_g(self): r'''Derivative of isobaric expansion coefficient with respect to pressure for the gas phase, [1/(Pa*K)]. .. math:: \frac{\partial \beta_g}{\partial P} = \frac{\frac{\partial^{2}} {\partial T\partial P} V{\left (T,P \right )_g}}{V{\left (T, P \right )_g}} - \frac{\frac{\partial}{\partial P} V{\left (T,P \right )_g} \frac{\partial}{\partial T} V{\left (T,P \right )_g}} {V^{2}{\left (T,P \right )_g}} ''' V_inv = 1.0/self.V_g dV_dT = self.dV_dT_g dV_dP = self.dV_dP_g return V_inv*(self.d2V_dTdP_g - dV_dT*dV_dP*V_inv)
[ "def", "dbeta_dP_g", "(", "self", ")", ":", "V_inv", "=", "1.0", "/", "self", ".", "V_g", "dV_dT", "=", "self", ".", "dV_dT_g", "dV_dP", "=", "self", ".", "dV_dP_g", "return", "V_inv", "*", "(", "self", ".", "d2V_dTdP_g", "-", "dV_dT", "*", "dV_dP", "*", "V_inv", ")" ]
https://github.com/CalebBell/thermo/blob/572a47d1b03d49fe609b8d5f826fa6a7cde00828/thermo/eos.py#L6739-L6753
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/xml/dom/minidom.py
python
parse
(file, parser=None, bufsize=None)
Parse a file into a DOM by filename or file object.
Parse a file into a DOM by filename or file object.
[ "Parse", "a", "file", "into", "a", "DOM", "by", "filename", "or", "file", "object", "." ]
def parse(file, parser=None, bufsize=None): """Parse a file into a DOM by filename or file object.""" if parser is None and not bufsize: from xml.dom import expatbuilder return expatbuilder.parse(file) else: from xml.dom import pulldom return _do_pulldom_parse(pulldom.parse, (file,), {'parser': parser, 'bufsize': bufsize})
[ "def", "parse", "(", "file", ",", "parser", "=", "None", ",", "bufsize", "=", "None", ")", ":", "if", "parser", "is", "None", "and", "not", "bufsize", ":", "from", "xml", ".", "dom", "import", "expatbuilder", "return", "expatbuilder", ".", "parse", "(", "file", ")", "else", ":", "from", "xml", ".", "dom", "import", "pulldom", "return", "_do_pulldom_parse", "(", "pulldom", ".", "parse", ",", "(", "file", ",", ")", ",", "{", "'parser'", ":", "parser", ",", "'bufsize'", ":", "bufsize", "}", ")" ]
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/xml/dom/minidom.py#L1984-L1992
cuemacro/findatapy
8ce72b17cc4dd3e3f53f0ab8adf58b6eeae29c10
findatapy/market/ioengine.py
python
IOEngine.read_time_series_cache_from_disk
(self, fname, engine='hdf5', start_date=None, finish_date=None, db_server=constants.db_server, db_port=constants.db_port, username=constants.db_username, password=constants.db_password)
return data_frame_list
Reads time series cache from disk in either HDF5 or bcolz Parameters ---------- fname : str (or list) file to be read from engine : str (optional) 'hd5' - reads HDF5 files (default) 'arctic' - reads from Arctic/MongoDB database 'bcolz' - reads from bcolz file (not fully implemented) 'parquet' - reads from Parquet start_date : str/datetime (optional) Start date finish_date : str/datetime (optional) Finish data db_server : str IP address of MongdDB (default '127.0.0.1') Returns ------- DataFrame
Reads time series cache from disk in either HDF5 or bcolz
[ "Reads", "time", "series", "cache", "from", "disk", "in", "either", "HDF5", "or", "bcolz" ]
def read_time_series_cache_from_disk(self, fname, engine='hdf5', start_date=None, finish_date=None, db_server=constants.db_server, db_port=constants.db_port, username=constants.db_username, password=constants.db_password): """Reads time series cache from disk in either HDF5 or bcolz Parameters ---------- fname : str (or list) file to be read from engine : str (optional) 'hd5' - reads HDF5 files (default) 'arctic' - reads from Arctic/MongoDB database 'bcolz' - reads from bcolz file (not fully implemented) 'parquet' - reads from Parquet start_date : str/datetime (optional) Start date finish_date : str/datetime (optional) Finish data db_server : str IP address of MongdDB (default '127.0.0.1') Returns ------- DataFrame """ logger = LoggerManager.getLogger(__name__) data_frame_list = [] if not(isinstance(fname, list)): if '*' in fname: fname = glob.glob(fname) else: fname = [fname] for fname_single in fname: logger.debug("Reading " + fname_single + "..") if engine == 'parquet' and '.gzip' not in fname_single and '.parquet' not in fname_single: fname_single = fname_single + '.parquet' if (engine == 'bcolz'): try: name = self.get_bcolz_filename(fname_single) zlens = bcolz.open(rootdir=name) data_frame = zlens.todataframe() data_frame.index = pd.DatetimeIndex(data_frame['DTS_']) data_frame.index.name = 'Date' del data_frame['DTS_'] # convert invalid characters (which Bcolz can't deal with) to more readable characters for pandas data_frame.columns = self.find_replace_chars(data_frame.columns, _replace_chars, _invalid_chars) data_frame.columns = [x[2:] for x in data_frame.columns] except: data_frame = None elif (engine == 'redis'): fname_single = os.path.basename(fname_single).replace('.', '_') msg = None try: r = redis.StrictRedis(host=db_server, port=db_port, db=0) # is there a compressed key stored?) k = r.keys('comp_' + fname_single) # if so, then it means that we have stored it as a compressed object # if have more than 1 element, take the last (which will be the latest to be added) if (len(k) >= 1): k = k[-1].decode('utf-8') msg = r.get(k) msg = io.BytesIO(msg) msg = pd.read_pickle(msg, compression="gzip") else: msg = r.get(fname_single) msg = pd.read_pickle(msg.read()) except Exception as e: logger.info("Cache not existent for " + fname_single + " in Redis: " + str(e)) if msg is None: data_frame = None else: logger.info('Load Redis cache: ' + fname_single) data_frame = msg # pd.read_msgpack(msg) elif (engine == 'arctic'): socketTimeoutMS = 2 * 1000 import pymongo from arctic import Arctic fname_single = os.path.basename(fname_single).replace('.', '_') logger.info('Load Arctic/MongoDB library: ' + fname_single) if username is not None and password is not None: c = pymongo.MongoClient( host="mongodb://" + username + ":" + password + "@" + str(db_server) + ":" + str(db_port), connect=False) # , username=username, password=password) else: c = pymongo.MongoClient(host="mongodb://" + str(db_server) + ":" + str(db_port), connect=False) store = Arctic(c, socketTimeoutMS=socketTimeoutMS, serverSelectionTimeoutMS=socketTimeoutMS) # Access the library try: library = store[fname_single] if start_date is None and finish_date is None: item = library.read(fname_single) else: from arctic.date import DateRange item = library.read(fname_single, date_range=DateRange(start_date.replace(tzinfo=None), finish_date.replace(tzinfo=None))) c.close() logger.info('Read ' + fname_single) data_frame = item.data except Exception as e: logger.warning('Library may not exist or another error: ' + fname_single + ' & message is ' + str(e)) data_frame = None elif self.path_exists(self.get_h5_filename(fname_single)): store = pd.HDFStore(self.get_h5_filename(fname_single)) data_frame = store.select("data") if ('intraday' in fname_single): data_frame = data_frame.astype('float32') store.close() elif self.path_exists(fname_single) and '.csv' in fname_single: data_frame = pd.read_csv(fname_single, index_col=0) data_frame.index = pd.to_datetime(data_frame.index) elif self.path_exists(fname_single): data_frame = self.read_parquet(fname_single) # data_frame = pd.read_parquet(fname_single) data_frame_list.append(data_frame) if len(data_frame_list) == 0: return None if len(data_frame_list) == 1: return data_frame_list[0] return data_frame_list
[ "def", "read_time_series_cache_from_disk", "(", "self", ",", "fname", ",", "engine", "=", "'hdf5'", ",", "start_date", "=", "None", ",", "finish_date", "=", "None", ",", "db_server", "=", "constants", ".", "db_server", ",", "db_port", "=", "constants", ".", "db_port", ",", "username", "=", "constants", ".", "db_username", ",", "password", "=", "constants", ".", "db_password", ")", ":", "logger", "=", "LoggerManager", ".", "getLogger", "(", "__name__", ")", "data_frame_list", "=", "[", "]", "if", "not", "(", "isinstance", "(", "fname", ",", "list", ")", ")", ":", "if", "'*'", "in", "fname", ":", "fname", "=", "glob", ".", "glob", "(", "fname", ")", "else", ":", "fname", "=", "[", "fname", "]", "for", "fname_single", "in", "fname", ":", "logger", ".", "debug", "(", "\"Reading \"", "+", "fname_single", "+", "\"..\"", ")", "if", "engine", "==", "'parquet'", "and", "'.gzip'", "not", "in", "fname_single", "and", "'.parquet'", "not", "in", "fname_single", ":", "fname_single", "=", "fname_single", "+", "'.parquet'", "if", "(", "engine", "==", "'bcolz'", ")", ":", "try", ":", "name", "=", "self", ".", "get_bcolz_filename", "(", "fname_single", ")", "zlens", "=", "bcolz", ".", "open", "(", "rootdir", "=", "name", ")", "data_frame", "=", "zlens", ".", "todataframe", "(", ")", "data_frame", ".", "index", "=", "pd", ".", "DatetimeIndex", "(", "data_frame", "[", "'DTS_'", "]", ")", "data_frame", ".", "index", ".", "name", "=", "'Date'", "del", "data_frame", "[", "'DTS_'", "]", "# convert invalid characters (which Bcolz can't deal with) to more readable characters for pandas", "data_frame", ".", "columns", "=", "self", ".", "find_replace_chars", "(", "data_frame", ".", "columns", ",", "_replace_chars", ",", "_invalid_chars", ")", "data_frame", ".", "columns", "=", "[", "x", "[", "2", ":", "]", "for", "x", "in", "data_frame", ".", "columns", "]", "except", ":", "data_frame", "=", "None", "elif", "(", "engine", "==", "'redis'", ")", ":", "fname_single", "=", "os", ".", "path", ".", "basename", "(", "fname_single", ")", ".", "replace", "(", "'.'", ",", "'_'", ")", "msg", "=", "None", "try", ":", "r", "=", "redis", ".", "StrictRedis", "(", "host", "=", "db_server", ",", "port", "=", "db_port", ",", "db", "=", "0", ")", "# is there a compressed key stored?)", "k", "=", "r", ".", "keys", "(", "'comp_'", "+", "fname_single", ")", "# if so, then it means that we have stored it as a compressed object", "# if have more than 1 element, take the last (which will be the latest to be added)", "if", "(", "len", "(", "k", ")", ">=", "1", ")", ":", "k", "=", "k", "[", "-", "1", "]", ".", "decode", "(", "'utf-8'", ")", "msg", "=", "r", ".", "get", "(", "k", ")", "msg", "=", "io", ".", "BytesIO", "(", "msg", ")", "msg", "=", "pd", ".", "read_pickle", "(", "msg", ",", "compression", "=", "\"gzip\"", ")", "else", ":", "msg", "=", "r", ".", "get", "(", "fname_single", ")", "msg", "=", "pd", ".", "read_pickle", "(", "msg", ".", "read", "(", ")", ")", "except", "Exception", "as", "e", ":", "logger", ".", "info", "(", "\"Cache not existent for \"", "+", "fname_single", "+", "\" in Redis: \"", "+", "str", "(", "e", ")", ")", "if", "msg", "is", "None", ":", "data_frame", "=", "None", "else", ":", "logger", ".", "info", "(", "'Load Redis cache: '", "+", "fname_single", ")", "data_frame", "=", "msg", "# pd.read_msgpack(msg)", "elif", "(", "engine", "==", "'arctic'", ")", ":", "socketTimeoutMS", "=", "2", "*", "1000", "import", "pymongo", "from", "arctic", "import", "Arctic", "fname_single", "=", "os", ".", "path", ".", "basename", "(", "fname_single", ")", ".", "replace", "(", "'.'", ",", "'_'", ")", "logger", ".", "info", "(", "'Load Arctic/MongoDB library: '", "+", "fname_single", ")", "if", "username", "is", "not", "None", "and", "password", "is", "not", "None", ":", "c", "=", "pymongo", ".", "MongoClient", "(", "host", "=", "\"mongodb://\"", "+", "username", "+", "\":\"", "+", "password", "+", "\"@\"", "+", "str", "(", "db_server", ")", "+", "\":\"", "+", "str", "(", "db_port", ")", ",", "connect", "=", "False", ")", "# , username=username, password=password)", "else", ":", "c", "=", "pymongo", ".", "MongoClient", "(", "host", "=", "\"mongodb://\"", "+", "str", "(", "db_server", ")", "+", "\":\"", "+", "str", "(", "db_port", ")", ",", "connect", "=", "False", ")", "store", "=", "Arctic", "(", "c", ",", "socketTimeoutMS", "=", "socketTimeoutMS", ",", "serverSelectionTimeoutMS", "=", "socketTimeoutMS", ")", "# Access the library", "try", ":", "library", "=", "store", "[", "fname_single", "]", "if", "start_date", "is", "None", "and", "finish_date", "is", "None", ":", "item", "=", "library", ".", "read", "(", "fname_single", ")", "else", ":", "from", "arctic", ".", "date", "import", "DateRange", "item", "=", "library", ".", "read", "(", "fname_single", ",", "date_range", "=", "DateRange", "(", "start_date", ".", "replace", "(", "tzinfo", "=", "None", ")", ",", "finish_date", ".", "replace", "(", "tzinfo", "=", "None", ")", ")", ")", "c", ".", "close", "(", ")", "logger", ".", "info", "(", "'Read '", "+", "fname_single", ")", "data_frame", "=", "item", ".", "data", "except", "Exception", "as", "e", ":", "logger", ".", "warning", "(", "'Library may not exist or another error: '", "+", "fname_single", "+", "' & message is '", "+", "str", "(", "e", ")", ")", "data_frame", "=", "None", "elif", "self", ".", "path_exists", "(", "self", ".", "get_h5_filename", "(", "fname_single", ")", ")", ":", "store", "=", "pd", ".", "HDFStore", "(", "self", ".", "get_h5_filename", "(", "fname_single", ")", ")", "data_frame", "=", "store", ".", "select", "(", "\"data\"", ")", "if", "(", "'intraday'", "in", "fname_single", ")", ":", "data_frame", "=", "data_frame", ".", "astype", "(", "'float32'", ")", "store", ".", "close", "(", ")", "elif", "self", ".", "path_exists", "(", "fname_single", ")", "and", "'.csv'", "in", "fname_single", ":", "data_frame", "=", "pd", ".", "read_csv", "(", "fname_single", ",", "index_col", "=", "0", ")", "data_frame", ".", "index", "=", "pd", ".", "to_datetime", "(", "data_frame", ".", "index", ")", "elif", "self", ".", "path_exists", "(", "fname_single", ")", ":", "data_frame", "=", "self", ".", "read_parquet", "(", "fname_single", ")", "# data_frame = pd.read_parquet(fname_single)", "data_frame_list", ".", "append", "(", "data_frame", ")", "if", "len", "(", "data_frame_list", ")", "==", "0", ":", "return", "None", "if", "len", "(", "data_frame_list", ")", "==", "1", ":", "return", "data_frame_list", "[", "0", "]", "return", "data_frame_list" ]
https://github.com/cuemacro/findatapy/blob/8ce72b17cc4dd3e3f53f0ab8adf58b6eeae29c10/findatapy/market/ioengine.py#L563-L720
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/core/compute_management_client.py
python
ComputeManagementClient.softreset_instance_pool
(self, instance_pool_id, **kwargs)
Performs the softreset (ACPI shutdown and power on) action on the specified instance pool, which performs the action on all the instances in the pool. Softreset gracefully reboots the instances by sending a shutdown command to the operating systems. After waiting 15 minutes for the OS to shut down, the instances are powered off and then powered back on. :param str instance_pool_id: (required) The `OCID`__ of the instance pool. __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm :param str opc_retry_token: (optional) A token that uniquely identifies a request so it can be retried in case of a timeout or server error without risk of executing that same action again. Retry tokens expire after 24 hours, but can be invalidated before then due to conflicting operations (for example, if a resource has been deleted and purged from the system, then a retry of the original creation request may be rejected). :param str if_match: (optional) For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.core.models.InstancePool` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/core/softreset_instance_pool.py.html>`__ to see an example of how to use softreset_instance_pool API.
Performs the softreset (ACPI shutdown and power on) action on the specified instance pool, which performs the action on all the instances in the pool.
[ "Performs", "the", "softreset", "(", "ACPI", "shutdown", "and", "power", "on", ")", "action", "on", "the", "specified", "instance", "pool", "which", "performs", "the", "action", "on", "all", "the", "instances", "in", "the", "pool", "." ]
def softreset_instance_pool(self, instance_pool_id, **kwargs): """ Performs the softreset (ACPI shutdown and power on) action on the specified instance pool, which performs the action on all the instances in the pool. Softreset gracefully reboots the instances by sending a shutdown command to the operating systems. After waiting 15 minutes for the OS to shut down, the instances are powered off and then powered back on. :param str instance_pool_id: (required) The `OCID`__ of the instance pool. __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm :param str opc_retry_token: (optional) A token that uniquely identifies a request so it can be retried in case of a timeout or server error without risk of executing that same action again. Retry tokens expire after 24 hours, but can be invalidated before then due to conflicting operations (for example, if a resource has been deleted and purged from the system, then a retry of the original creation request may be rejected). :param str if_match: (optional) For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.core.models.InstancePool` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/core/softreset_instance_pool.py.html>`__ to see an example of how to use softreset_instance_pool API. """ resource_path = "/instancePools/{instancePoolId}/actions/softreset" method = "POST" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "opc_retry_token", "if_match" ] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "softreset_instance_pool got unknown kwargs: {!r}".format(extra_kwargs)) path_params = { "instancePoolId": instance_pool_id } path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing} for (k, v) in six.iteritems(path_params): if v is None or (isinstance(v, six.string_types) and len(v.strip()) == 0): raise ValueError('Parameter {} cannot be None, whitespace or empty string'.format(k)) header_params = { "accept": "application/json", "content-type": "application/json", "opc-retry-token": kwargs.get("opc_retry_token", missing), "if-match": kwargs.get("if_match", missing) } header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None} retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_retry_token_if_needed(header_params) self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, response_type="InstancePool") else: return self.base_client.call_api( resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, response_type="InstancePool")
[ "def", "softreset_instance_pool", "(", "self", ",", "instance_pool_id", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/instancePools/{instancePoolId}/actions/softreset\"", "method", "=", "\"POST\"", "# Don't accept unknown kwargs", "expected_kwargs", "=", "[", "\"retry_strategy\"", ",", "\"opc_retry_token\"", ",", "\"if_match\"", "]", "extra_kwargs", "=", "[", "_key", "for", "_key", "in", "six", ".", "iterkeys", "(", "kwargs", ")", "if", "_key", "not", "in", "expected_kwargs", "]", "if", "extra_kwargs", ":", "raise", "ValueError", "(", "\"softreset_instance_pool got unknown kwargs: {!r}\"", ".", "format", "(", "extra_kwargs", ")", ")", "path_params", "=", "{", "\"instancePoolId\"", ":", "instance_pool_id", "}", "path_params", "=", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "six", ".", "iteritems", "(", "path_params", ")", "if", "v", "is", "not", "missing", "}", "for", "(", "k", ",", "v", ")", "in", "six", ".", "iteritems", "(", "path_params", ")", ":", "if", "v", "is", "None", "or", "(", "isinstance", "(", "v", ",", "six", ".", "string_types", ")", "and", "len", "(", "v", ".", "strip", "(", ")", ")", "==", "0", ")", ":", "raise", "ValueError", "(", "'Parameter {} cannot be None, whitespace or empty string'", ".", "format", "(", "k", ")", ")", "header_params", "=", "{", "\"accept\"", ":", "\"application/json\"", ",", "\"content-type\"", ":", "\"application/json\"", ",", "\"opc-retry-token\"", ":", "kwargs", ".", "get", "(", "\"opc_retry_token\"", ",", "missing", ")", ",", "\"if-match\"", ":", "kwargs", ".", "get", "(", "\"if_match\"", ",", "missing", ")", "}", "header_params", "=", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "six", ".", "iteritems", "(", "header_params", ")", "if", "v", "is", "not", "missing", "and", "v", "is", "not", "None", "}", "retry_strategy", "=", "self", ".", "base_client", ".", "get_preferred_retry_strategy", "(", "operation_retry_strategy", "=", "kwargs", ".", "get", "(", "'retry_strategy'", ")", ",", "client_retry_strategy", "=", "self", ".", "retry_strategy", ")", "if", "retry_strategy", ":", "if", "not", "isinstance", "(", "retry_strategy", ",", "retry", ".", "NoneRetryStrategy", ")", ":", "self", ".", "base_client", ".", "add_opc_retry_token_if_needed", "(", "header_params", ")", "self", ".", "base_client", ".", "add_opc_client_retries_header", "(", "header_params", ")", "retry_strategy", ".", "add_circuit_breaker_callback", "(", "self", ".", "circuit_breaker_callback", ")", "return", "retry_strategy", ".", "make_retrying_call", "(", "self", ".", "base_client", ".", "call_api", ",", "resource_path", "=", "resource_path", ",", "method", "=", "method", ",", "path_params", "=", "path_params", ",", "header_params", "=", "header_params", ",", "response_type", "=", "\"InstancePool\"", ")", "else", ":", "return", "self", ".", "base_client", ".", "call_api", "(", "resource_path", "=", "resource_path", ",", "method", "=", "method", ",", "path_params", "=", "path_params", ",", "header_params", "=", "header_params", ",", "response_type", "=", "\"InstancePool\"", ")" ]
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/core/compute_management_client.py#L2396-L2491
AstroPrint/AstroBox
e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75
src/astroprint/plugin/services/account.py
python
AccountService._onFleetStateChange
(self,event,value)
[]
def _onFleetStateChange(self,event,value): data = { 'orgId' : value['orgId'], 'groupId' : value['groupId'] } self.publishEvent('fleet_state_change',data)
[ "def", "_onFleetStateChange", "(", "self", ",", "event", ",", "value", ")", ":", "data", "=", "{", "'orgId'", ":", "value", "[", "'orgId'", "]", ",", "'groupId'", ":", "value", "[", "'groupId'", "]", "}", "self", ".", "publishEvent", "(", "'fleet_state_change'", ",", "data", ")" ]
https://github.com/AstroPrint/AstroBox/blob/e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75/src/astroprint/plugin/services/account.py#L240-L245
Project-MONAI/MONAI
83f8b06372a3803ebe9281300cb794a1f3395018
versioneer.py
python
write_to_version_file
(filename, versions)
Write the given version number to the given _version.py file.
Write the given version number to the given _version.py file.
[ "Write", "the", "given", "version", "number", "to", "the", "given", "_version", ".", "py", "file", "." ]
def write_to_version_file(filename, versions): """Write the given version number to the given _version.py file.""" os.unlink(filename) contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) with open(filename, "w") as f: f.write(SHORT_VERSION_PY % contents) print("set %s to '%s'" % (filename, versions["version"]))
[ "def", "write_to_version_file", "(", "filename", ",", "versions", ")", ":", "os", ".", "unlink", "(", "filename", ")", "contents", "=", "json", ".", "dumps", "(", "versions", ",", "sort_keys", "=", "True", ",", "indent", "=", "1", ",", "separators", "=", "(", "\",\"", ",", "\": \"", ")", ")", "with", "open", "(", "filename", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "SHORT_VERSION_PY", "%", "contents", ")", "print", "(", "\"set %s to '%s'\"", "%", "(", "filename", ",", "versions", "[", "\"version\"", "]", ")", ")" ]
https://github.com/Project-MONAI/MONAI/blob/83f8b06372a3803ebe9281300cb794a1f3395018/versioneer.py#L1226-L1233
obspy/obspy
0ee5a0d2db293c8d5d4c3b1f148a6c5a85fea55f
obspy/signal/tf_misfit.py
python
tem
(st1, st2, dt=0.01, fmin=1., fmax=10., nf=100, w0=6, norm='global', st2_isref=True)
Time-dependent Envelope Misfit .. seealso:: [Kristekova2009]_, Table 1. and 2. :param st1: signal 1 of two signals to compare, type numpy.ndarray with shape (number of components, number of time samples) or (number of timesamples, ) for single component data :param st2: signal 2 of two signals to compare, type and shape as st1 :param dt: time step between two samples in st1 and st2 :param fmin: minimal frequency to be analyzed :param fmax: maximal frequency to be analyzed :param nf: number of frequencies (will be chosen with logarithmic spacing) :param w0: parameter for the wavelet, tradeoff between time and frequency resolution :param norm: 'global' or 'local' normalization of the misfit :type st2_isref: bool :param st2_isref: True if st2 is a reference signal, False if none is a reference :return: Time-dependent Envelope Misfit, type numpy.ndarray with shape (len(st1),) for single component data and (number of components, len(st1)) for multicomponent data
Time-dependent Envelope Misfit
[ "Time", "-", "dependent", "Envelope", "Misfit" ]
def tem(st1, st2, dt=0.01, fmin=1., fmax=10., nf=100, w0=6, norm='global', st2_isref=True): """ Time-dependent Envelope Misfit .. seealso:: [Kristekova2009]_, Table 1. and 2. :param st1: signal 1 of two signals to compare, type numpy.ndarray with shape (number of components, number of time samples) or (number of timesamples, ) for single component data :param st2: signal 2 of two signals to compare, type and shape as st1 :param dt: time step between two samples in st1 and st2 :param fmin: minimal frequency to be analyzed :param fmax: maximal frequency to be analyzed :param nf: number of frequencies (will be chosen with logarithmic spacing) :param w0: parameter for the wavelet, tradeoff between time and frequency resolution :param norm: 'global' or 'local' normalization of the misfit :type st2_isref: bool :param st2_isref: True if st2 is a reference signal, False if none is a reference :return: Time-dependent Envelope Misfit, type numpy.ndarray with shape (len(st1),) for single component data and (number of components, len(st1)) for multicomponent data """ if len(st1.shape) == 1: w_1 = np.zeros((1, nf, st1.shape[0]), dtype=np.complex) w_2 = np.zeros((1, nf, st1.shape[0]), dtype=np.complex) w_1[0] = cwt(st1, dt, w0, fmin, fmax, nf) w_2[0] = cwt(st2, dt, w0, fmin, fmax, nf) else: w_1 = np.zeros((st1.shape[0], nf, st1.shape[1]), dtype=np.complex) w_2 = np.zeros((st2.shape[0], nf, st2.shape[1]), dtype=np.complex) for i in np.arange(st1.shape[0]): w_1[i] = cwt(st1[i], dt, w0, fmin, fmax, nf) w_2[i] = cwt(st2[i], dt, w0, fmin, fmax, nf) if st2_isref: _ar = np.abs(w_2) else: if np.abs(w_1).max() > np.abs(w_2).max(): _ar = np.abs(w_1) else: _ar = np.abs(w_2) _tem = np.sum((np.abs(w_1) - np.abs(w_2)), axis=1) if norm == 'global': if len(st1.shape) == 1: return _tem[0] / np.max(np.sum(_ar, axis=1)) else: return _tem / np.max(np.sum(_ar, axis=1)) elif norm == 'local': if len(st1.shape) == 1: return _tem[0] / np.sum(_ar, axis=1)[0] else: return _tem / np.sum(_ar, axis=1) else: raise ValueError('norm "' + norm + '" not defined!')
[ "def", "tem", "(", "st1", ",", "st2", ",", "dt", "=", "0.01", ",", "fmin", "=", "1.", ",", "fmax", "=", "10.", ",", "nf", "=", "100", ",", "w0", "=", "6", ",", "norm", "=", "'global'", ",", "st2_isref", "=", "True", ")", ":", "if", "len", "(", "st1", ".", "shape", ")", "==", "1", ":", "w_1", "=", "np", ".", "zeros", "(", "(", "1", ",", "nf", ",", "st1", ".", "shape", "[", "0", "]", ")", ",", "dtype", "=", "np", ".", "complex", ")", "w_2", "=", "np", ".", "zeros", "(", "(", "1", ",", "nf", ",", "st1", ".", "shape", "[", "0", "]", ")", ",", "dtype", "=", "np", ".", "complex", ")", "w_1", "[", "0", "]", "=", "cwt", "(", "st1", ",", "dt", ",", "w0", ",", "fmin", ",", "fmax", ",", "nf", ")", "w_2", "[", "0", "]", "=", "cwt", "(", "st2", ",", "dt", ",", "w0", ",", "fmin", ",", "fmax", ",", "nf", ")", "else", ":", "w_1", "=", "np", ".", "zeros", "(", "(", "st1", ".", "shape", "[", "0", "]", ",", "nf", ",", "st1", ".", "shape", "[", "1", "]", ")", ",", "dtype", "=", "np", ".", "complex", ")", "w_2", "=", "np", ".", "zeros", "(", "(", "st2", ".", "shape", "[", "0", "]", ",", "nf", ",", "st2", ".", "shape", "[", "1", "]", ")", ",", "dtype", "=", "np", ".", "complex", ")", "for", "i", "in", "np", ".", "arange", "(", "st1", ".", "shape", "[", "0", "]", ")", ":", "w_1", "[", "i", "]", "=", "cwt", "(", "st1", "[", "i", "]", ",", "dt", ",", "w0", ",", "fmin", ",", "fmax", ",", "nf", ")", "w_2", "[", "i", "]", "=", "cwt", "(", "st2", "[", "i", "]", ",", "dt", ",", "w0", ",", "fmin", ",", "fmax", ",", "nf", ")", "if", "st2_isref", ":", "_ar", "=", "np", ".", "abs", "(", "w_2", ")", "else", ":", "if", "np", ".", "abs", "(", "w_1", ")", ".", "max", "(", ")", ">", "np", ".", "abs", "(", "w_2", ")", ".", "max", "(", ")", ":", "_ar", "=", "np", ".", "abs", "(", "w_1", ")", "else", ":", "_ar", "=", "np", ".", "abs", "(", "w_2", ")", "_tem", "=", "np", ".", "sum", "(", "(", "np", ".", "abs", "(", "w_1", ")", "-", "np", ".", "abs", "(", "w_2", ")", ")", ",", "axis", "=", "1", ")", "if", "norm", "==", "'global'", ":", "if", "len", "(", "st1", ".", "shape", ")", "==", "1", ":", "return", "_tem", "[", "0", "]", "/", "np", ".", "max", "(", "np", ".", "sum", "(", "_ar", ",", "axis", "=", "1", ")", ")", "else", ":", "return", "_tem", "/", "np", ".", "max", "(", "np", ".", "sum", "(", "_ar", ",", "axis", "=", "1", ")", ")", "elif", "norm", "==", "'local'", ":", "if", "len", "(", "st1", ".", "shape", ")", "==", "1", ":", "return", "_tem", "[", "0", "]", "/", "np", ".", "sum", "(", "_ar", ",", "axis", "=", "1", ")", "[", "0", "]", "else", ":", "return", "_tem", "/", "np", ".", "sum", "(", "_ar", ",", "axis", "=", "1", ")", "else", ":", "raise", "ValueError", "(", "'norm \"'", "+", "norm", "+", "'\" not defined!'", ")" ]
https://github.com/obspy/obspy/blob/0ee5a0d2db293c8d5d4c3b1f148a6c5a85fea55f/obspy/signal/tf_misfit.py#L218-L279
meduza-corp/interstellar
40a801ccd7856491726f5a126621d9318cabe2e1
gsutil/third_party/boto/boto/ec2/instance.py
python
Instance.create_image
(self, name, description=None, no_reboot=False, dry_run=False)
return self.connection.create_image( self.id, name, description, no_reboot, dry_run=dry_run )
Will create an AMI from the instance in the running or stopped state. :type name: string :param name: The name of the new image :type description: string :param description: An optional human-readable string describing the contents and purpose of the AMI. :type no_reboot: bool :param no_reboot: An optional flag indicating that the bundling process should not attempt to shutdown the instance before bundling. If this flag is True, the responsibility of maintaining file system integrity is left to the owner of the instance. :rtype: string :return: The new image id
Will create an AMI from the instance in the running or stopped state.
[ "Will", "create", "an", "AMI", "from", "the", "instance", "in", "the", "running", "or", "stopped", "state", "." ]
def create_image(self, name, description=None, no_reboot=False, dry_run=False): """ Will create an AMI from the instance in the running or stopped state. :type name: string :param name: The name of the new image :type description: string :param description: An optional human-readable string describing the contents and purpose of the AMI. :type no_reboot: bool :param no_reboot: An optional flag indicating that the bundling process should not attempt to shutdown the instance before bundling. If this flag is True, the responsibility of maintaining file system integrity is left to the owner of the instance. :rtype: string :return: The new image id """ return self.connection.create_image( self.id, name, description, no_reboot, dry_run=dry_run )
[ "def", "create_image", "(", "self", ",", "name", ",", "description", "=", "None", ",", "no_reboot", "=", "False", ",", "dry_run", "=", "False", ")", ":", "return", "self", ".", "connection", ".", "create_image", "(", "self", ".", "id", ",", "name", ",", "description", ",", "no_reboot", ",", "dry_run", "=", "dry_run", ")" ]
https://github.com/meduza-corp/interstellar/blob/40a801ccd7856491726f5a126621d9318cabe2e1/gsutil/third_party/boto/boto/ec2/instance.py#L577-L606
researchmm/tasn
5dba8ccc096cedc63913730eeea14a9647911129
tasn-mxnet/3rdparty/tvm/python/tvm/contrib/util.py
python
TempDirectory.relpath
(self, name)
return os.path.join(self.temp_dir, name)
Relative path in temp dir Parameters ---------- name : str The name of the file. Returns ------- path : str The concatenated path.
Relative path in temp dir
[ "Relative", "path", "in", "temp", "dir" ]
def relpath(self, name): """Relative path in temp dir Parameters ---------- name : str The name of the file. Returns ------- path : str The concatenated path. """ return os.path.join(self.temp_dir, name)
[ "def", "relpath", "(", "self", ",", "name", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "temp_dir", ",", "name", ")" ]
https://github.com/researchmm/tasn/blob/5dba8ccc096cedc63913730eeea14a9647911129/tasn-mxnet/3rdparty/tvm/python/tvm/contrib/util.py#L30-L43
BaselAbujamous/clust
3d3fbd27bf1536798cb347b5f67410c002608630
clust/scripts/preprocess_data.py
python
autoNormalise
(X)
Automatically normalise dataset X and filter it if needed :param X: Dataset matrix (numpy array) :return: array of normalisation codes
Automatically normalise dataset X and filter it if needed
[ "Automatically", "normalise", "dataset", "X", "and", "filter", "it", "if", "needed" ]
def autoNormalise(X): """ Automatically normalise dataset X and filter it if needed :param X: Dataset matrix (numpy array) :return: array of normalisation codes """ Xloc = np.array(X) twosided = np.sum(Xloc < 0) > 0.2 * np.sum(Xloc > 0) # negative values are at least 20% of positive values arelogs = arelogs_function(Xloc) #arelogs = np.sum(abs(Xloc) < 30) > 0.98 * ds.numel(Xloc) # More than 98% of values are below 30.0 if twosided: return np.array([4]) #return np.array([101, 4]) else: Xloc[isnan(Xloc)] = 0.0 Xloc[Xloc < 0] = 0.0 if arelogs: Xf = normaliseSampleFeatureMat(Xloc, [13])[0] if isnormal_68_95_99p7_rule(Xf)[1] < isnormal_68_95_99p7_rule(Xloc)[1]: return np.array([13, 4]) else: return np.array([4]) else: Xl = normaliseSampleFeatureMat(Xloc, [3])[0] # index 1 (Xloc, i.e. original X is index 0) Xlp = normaliseSampleFeatureMat(Xloc, [31])[0] # index 2 Xf = normaliseSampleFeatureMat(Xloc, [13])[0] # index 3 Xlf = normaliseSampleFeatureMat(Xl, [13])[0] # index 4 Xlpf = normaliseSampleFeatureMat(Xlp, [13])[0] # index 5 isnormal_stats = [isnormal_68_95_99p7_rule(Xloc)[1], isnormal_68_95_99p7_rule(Xl)[1], isnormal_68_95_99p7_rule(Xlp)[1], isnormal_68_95_99p7_rule(Xf)[1], isnormal_68_95_99p7_rule(Xlf)[1], isnormal_68_95_99p7_rule(Xlpf)[1]] most_normal_index = np.argmin(isnormal_stats) if most_normal_index == 0: return np.array([4]) elif most_normal_index == 1: return np.array([3, 4]) elif most_normal_index == 2: return np.array([31, 4]) elif most_normal_index == 3: return np.array([13, 4]) elif most_normal_index == 4: return np.array([3, 13, 4]) elif most_normal_index == 5: return np.array([31, 13, 4]) else: raise ValueError('You should never reach this error. Please contact {0}'.format(glob.email))
[ "def", "autoNormalise", "(", "X", ")", ":", "Xloc", "=", "np", ".", "array", "(", "X", ")", "twosided", "=", "np", ".", "sum", "(", "Xloc", "<", "0", ")", ">", "0.2", "*", "np", ".", "sum", "(", "Xloc", ">", "0", ")", "# negative values are at least 20% of positive values", "arelogs", "=", "arelogs_function", "(", "Xloc", ")", "#arelogs = np.sum(abs(Xloc) < 30) > 0.98 * ds.numel(Xloc) # More than 98% of values are below 30.0", "if", "twosided", ":", "return", "np", ".", "array", "(", "[", "4", "]", ")", "#return np.array([101, 4])", "else", ":", "Xloc", "[", "isnan", "(", "Xloc", ")", "]", "=", "0.0", "Xloc", "[", "Xloc", "<", "0", "]", "=", "0.0", "if", "arelogs", ":", "Xf", "=", "normaliseSampleFeatureMat", "(", "Xloc", ",", "[", "13", "]", ")", "[", "0", "]", "if", "isnormal_68_95_99p7_rule", "(", "Xf", ")", "[", "1", "]", "<", "isnormal_68_95_99p7_rule", "(", "Xloc", ")", "[", "1", "]", ":", "return", "np", ".", "array", "(", "[", "13", ",", "4", "]", ")", "else", ":", "return", "np", ".", "array", "(", "[", "4", "]", ")", "else", ":", "Xl", "=", "normaliseSampleFeatureMat", "(", "Xloc", ",", "[", "3", "]", ")", "[", "0", "]", "# index 1 (Xloc, i.e. original X is index 0)", "Xlp", "=", "normaliseSampleFeatureMat", "(", "Xloc", ",", "[", "31", "]", ")", "[", "0", "]", "# index 2", "Xf", "=", "normaliseSampleFeatureMat", "(", "Xloc", ",", "[", "13", "]", ")", "[", "0", "]", "# index 3", "Xlf", "=", "normaliseSampleFeatureMat", "(", "Xl", ",", "[", "13", "]", ")", "[", "0", "]", "# index 4", "Xlpf", "=", "normaliseSampleFeatureMat", "(", "Xlp", ",", "[", "13", "]", ")", "[", "0", "]", "# index 5", "isnormal_stats", "=", "[", "isnormal_68_95_99p7_rule", "(", "Xloc", ")", "[", "1", "]", ",", "isnormal_68_95_99p7_rule", "(", "Xl", ")", "[", "1", "]", ",", "isnormal_68_95_99p7_rule", "(", "Xlp", ")", "[", "1", "]", ",", "isnormal_68_95_99p7_rule", "(", "Xf", ")", "[", "1", "]", ",", "isnormal_68_95_99p7_rule", "(", "Xlf", ")", "[", "1", "]", ",", "isnormal_68_95_99p7_rule", "(", "Xlpf", ")", "[", "1", "]", "]", "most_normal_index", "=", "np", ".", "argmin", "(", "isnormal_stats", ")", "if", "most_normal_index", "==", "0", ":", "return", "np", ".", "array", "(", "[", "4", "]", ")", "elif", "most_normal_index", "==", "1", ":", "return", "np", ".", "array", "(", "[", "3", ",", "4", "]", ")", "elif", "most_normal_index", "==", "2", ":", "return", "np", ".", "array", "(", "[", "31", ",", "4", "]", ")", "elif", "most_normal_index", "==", "3", ":", "return", "np", ".", "array", "(", "[", "13", ",", "4", "]", ")", "elif", "most_normal_index", "==", "4", ":", "return", "np", ".", "array", "(", "[", "3", ",", "13", ",", "4", "]", ")", "elif", "most_normal_index", "==", "5", ":", "return", "np", ".", "array", "(", "[", "31", ",", "13", ",", "4", "]", ")", "else", ":", "raise", "ValueError", "(", "'You should never reach this error. Please contact {0}'", ".", "format", "(", "glob", ".", "email", ")", ")" ]
https://github.com/BaselAbujamous/clust/blob/3d3fbd27bf1536798cb347b5f67410c002608630/clust/scripts/preprocess_data.py#L187-L235
qiime2/qiime2
3906f67c70a1321e99e7fc59e79550c2432a8cee
qiime2/metadata/metadata.py
python
Metadata.__eq__
(self, other)
return ( super().__eq__(other) and self._columns == other._columns and self._dataframe.equals(other._dataframe) )
Determine if this metadata is equal to another. ``Metadata`` objects are equal if their IDs, columns (including column names, types, and ordering), ID headers, source artifacts, and metadata values are equal. Parameters ---------- other : Metadata Metadata to test for equality. Returns ------- bool Indicates whether this ``Metadata`` object is equal to `other`. See Also -------- __ne__
Determine if this metadata is equal to another.
[ "Determine", "if", "this", "metadata", "is", "equal", "to", "another", "." ]
def __eq__(self, other): """Determine if this metadata is equal to another. ``Metadata`` objects are equal if their IDs, columns (including column names, types, and ordering), ID headers, source artifacts, and metadata values are equal. Parameters ---------- other : Metadata Metadata to test for equality. Returns ------- bool Indicates whether this ``Metadata`` object is equal to `other`. See Also -------- __ne__ """ return ( super().__eq__(other) and self._columns == other._columns and self._dataframe.equals(other._dataframe) )
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "return", "(", "super", "(", ")", ".", "__eq__", "(", "other", ")", "and", "self", ".", "_columns", "==", "other", ".", "_columns", "and", "self", ".", "_dataframe", ".", "equals", "(", "other", ".", "_dataframe", ")", ")" ]
https://github.com/qiime2/qiime2/blob/3906f67c70a1321e99e7fc59e79550c2432a8cee/qiime2/metadata/metadata.py#L472-L498
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/pydoc.py
python
doc
(thing, title='Python Library Documentation: %s', forceload=0, output=None)
Display text documentation, given an object or a path to an object.
Display text documentation, given an object or a path to an object.
[ "Display", "text", "documentation", "given", "an", "object", "or", "a", "path", "to", "an", "object", "." ]
def doc(thing, title='Python Library Documentation: %s', forceload=0, output=None): """Display text documentation, given an object or a path to an object.""" try: if output is None: pager(render_doc(thing, title, forceload)) else: output.write(render_doc(thing, title, forceload, plaintext)) except (ImportError, ErrorDuringImport) as value: print(value)
[ "def", "doc", "(", "thing", ",", "title", "=", "'Python Library Documentation: %s'", ",", "forceload", "=", "0", ",", "output", "=", "None", ")", ":", "try", ":", "if", "output", "is", "None", ":", "pager", "(", "render_doc", "(", "thing", ",", "title", ",", "forceload", ")", ")", "else", ":", "output", ".", "write", "(", "render_doc", "(", "thing", ",", "title", ",", "forceload", ",", "plaintext", ")", ")", "except", "(", "ImportError", ",", "ErrorDuringImport", ")", "as", "value", ":", "print", "(", "value", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/pydoc.py#L1669-L1678
yzhao062/combo
229d578de498b47ae03cf2580472aceebf8c2766
combo/models/sklearn_base.py
python
_partition_estimators
(n_estimators, n_jobs)
return n_jobs, n_estimators_per_job.tolist(), [0] + starts.tolist()
Private function used to partition estimators between jobs. See sklearn/ensemble/base.py for more information.
Private function used to partition estimators between jobs. See sklearn/ensemble/base.py for more information.
[ "Private", "function", "used", "to", "partition", "estimators", "between", "jobs", ".", "See", "sklearn", "/", "ensemble", "/", "base", ".", "py", "for", "more", "information", "." ]
def _partition_estimators(n_estimators, n_jobs): """Private function used to partition estimators between jobs. See sklearn/ensemble/base.py for more information. """ # Compute the number of jobs n_jobs = min(_get_n_jobs(n_jobs), n_estimators) # Partition estimators between jobs n_estimators_per_job = (n_estimators // n_jobs) * np.ones(n_jobs, dtype=np.int) n_estimators_per_job[:n_estimators % n_jobs] += 1 starts = np.cumsum(n_estimators_per_job) return n_jobs, n_estimators_per_job.tolist(), [0] + starts.tolist()
[ "def", "_partition_estimators", "(", "n_estimators", ",", "n_jobs", ")", ":", "# Compute the number of jobs", "n_jobs", "=", "min", "(", "_get_n_jobs", "(", "n_jobs", ")", ",", "n_estimators", ")", "# Partition estimators between jobs", "n_estimators_per_job", "=", "(", "n_estimators", "//", "n_jobs", ")", "*", "np", ".", "ones", "(", "n_jobs", ",", "dtype", "=", "np", ".", "int", ")", "n_estimators_per_job", "[", ":", "n_estimators", "%", "n_jobs", "]", "+=", "1", "starts", "=", "np", ".", "cumsum", "(", "n_estimators_per_job", ")", "return", "n_jobs", ",", "n_estimators_per_job", ".", "tolist", "(", ")", ",", "[", "0", "]", "+", "starts", ".", "tolist", "(", ")" ]
https://github.com/yzhao062/combo/blob/229d578de498b47ae03cf2580472aceebf8c2766/combo/models/sklearn_base.py#L39-L52
elfi-dev/elfi
07ac0ed5e81d5d5fb42de63db3cf9ccc9135b88c
elfi/methods/results.py
python
Sample.__init__
(self, method_name, outputs, parameter_names, discrepancy_name=None, weights=None, **kwargs)
Initialize result. Parameters ---------- method_name : string Name of inference method. outputs : dict Dictionary with outputs from the nodes, e.g. samples. parameter_names : list Names of the parameter nodes discrepancy_name : string, optional Name of the discrepancy in outputs. weights : array_like **kwargs Other meta information for the result
Initialize result.
[ "Initialize", "result", "." ]
def __init__(self, method_name, outputs, parameter_names, discrepancy_name=None, weights=None, **kwargs): """Initialize result. Parameters ---------- method_name : string Name of inference method. outputs : dict Dictionary with outputs from the nodes, e.g. samples. parameter_names : list Names of the parameter nodes discrepancy_name : string, optional Name of the discrepancy in outputs. weights : array_like **kwargs Other meta information for the result """ super(Sample, self).__init__( method_name=method_name, outputs=outputs, parameter_names=parameter_names, **kwargs) self.samples = OrderedDict() for n in self.parameter_names: self.samples[n] = self.outputs[n] self.discrepancy_name = discrepancy_name self.weights = weights
[ "def", "__init__", "(", "self", ",", "method_name", ",", "outputs", ",", "parameter_names", ",", "discrepancy_name", "=", "None", ",", "weights", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Sample", ",", "self", ")", ".", "__init__", "(", "method_name", "=", "method_name", ",", "outputs", "=", "outputs", ",", "parameter_names", "=", "parameter_names", ",", "*", "*", "kwargs", ")", "self", ".", "samples", "=", "OrderedDict", "(", ")", "for", "n", "in", "self", ".", "parameter_names", ":", "self", ".", "samples", "[", "n", "]", "=", "self", ".", "outputs", "[", "n", "]", "self", ".", "discrepancy_name", "=", "discrepancy_name", "self", ".", "weights", "=", "weights" ]
https://github.com/elfi-dev/elfi/blob/07ac0ed5e81d5d5fb42de63db3cf9ccc9135b88c/elfi/methods/results.py#L73-L105
skelsec/pypykatz
dd129ff36e00593d1340776b517f7e749ad8d314
pypykatz/commons/readers/local/common/kernel32.py
python
MemoryBasicInformation.is_executable
(self)
return self.has_content() and bool(self.Protect & self.EXECUTABLE)
@rtype: bool @return: C{True} if all pages in this region are executable. @note: Executable pages are always readable.
[]
def is_executable(self): """ @rtype: bool @return: C{True} if all pages in this region are executable. @note: Executable pages are always readable. """ return self.has_content() and bool(self.Protect & self.EXECUTABLE)
[ "def", "is_executable", "(", "self", ")", ":", "return", "self", ".", "has_content", "(", ")", "and", "bool", "(", "self", ".", "Protect", "&", "self", ".", "EXECUTABLE", ")" ]
https://github.com/skelsec/pypykatz/blob/dd129ff36e00593d1340776b517f7e749ad8d314/pypykatz/commons/readers/local/common/kernel32.py#L283-L289
nlloyd/SubliminalCollaborator
5c619e17ddbe8acb9eea8996ec038169ddcd50a1
libs/twisted/python/filepath.py
python
IFilePath.isfile
()
@return: C{True} if the file at this file path is a regular file, C{False} otherwise.
[]
def isfile(): """ @return: C{True} if the file at this file path is a regular file, C{False} otherwise. """
[ "def", "isfile", "(", ")", ":" ]
https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/twisted/python/filepath.py#L180-L184
digidotcom/xbee-python
0757f4be0017530c205175fbee8f9f61be9614d1
digi/xbee/io.py
python
IOSample.has_analog_value
(self, io_line)
return io_line in self.__analog_values_map.keys()
Returns whether the given IOLine has an analog value or not. Returns: Boolean: `True` if the given IOLine has an analog value, `False` otherwise.
Returns whether the given IOLine has an analog value or not.
[ "Returns", "whether", "the", "given", "IOLine", "has", "an", "analog", "value", "or", "not", "." ]
def has_analog_value(self, io_line): """ Returns whether the given IOLine has an analog value or not. Returns: Boolean: `True` if the given IOLine has an analog value, `False` otherwise. """ return io_line in self.__analog_values_map.keys()
[ "def", "has_analog_value", "(", "self", ",", "io_line", ")", ":", "return", "io_line", "in", "self", ".", "__analog_values_map", ".", "keys", "(", ")" ]
https://github.com/digidotcom/xbee-python/blob/0757f4be0017530c205175fbee8f9f61be9614d1/digi/xbee/io.py#L541-L549
redis/redis-py
0affa0ed3f3cbcb6dec29b34a580f769f69ae9f7
redis/commands/search/commands.py
python
SearchCommands.suglen
(self, key)
return self.execute_command(SUGLEN_COMMAND, key)
Return the number of entries in the AutoCompleter index. For more information https://oss.redis.com/redisearch/master/Commands/#ftsuglen
Return the number of entries in the AutoCompleter index.
[ "Return", "the", "number", "of", "entries", "in", "the", "AutoCompleter", "index", "." ]
def suglen(self, key): """ Return the number of entries in the AutoCompleter index. For more information https://oss.redis.com/redisearch/master/Commands/#ftsuglen """ # noqa return self.execute_command(SUGLEN_COMMAND, key)
[ "def", "suglen", "(", "self", ",", "key", ")", ":", "# noqa", "return", "self", ".", "execute_command", "(", "SUGLEN_COMMAND", ",", "key", ")" ]
https://github.com/redis/redis-py/blob/0affa0ed3f3cbcb6dec29b34a580f769f69ae9f7/redis/commands/search/commands.py#L721-L727
meetbill/zabbix_manager
739e5b51facf19cc6bda2b50f29108f831cf833e
ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/Worksheet.py
python
Worksheet.row
(self, indx)
return self.__rows[indx]
[]
def row(self, indx): if indx not in self.__rows: if indx in self.__flushed_rows: raise Exception("Attempt to reuse row index %d of sheet %r after flushing" % (indx, self.__name)) self.__rows[indx] = self.Row(indx, self) if indx > self.last_used_row: self.last_used_row = indx if indx < self.first_used_row: self.first_used_row = indx return self.__rows[indx]
[ "def", "row", "(", "self", ",", "indx", ")", ":", "if", "indx", "not", "in", "self", ".", "__rows", ":", "if", "indx", "in", "self", ".", "__flushed_rows", ":", "raise", "Exception", "(", "\"Attempt to reuse row index %d of sheet %r after flushing\"", "%", "(", "indx", ",", "self", ".", "__name", ")", ")", "self", ".", "__rows", "[", "indx", "]", "=", "self", ".", "Row", "(", "indx", ",", "self", ")", "if", "indx", ">", "self", ".", "last_used_row", ":", "self", ".", "last_used_row", "=", "indx", "if", "indx", "<", "self", ".", "first_used_row", ":", "self", ".", "first_used_row", "=", "indx", "return", "self", ".", "__rows", "[", "indx", "]" ]
https://github.com/meetbill/zabbix_manager/blob/739e5b51facf19cc6bda2b50f29108f831cf833e/ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/Worksheet.py#L1132-L1141
IFGHou/wapiti
91242a8ad293a8ee54ab6e62732ff4b9d770772c
wapitiCore/attack/mod_sql.py
python
mod_sql.attackPOST
(self, form)
This method performs the SQL Injection attack with method POST
This method performs the SQL Injection attack with method POST
[ "This", "method", "performs", "the", "SQL", "Injection", "attack", "with", "method", "POST" ]
def attackPOST(self, form): """This method performs the SQL Injection attack with method POST""" payload = "\xbf'\"(" filename_payload = "'\"(" err = "" # copies get_params = form.get_params post_params = form.post_params file_params = form.file_params referer = form.referer for params_list in [get_params, post_params, file_params]: for i in xrange(len(params_list)): saved_value = params_list[i][1] if saved_value is None: saved_value = "" if params_list is file_params: params_list[i][1] = ["_SQL__", params_list[i][1][1]] else: params_list[i][1] = "__SQL__" param_name = self.HTTP.quote(params_list[i][0]) attack_pattern = HTTP.HTTPResource(form.path, method=form.method, get_params=get_params, post_params=post_params, file_params=file_params) if attack_pattern not in self.attackedPOST: self.attackedPOST.append(attack_pattern) if params_list is file_params: params_list[i][1][0] = filename_payload else: params_list[i][1] = payload evil_req = HTTP.HTTPResource(form.path, method=form.method, get_params=get_params, post_params=post_params, file_params=file_params, referer=referer) if self.verbose == 2: print(u"+ {0}".format(evil_req)) try: resp = self.HTTP.send(evil_req) data, code = resp.getPageCode() except requests.exceptions.Timeout, timeout: # No timeout report here... launch blind sql detection later code = "408" else: err = self.__findPatternInResponse(data) if err != "": self.logVuln(category=Vulnerability.SQL_INJECTION, level=Vulnerability.HIGH_LEVEL, request=evil_req, parameter=param_name, info=_("{0} via injection in the parameter {1}").format(err, param_name)) self.logR(Vulnerability.MSG_PARAM_INJECT, err, evil_req.url, param_name) self.logR(Vulnerability.MSG_EVIL_REQUEST) self.logC(evil_req.http_repr) print('') self.vulnerablePOST.append(attack_pattern) else: if code == "500": self.logAnom(category=Anomaly.ERROR_500, level=Anomaly.HIGH_LEVEL, request=evil_req, parameter=param_name, info=Anomaly.MSG_PARAM_500.format(param_name)) self.logO(Anomaly.MSG_500, evil_req.url) self.logO(Anomaly.MSG_EVIL_REQUEST) self.logC(evil_req.http_repr) print('') params_list[i][1] = saved_value
[ "def", "attackPOST", "(", "self", ",", "form", ")", ":", "payload", "=", "\"\\xbf'\\\"(\"", "filename_payload", "=", "\"'\\\"(\"", "err", "=", "\"\"", "# copies", "get_params", "=", "form", ".", "get_params", "post_params", "=", "form", ".", "post_params", "file_params", "=", "form", ".", "file_params", "referer", "=", "form", ".", "referer", "for", "params_list", "in", "[", "get_params", ",", "post_params", ",", "file_params", "]", ":", "for", "i", "in", "xrange", "(", "len", "(", "params_list", ")", ")", ":", "saved_value", "=", "params_list", "[", "i", "]", "[", "1", "]", "if", "saved_value", "is", "None", ":", "saved_value", "=", "\"\"", "if", "params_list", "is", "file_params", ":", "params_list", "[", "i", "]", "[", "1", "]", "=", "[", "\"_SQL__\"", ",", "params_list", "[", "i", "]", "[", "1", "]", "[", "1", "]", "]", "else", ":", "params_list", "[", "i", "]", "[", "1", "]", "=", "\"__SQL__\"", "param_name", "=", "self", ".", "HTTP", ".", "quote", "(", "params_list", "[", "i", "]", "[", "0", "]", ")", "attack_pattern", "=", "HTTP", ".", "HTTPResource", "(", "form", ".", "path", ",", "method", "=", "form", ".", "method", ",", "get_params", "=", "get_params", ",", "post_params", "=", "post_params", ",", "file_params", "=", "file_params", ")", "if", "attack_pattern", "not", "in", "self", ".", "attackedPOST", ":", "self", ".", "attackedPOST", ".", "append", "(", "attack_pattern", ")", "if", "params_list", "is", "file_params", ":", "params_list", "[", "i", "]", "[", "1", "]", "[", "0", "]", "=", "filename_payload", "else", ":", "params_list", "[", "i", "]", "[", "1", "]", "=", "payload", "evil_req", "=", "HTTP", ".", "HTTPResource", "(", "form", ".", "path", ",", "method", "=", "form", ".", "method", ",", "get_params", "=", "get_params", ",", "post_params", "=", "post_params", ",", "file_params", "=", "file_params", ",", "referer", "=", "referer", ")", "if", "self", ".", "verbose", "==", "2", ":", "print", "(", "u\"+ {0}\"", ".", "format", "(", "evil_req", ")", ")", "try", ":", "resp", "=", "self", ".", "HTTP", ".", "send", "(", "evil_req", ")", "data", ",", "code", "=", "resp", ".", "getPageCode", "(", ")", "except", "requests", ".", "exceptions", ".", "Timeout", ",", "timeout", ":", "# No timeout report here... launch blind sql detection later", "code", "=", "\"408\"", "else", ":", "err", "=", "self", ".", "__findPatternInResponse", "(", "data", ")", "if", "err", "!=", "\"\"", ":", "self", ".", "logVuln", "(", "category", "=", "Vulnerability", ".", "SQL_INJECTION", ",", "level", "=", "Vulnerability", ".", "HIGH_LEVEL", ",", "request", "=", "evil_req", ",", "parameter", "=", "param_name", ",", "info", "=", "_", "(", "\"{0} via injection in the parameter {1}\"", ")", ".", "format", "(", "err", ",", "param_name", ")", ")", "self", ".", "logR", "(", "Vulnerability", ".", "MSG_PARAM_INJECT", ",", "err", ",", "evil_req", ".", "url", ",", "param_name", ")", "self", ".", "logR", "(", "Vulnerability", ".", "MSG_EVIL_REQUEST", ")", "self", ".", "logC", "(", "evil_req", ".", "http_repr", ")", "print", "(", "''", ")", "self", ".", "vulnerablePOST", ".", "append", "(", "attack_pattern", ")", "else", ":", "if", "code", "==", "\"500\"", ":", "self", ".", "logAnom", "(", "category", "=", "Anomaly", ".", "ERROR_500", ",", "level", "=", "Anomaly", ".", "HIGH_LEVEL", ",", "request", "=", "evil_req", ",", "parameter", "=", "param_name", ",", "info", "=", "Anomaly", ".", "MSG_PARAM_500", ".", "format", "(", "param_name", ")", ")", "self", ".", "logO", "(", "Anomaly", ".", "MSG_500", ",", "evil_req", ".", "url", ")", "self", ".", "logO", "(", "Anomaly", ".", "MSG_EVIL_REQUEST", ")", "self", ".", "logC", "(", "evil_req", ".", "http_repr", ")", "print", "(", "''", ")", "params_list", "[", "i", "]", "[", "1", "]", "=", "saved_value" ]
https://github.com/IFGHou/wapiti/blob/91242a8ad293a8ee54ab6e62732ff4b9d770772c/wapitiCore/attack/mod_sql.py#L189-L270
omaha-consulting/omaha-server
1aa507b51e3656b490f72a3c9d60ee9d085e389e
omaha_server/omaha/utils.py
python
get_id
(uuid)
return int(id)
>>> get_id('{8C65E04C-0383-4AE2-893F-4EC7C58F70DC}') 1 >>> get_id('{8C65E04C-0383-4AE2-893F-4EC7C58F70DC}') 1
>>> get_id('{8C65E04C-0383-4AE2-893F-4EC7C58F70DC}') 1 >>> get_id('{8C65E04C-0383-4AE2-893F-4EC7C58F70DC}') 1
[ ">>>", "get_id", "(", "{", "8C65E04C", "-", "0383", "-", "4AE2", "-", "893F", "-", "4EC7C58F70DC", "}", ")", "1", ">>>", "get_id", "(", "{", "8C65E04C", "-", "0383", "-", "4AE2", "-", "893F", "-", "4EC7C58F70DC", "}", ")", "1" ]
def get_id(uuid): """ >>> get_id('{8C65E04C-0383-4AE2-893F-4EC7C58F70DC}') 1 >>> get_id('{8C65E04C-0383-4AE2-893F-4EC7C58F70DC}') 1 """ id = redis.get('{}:{}'.format(KEY_PREFIX, uuid)) if id is None: id = create_id(uuid) return int(id)
[ "def", "get_id", "(", "uuid", ")", ":", "id", "=", "redis", ".", "get", "(", "'{}:{}'", ".", "format", "(", "KEY_PREFIX", ",", "uuid", ")", ")", "if", "id", "is", "None", ":", "id", "=", "create_id", "(", "uuid", ")", "return", "int", "(", "id", ")" ]
https://github.com/omaha-consulting/omaha-server/blob/1aa507b51e3656b490f72a3c9d60ee9d085e389e/omaha_server/omaha/utils.py#L66-L76
hzlzh/AlfredWorkflow.com
7055f14f6922c80ea5943839eb0caff11ae57255
Sources/Workflows/KindleBookstore/PyAl/Request/bs4/builder/__init__.py
python
register_treebuilders_from
(module)
Copy TreeBuilders from the given module into this module.
Copy TreeBuilders from the given module into this module.
[ "Copy", "TreeBuilders", "from", "the", "given", "module", "into", "this", "module", "." ]
def register_treebuilders_from(module): """Copy TreeBuilders from the given module into this module.""" # I'm fairly sure this is not the best way to do this. this_module = sys.modules['PyAl.Request.bs4.builder'] for name in module.__all__: obj = getattr(module, name) if issubclass(obj, TreeBuilder): setattr(this_module, name, obj) this_module.__all__.append(name) # Register the builder while we're at it. this_module.builder_registry.register(obj)
[ "def", "register_treebuilders_from", "(", "module", ")", ":", "# I'm fairly sure this is not the best way to do this.", "this_module", "=", "sys", ".", "modules", "[", "'PyAl.Request.bs4.builder'", "]", "for", "name", "in", "module", ".", "__all__", ":", "obj", "=", "getattr", "(", "module", ",", "name", ")", "if", "issubclass", "(", "obj", ",", "TreeBuilder", ")", ":", "setattr", "(", "this_module", ",", "name", ",", "obj", ")", "this_module", ".", "__all__", ".", "append", "(", "name", ")", "# Register the builder while we're at it.", "this_module", ".", "builder_registry", ".", "register", "(", "obj", ")" ]
https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/KindleBookstore/PyAl/Request/bs4/builder/__init__.py#L286-L297
translate/translate
72816df696b5263abfe80ab59129b299b85ae749
translate/convert/yaml2po.py
python
yaml2po.convert_unit
(self, unit)
return target_unit
Convert a source format unit to a target format unit.
Convert a source format unit to a target format unit.
[ "Convert", "a", "source", "format", "unit", "to", "a", "target", "format", "unit", "." ]
def convert_unit(self, unit): """Convert a source format unit to a target format unit.""" target_unit = self.TargetUnitClass(encoding="UTF-8") target_unit.setid(unit.getid()) target_unit.addlocation(unit.getid()) target_unit.addnote(unit.getnotes(), "developer") target_unit.source = unit.source return target_unit
[ "def", "convert_unit", "(", "self", ",", "unit", ")", ":", "target_unit", "=", "self", ".", "TargetUnitClass", "(", "encoding", "=", "\"UTF-8\"", ")", "target_unit", ".", "setid", "(", "unit", ".", "getid", "(", ")", ")", "target_unit", ".", "addlocation", "(", "unit", ".", "getid", "(", ")", ")", "target_unit", ".", "addnote", "(", "unit", ".", "getnotes", "(", ")", ",", "\"developer\"", ")", "target_unit", ".", "source", "=", "unit", ".", "source", "return", "target_unit" ]
https://github.com/translate/translate/blob/72816df696b5263abfe80ab59129b299b85ae749/translate/convert/yaml2po.py#L57-L64
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/plat-linux2/IN.py
python
IN6_IS_ADDR_MC_SITELOCAL
(a)
return
[]
def IN6_IS_ADDR_MC_SITELOCAL(a): return
[ "def", "IN6_IS_ADDR_MC_SITELOCAL", "(", "a", ")", ":", "return" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/plat-linux2/IN.py#L611-L611
feeluown/FeelUOwn
ec104689add09c351e6ca4133a5d0632294b3784
feeluown/player/base_player.py
python
AbstractPlayer.state
(self)
return self._state
Player state :rtype: State
Player state
[ "Player", "state" ]
def state(self): """Player state :rtype: State """ return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
https://github.com/feeluown/FeelUOwn/blob/ec104689add09c351e6ca4133a5d0632294b3784/feeluown/player/base_player.py#L69-L74
CellProfiler/CellProfiler
a90e17e4d258c6f3900238be0f828e0b4bd1b293
cellprofiler/gui/artist.py
python
ColorMixin._set_colormap
(self, colormap)
Override to set the colormap
Override to set the colormap
[ "Override", "to", "set", "the", "colormap" ]
def _set_colormap(self, colormap): """Override to set the colormap""" self._colormap = colormap self._on_colormap_changed()
[ "def", "_set_colormap", "(", "self", ",", "colormap", ")", ":", "self", ".", "_colormap", "=", "colormap", "self", ".", "_on_colormap_changed", "(", ")" ]
https://github.com/CellProfiler/CellProfiler/blob/a90e17e4d258c6f3900238be0f828e0b4bd1b293/cellprofiler/gui/artist.py#L110-L113
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/core/pythonapi.py
python
PythonAPI.number_positive
(self, obj)
return self.builder.call(fn, (obj,))
[]
def number_positive(self, obj): fnty = Type.function(self.pyobj, [self.pyobj]) fn = self._get_function(fnty, name="PyNumber_Positive") return self.builder.call(fn, (obj,))
[ "def", "number_positive", "(", "self", ",", "obj", ")", ":", "fnty", "=", "Type", ".", "function", "(", "self", ".", "pyobj", ",", "[", "self", ".", "pyobj", "]", ")", "fn", "=", "self", ".", "_get_function", "(", "fnty", ",", "name", "=", "\"PyNumber_Positive\"", ")", "return", "self", ".", "builder", ".", "call", "(", "fn", ",", "(", "obj", ",", ")", ")" ]
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/core/pythonapi.py#L616-L619
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/pymysql/charset.py
python
Charset.__init__
(self, id, name, collation, is_default)
[]
def __init__(self, id, name, collation, is_default): self.id, self.name, self.collation = id, name, collation self.is_default = is_default == 'Yes'
[ "def", "__init__", "(", "self", ",", "id", ",", "name", ",", "collation", ",", "is_default", ")", ":", "self", ".", "id", ",", "self", ".", "name", ",", "self", ".", "collation", "=", "id", ",", "name", ",", "collation", "self", ".", "is_default", "=", "is_default", "==", "'Yes'" ]
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/pymysql/charset.py#L10-L12
internetarchive/openlibrary
33b9b005ecb0adeda690c67952f5ae5f1fe3a8d8
openlibrary/plugins/upstream/addbook.py
python
addbook.work_match
(self, saveutil, work, i)
Action for when a work, but not edition, is matched. Saves a new edition of work, created form the formdata i. Redirects the user to the newly created edition page in edit mode to add more details. :param DocSaveHelper saveutil: :param Work work: the matched work for this book :param web.utils.Storage i: user supplied book formdata :rtype: None
Action for when a work, but not edition, is matched. Saves a new edition of work, created form the formdata i. Redirects the user to the newly created edition page in edit mode to add more details.
[ "Action", "for", "when", "a", "work", "but", "not", "edition", "is", "matched", ".", "Saves", "a", "new", "edition", "of", "work", "created", "form", "the", "formdata", "i", ".", "Redirects", "the", "user", "to", "the", "newly", "created", "edition", "page", "in", "edit", "mode", "to", "add", "more", "details", "." ]
def work_match(self, saveutil, work, i): """ Action for when a work, but not edition, is matched. Saves a new edition of work, created form the formdata i. Redirects the user to the newly created edition page in edit mode to add more details. :param DocSaveHelper saveutil: :param Work work: the matched work for this book :param web.utils.Storage i: user supplied book formdata :rtype: None """ edition = self._make_edition(work, i) saveutil.save(edition) comment = utils.get_message("comment_add_book") saveutil.commit(comment=comment, action="add-book") raise safe_seeother(edition.url("/edit?mode=add-book"))
[ "def", "work_match", "(", "self", ",", "saveutil", ",", "work", ",", "i", ")", ":", "edition", "=", "self", ".", "_make_edition", "(", "work", ",", "i", ")", "saveutil", ".", "save", "(", "edition", ")", "comment", "=", "utils", ".", "get_message", "(", "\"comment_add_book\"", ")", "saveutil", ".", "commit", "(", "comment", "=", "comment", ",", "action", "=", "\"add-book\"", ")", "raise", "safe_seeother", "(", "edition", ".", "url", "(", "\"/edit?mode=add-book\"", ")", ")" ]
https://github.com/internetarchive/openlibrary/blob/33b9b005ecb0adeda690c67952f5ae5f1fe3a8d8/openlibrary/plugins/upstream/addbook.py#L390-L408
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/tornado-4.3b2-py3.3-win-amd64.egg/tornado/gen.py
python
YieldPoint.start
(self, runner)
Called by the runner after the generator has yielded. No other methods will be called on this object before ``start``.
Called by the runner after the generator has yielded.
[ "Called", "by", "the", "runner", "after", "the", "generator", "has", "yielded", "." ]
def start(self, runner): """Called by the runner after the generator has yielded. No other methods will be called on this object before ``start``. """ raise NotImplementedError()
[ "def", "start", "(", "self", ",", "runner", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/tornado-4.3b2-py3.3-win-amd64.egg/tornado/gen.py#L464-L469
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/ex-submodules/casexml/apps/case/mock/mock.py
python
CaseFactory.post_case_blocks
(self, caseblocks, form_extras=None, user_id=None, device_id=None)
return post_case_blocks( caseblocks, form_extras=submit_form_extras, domain=self.domain, user_id=user_id, device_id=device_id, )
[]
def post_case_blocks(self, caseblocks, form_extras=None, user_id=None, device_id=None): submit_form_extras = copy.copy(self.form_extras) if form_extras is not None: submit_form_extras.update(form_extras) return post_case_blocks( caseblocks, form_extras=submit_form_extras, domain=self.domain, user_id=user_id, device_id=device_id, )
[ "def", "post_case_blocks", "(", "self", ",", "caseblocks", ",", "form_extras", "=", "None", ",", "user_id", "=", "None", ",", "device_id", "=", "None", ")", ":", "submit_form_extras", "=", "copy", ".", "copy", "(", "self", ".", "form_extras", ")", "if", "form_extras", "is", "not", "None", ":", "submit_form_extras", ".", "update", "(", "form_extras", ")", "return", "post_case_blocks", "(", "caseblocks", ",", "form_extras", "=", "submit_form_extras", ",", "domain", "=", "self", ".", "domain", ",", "user_id", "=", "user_id", ",", "device_id", "=", "device_id", ",", ")" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/ex-submodules/casexml/apps/case/mock/mock.py#L97-L107
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/base.py
python
DropboxBase.files_tags_get
(self, paths)
return r
Get list of tags assigned to items. :param List[str] paths: Path to the items. :rtype: :class:`dropbox.files.GetTagsResult` :raises: :class:`.exceptions.ApiError` If this raises, ApiError will contain: :class:`dropbox.files.BaseTagError`
Get list of tags assigned to items.
[ "Get", "list", "of", "tags", "assigned", "to", "items", "." ]
def files_tags_get(self, paths): """ Get list of tags assigned to items. :param List[str] paths: Path to the items. :rtype: :class:`dropbox.files.GetTagsResult` :raises: :class:`.exceptions.ApiError` If this raises, ApiError will contain: :class:`dropbox.files.BaseTagError` """ arg = files.GetTagsArg(paths) r = self.request( files.tags_get, 'files', arg, None, ) return r
[ "def", "files_tags_get", "(", "self", ",", "paths", ")", ":", "arg", "=", "files", ".", "GetTagsArg", "(", "paths", ")", "r", "=", "self", ".", "request", "(", "files", ".", "tags_get", ",", "'files'", ",", "arg", ",", "None", ",", ")", "return", "r" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/base.py#L2803-L2822
openstack/ironic
b392dc19bcd29cef5a69ec00d2f18a7a19a679e5
ironic/common/driver_factory.py
python
BaseDriverFactory.items
(self)
return ((ext.name, ext.obj) for ext in self._extension_manager)
Iterator over pairs (name, instance).
Iterator over pairs (name, instance).
[ "Iterator", "over", "pairs", "(", "name", "instance", ")", "." ]
def items(self): """Iterator over pairs (name, instance).""" return ((ext.name, ext.obj) for ext in self._extension_manager)
[ "def", "items", "(", "self", ")", ":", "return", "(", "(", "ext", ".", "name", ",", "ext", ".", "obj", ")", "for", "ext", "in", "self", ".", "_extension_manager", ")" ]
https://github.com/openstack/ironic/blob/b392dc19bcd29cef5a69ec00d2f18a7a19a679e5/ironic/common/driver_factory.py#L427-L429
poodarchu/Det3D
01258d8cb26656c5b950f8d41f9dcc1dd62a391e
det3d/datasets/utils/kitti_object_eval_python/evaluate.py
python
_read_imageset_file
(path)
return [int(line) for line in lines]
[]
def _read_imageset_file(path): with open(path, "r") as f: lines = f.readlines() return [int(line) for line in lines]
[ "def", "_read_imageset_file", "(", "path", ")", ":", "with", "open", "(", "path", ",", "\"r\"", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "return", "[", "int", "(", "line", ")", "for", "line", "in", "lines", "]" ]
https://github.com/poodarchu/Det3D/blob/01258d8cb26656c5b950f8d41f9dcc1dd62a391e/det3d/datasets/utils/kitti_object_eval_python/evaluate.py#L8-L11
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/lib-tk/tkSimpleDialog.py
python
Dialog.body
(self, master)
create dialog body. return widget that should have initial focus. This method should be overridden, and is called by the __init__ method.
create dialog body.
[ "create", "dialog", "body", "." ]
def body(self, master): '''create dialog body. return widget that should have initial focus. This method should be overridden, and is called by the __init__ method. ''' pass
[ "def", "body", "(", "self", ",", "master", ")", ":", "pass" ]
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/lib-tk/tkSimpleDialog.py#L96-L103
getting-things-gnome/gtg
4b02c43744b32a00facb98174f04ec5953bd055d
GTG/backends/sync_engine.py
python
SyncEngine.record_relationship
(self, local_id, remote_id, meme)
Records that an object from the local set is related with one a remote set. @param local_id: the id of the local task @param remote_id: the id of the remote task @param meme: the SyncMeme that keeps track of the relationship
Records that an object from the local set is related with one a remote set.
[ "Records", "that", "an", "object", "from", "the", "local", "set", "is", "related", "with", "one", "a", "remote", "set", "." ]
def record_relationship(self, local_id, remote_id, meme): """ Records that an object from the local set is related with one a remote set. @param local_id: the id of the local task @param remote_id: the id of the remote task @param meme: the SyncMeme that keeps track of the relationship """ triplet = (local_id, remote_id, meme) self.sync_memes.add(triplet)
[ "def", "record_relationship", "(", "self", ",", "local_id", ",", "remote_id", ",", "meme", ")", ":", "triplet", "=", "(", "local_id", ",", "remote_id", ",", "meme", ")", "self", ".", "sync_memes", ".", "add", "(", "triplet", ")" ]
https://github.com/getting-things-gnome/gtg/blob/4b02c43744b32a00facb98174f04ec5953bd055d/GTG/backends/sync_engine.py#L240-L250
lisa-lab/pylearn2
af81e5c362f0df4df85c3e54e23b2adeec026055
pylearn2/models/gated_autoencoder.py
python
FactoredGatedAutoencoder._factorsX
(self, inputs)
return tensor.dot(inputs[0], self.wxf)
Applies the filters wxf to the first input and returns the corresponding factors
Applies the filters wxf to the first input and returns the corresponding factors
[ "Applies", "the", "filters", "wxf", "to", "the", "first", "input", "and", "returns", "the", "corresponding", "factors" ]
def _factorsX(self, inputs): """ Applies the filters wxf to the first input and returns the corresponding factors """ return tensor.dot(inputs[0], self.wxf)
[ "def", "_factorsX", "(", "self", ",", "inputs", ")", ":", "return", "tensor", ".", "dot", "(", "inputs", "[", "0", "]", ",", "self", ".", "wxf", ")" ]
https://github.com/lisa-lab/pylearn2/blob/af81e5c362f0df4df85c3e54e23b2adeec026055/pylearn2/models/gated_autoencoder.py#L296-L301
VLSIDA/OpenRAM
f66aac3264598eeae31225c62b6a4af52412d407
compiler/router/router.py
python
router.clear_pins
(self)
Convert the routed path to blockages. Keep the other blockages unchanged.
Convert the routed path to blockages. Keep the other blockages unchanged.
[ "Convert", "the", "routed", "path", "to", "blockages", ".", "Keep", "the", "other", "blockages", "unchanged", "." ]
def clear_pins(self): """ Convert the routed path to blockages. Keep the other blockages unchanged. """ self.pins = {} self.all_pins = set() self.pin_groups = {} # DO NOT clear the blockages as these don't change self.rg.reinit()
[ "def", "clear_pins", "(", "self", ")", ":", "self", ".", "pins", "=", "{", "}", "self", ".", "all_pins", "=", "set", "(", ")", "self", ".", "pin_groups", "=", "{", "}", "# DO NOT clear the blockages as these don't change", "self", ".", "rg", ".", "reinit", "(", ")" ]
https://github.com/VLSIDA/OpenRAM/blob/f66aac3264598eeae31225c62b6a4af52412d407/compiler/router/router.py#L102-L111
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/ssm/v20190923/ssm_client.py
python
SsmClient.UpdateSecret
(self, request)
该接口用于更新指定凭据名称和版本号的内容,调用该接口会对新的凭据内容加密后覆盖旧的内容。仅允许更新Enabled 和 Disabled 状态的凭据。 本接口仅适用于用户自定义凭据,不能对云产品凭据操作。 :param request: Request instance for UpdateSecret. :type request: :class:`tencentcloud.ssm.v20190923.models.UpdateSecretRequest` :rtype: :class:`tencentcloud.ssm.v20190923.models.UpdateSecretResponse`
该接口用于更新指定凭据名称和版本号的内容,调用该接口会对新的凭据内容加密后覆盖旧的内容。仅允许更新Enabled 和 Disabled 状态的凭据。 本接口仅适用于用户自定义凭据,不能对云产品凭据操作。
[ "该接口用于更新指定凭据名称和版本号的内容,调用该接口会对新的凭据内容加密后覆盖旧的内容。仅允许更新Enabled", "和", "Disabled", "状态的凭据。", "本接口仅适用于用户自定义凭据,不能对云产品凭据操作。" ]
def UpdateSecret(self, request): """该接口用于更新指定凭据名称和版本号的内容,调用该接口会对新的凭据内容加密后覆盖旧的内容。仅允许更新Enabled 和 Disabled 状态的凭据。 本接口仅适用于用户自定义凭据,不能对云产品凭据操作。 :param request: Request instance for UpdateSecret. :type request: :class:`tencentcloud.ssm.v20190923.models.UpdateSecretRequest` :rtype: :class:`tencentcloud.ssm.v20190923.models.UpdateSecretResponse` """ try: params = request._serialize() body = self.call("UpdateSecret", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.UpdateSecretResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "UpdateSecret", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"UpdateSecret\"", ",", "params", ")", "response", "=", "json", ".", "loads", "(", "body", ")", "if", "\"Error\"", "not", "in", "response", "[", "\"Response\"", "]", ":", "model", "=", "models", ".", "UpdateSecretResponse", "(", ")", "model", ".", "_deserialize", "(", "response", "[", "\"Response\"", "]", ")", "return", "model", "else", ":", "code", "=", "response", "[", "\"Response\"", "]", "[", "\"Error\"", "]", "[", "\"Code\"", "]", "message", "=", "response", "[", "\"Response\"", "]", "[", "\"Error\"", "]", "[", "\"Message\"", "]", "reqid", "=", "response", "[", "\"Response\"", "]", "[", "\"RequestId\"", "]", "raise", "TencentCloudSDKException", "(", "code", ",", "message", ",", "reqid", ")", "except", "Exception", "as", "e", ":", "if", "isinstance", "(", "e", ",", "TencentCloudSDKException", ")", ":", "raise", "else", ":", "raise", "TencentCloudSDKException", "(", "e", ".", "message", ",", "e", ".", "message", ")" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/ssm/v20190923/ssm_client.py#L681-L707
iGio90/Dwarf
bb3011cdffd209c7e3f5febe558053bf649ca69c
dwarf_debugger/lib/core.py
python
Dwarf.current_context
(self)
return None
[]
def current_context(self): key = str(self.context_tid) if key in self.contexts: return self.contexts[key] return None
[ "def", "current_context", "(", "self", ")", ":", "key", "=", "str", "(", "self", ".", "context_tid", ")", "if", "key", "in", "self", ".", "contexts", ":", "return", "self", ".", "contexts", "[", "key", "]", "return", "None" ]
https://github.com/iGio90/Dwarf/blob/bb3011cdffd209c7e3f5febe558053bf649ca69c/dwarf_debugger/lib/core.py#L241-L245
grow/grow
97fc21730b6a674d5d33948d94968e79447ce433
grow/pods/ui.py
python
create_jinja_env
()
return env
[]
def create_jinja_env(): root = os.path.join(utils.get_grow_dir(), 'ui', 'admin') loader = storage.FileStorage.JinjaLoader(root) env = jinja2.Environment( loader=loader, autoescape=True, trim_blocks=True, extensions=[ 'jinja2.ext.autoescape', 'jinja2.ext.do', 'jinja2.ext.i18n', 'jinja2.ext.loopcontrols', 'jinja2.ext.with_', ]) env.filters.update(filters.create_builtin_filters(env, None)) return env
[ "def", "create_jinja_env", "(", ")", ":", "root", "=", "os", ".", "path", ".", "join", "(", "utils", ".", "get_grow_dir", "(", ")", ",", "'ui'", ",", "'admin'", ")", "loader", "=", "storage", ".", "FileStorage", ".", "JinjaLoader", "(", "root", ")", "env", "=", "jinja2", ".", "Environment", "(", "loader", "=", "loader", ",", "autoescape", "=", "True", ",", "trim_blocks", "=", "True", ",", "extensions", "=", "[", "'jinja2.ext.autoescape'", ",", "'jinja2.ext.do'", ",", "'jinja2.ext.i18n'", ",", "'jinja2.ext.loopcontrols'", ",", "'jinja2.ext.with_'", ",", "]", ")", "env", ".", "filters", ".", "update", "(", "filters", ".", "create_builtin_filters", "(", "env", ",", "None", ")", ")", "return", "env" ]
https://github.com/grow/grow/blob/97fc21730b6a674d5d33948d94968e79447ce433/grow/pods/ui.py#L11-L26
arthurdejong/python-stdnum
02dec52602ae0709b940b781fc1fcebfde7340b7
stdnum/it/aic.py
python
compact
(number)
return clean(number, ' ').upper().strip()
Convert the number to the minimal representation.
Convert the number to the minimal representation.
[ "Convert", "the", "number", "to", "the", "minimal", "representation", "." ]
def compact(number): """Convert the number to the minimal representation.""" return clean(number, ' ').upper().strip()
[ "def", "compact", "(", "number", ")", ":", "return", "clean", "(", "number", ",", "' '", ")", ".", "upper", "(", ")", ".", "strip", "(", ")" ]
https://github.com/arthurdejong/python-stdnum/blob/02dec52602ae0709b940b781fc1fcebfde7340b7/stdnum/it/aic.py#L58-L60
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idc.py
python
SetBmaskName
(enum_id, bmask, name)
return idaapi.set_bmask_name(enum_id, bmask, name)
Set bitmask name (only for bitfields) @param enum_id: id of enum @param bmask: bitmask of the constant @param name: name of bitmask @return: 1-ok, 0-failed
Set bitmask name (only for bitfields)
[ "Set", "bitmask", "name", "(", "only", "for", "bitfields", ")" ]
def SetBmaskName(enum_id, bmask, name): """ Set bitmask name (only for bitfields) @param enum_id: id of enum @param bmask: bitmask of the constant @param name: name of bitmask @return: 1-ok, 0-failed """ if bmask < 0: bmask &= BADADDR return idaapi.set_bmask_name(enum_id, bmask, name)
[ "def", "SetBmaskName", "(", "enum_id", ",", "bmask", ",", "name", ")", ":", "if", "bmask", "<", "0", ":", "bmask", "&=", "BADADDR", "return", "idaapi", ".", "set_bmask_name", "(", "enum_id", ",", "bmask", ",", "name", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idc.py#L5990-L6002
FSecureLABS/Jandroid
e31d0dab58a2bfd6ed8e0a387172b8bd7c893436
libs/platform-tools/platform-tools_windows/systrace/catapult/devil/devil/android/fastboot_utils.py
python
FastbootUtils.WaitForFastbootMode
(self, timeout=None, retries=None)
Wait for device to boot into fastboot mode. This waits for the device serial to show up in fastboot devices output.
Wait for device to boot into fastboot mode.
[ "Wait", "for", "device", "to", "boot", "into", "fastboot", "mode", "." ]
def WaitForFastbootMode(self, timeout=None, retries=None): """Wait for device to boot into fastboot mode. This waits for the device serial to show up in fastboot devices output. """ def fastboot_mode(): return self._serial in self.fastboot.Devices() timeout_retry.WaitFor(fastboot_mode, wait_period=self._FASTBOOT_WAIT_TIME)
[ "def", "WaitForFastbootMode", "(", "self", ",", "timeout", "=", "None", ",", "retries", "=", "None", ")", ":", "def", "fastboot_mode", "(", ")", ":", "return", "self", ".", "_serial", "in", "self", ".", "fastboot", ".", "Devices", "(", ")", "timeout_retry", ".", "WaitFor", "(", "fastboot_mode", ",", "wait_period", "=", "self", ".", "_FASTBOOT_WAIT_TIME", ")" ]
https://github.com/FSecureLABS/Jandroid/blob/e31d0dab58a2bfd6ed8e0a387172b8bd7c893436/libs/platform-tools/platform-tools_windows/systrace/catapult/devil/devil/android/fastboot_utils.py#L105-L113
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/decimal.py
python
Decimal.__abs__
(self, round=True, context=None)
return ans
Returns the absolute value of self. If the keyword argument 'round' is false, do not round. The expression self.__abs__(round=False) is equivalent to self.copy_abs().
Returns the absolute value of self.
[ "Returns", "the", "absolute", "value", "of", "self", "." ]
def __abs__(self, round=True, context=None): """Returns the absolute value of self. If the keyword argument 'round' is false, do not round. The expression self.__abs__(round=False) is equivalent to self.copy_abs(). """ if not round: return self.copy_abs() if self._is_special: ans = self._check_nans(context=context) if ans: return ans if self._sign: ans = self.__neg__(context=context) else: ans = self.__pos__(context=context) return ans
[ "def", "__abs__", "(", "self", ",", "round", "=", "True", ",", "context", "=", "None", ")", ":", "if", "not", "round", ":", "return", "self", ".", "copy_abs", "(", ")", "if", "self", ".", "_is_special", ":", "ans", "=", "self", ".", "_check_nans", "(", "context", "=", "context", ")", "if", "ans", ":", "return", "ans", "if", "self", ".", "_sign", ":", "ans", "=", "self", ".", "__neg__", "(", "context", "=", "context", ")", "else", ":", "ans", "=", "self", ".", "__pos__", "(", "context", "=", "context", ")", "return", "ans" ]
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/decimal.py#L1128-L1148
rhinstaller/anaconda
63edc8680f1b05cbfe11bef28703acba808c5174
pyanaconda/modules/common/structures/user.py
python
UserData.get_uid
(self)
Return a UID value which can be a number or None. Prefer using this method instead of directly reading uid and uid_mode. :return: UID or None if not set :rtype: int or None
Return a UID value which can be a number or None.
[ "Return", "a", "UID", "value", "which", "can", "be", "a", "number", "or", "None", "." ]
def get_uid(self): """Return a UID value which can be a number or None. Prefer using this method instead of directly reading uid and uid_mode. :return: UID or None if not set :rtype: int or None """ if self._uid_mode == ID_MODE_USE_DEFAULT: return None else: return self._uid
[ "def", "get_uid", "(", "self", ")", ":", "if", "self", ".", "_uid_mode", "==", "ID_MODE_USE_DEFAULT", ":", "return", "None", "else", ":", "return", "self", ".", "_uid" ]
https://github.com/rhinstaller/anaconda/blob/63edc8680f1b05cbfe11bef28703acba808c5174/pyanaconda/modules/common/structures/user.py#L99-L110
csujedihy/lc-all-solutions
b9fd938a7b3c164f28096361993600e338c399c3
157.read-n-characters-given-read4/read-n-characters-given-read4.py
python
Solution.read
(self, buf, n)
return cnt
:type buf: Destination buffer (List[str]) :type n: Maximum number of characters to read (int) :rtype: The number of characters read (int)
:type buf: Destination buffer (List[str]) :type n: Maximum number of characters to read (int) :rtype: The number of characters read (int)
[ ":", "type", "buf", ":", "Destination", "buffer", "(", "List", "[", "str", "]", ")", ":", "type", "n", ":", "Maximum", "number", "of", "characters", "to", "read", "(", "int", ")", ":", "rtype", ":", "The", "number", "of", "characters", "read", "(", "int", ")" ]
def read(self, buf, n): """ :type buf: Destination buffer (List[str]) :type n: Maximum number of characters to read (int) :rtype: The number of characters read (int) """ cnt = 0 tmp = [""] * 4 while cnt < n: r = read4(tmp) if r == 0: break for i in range(min(r, n - cnt)): buf[cnt] = tmp[i] cnt += 1 return cnt
[ "def", "read", "(", "self", ",", "buf", ",", "n", ")", ":", "cnt", "=", "0", "tmp", "=", "[", "\"\"", "]", "*", "4", "while", "cnt", "<", "n", ":", "r", "=", "read4", "(", "tmp", ")", "if", "r", "==", "0", ":", "break", "for", "i", "in", "range", "(", "min", "(", "r", ",", "n", "-", "cnt", ")", ")", ":", "buf", "[", "cnt", "]", "=", "tmp", "[", "i", "]", "cnt", "+=", "1", "return", "cnt" ]
https://github.com/csujedihy/lc-all-solutions/blob/b9fd938a7b3c164f28096361993600e338c399c3/157.read-n-characters-given-read4/read-n-characters-given-read4.py#L7-L22
Tencent/QT4A
cc99ce12bd10f864c95b7bf0675fd1b757bce4bb
qt4a/androiddriver/androiddriver.py
python
AndroidDriver._wait_for_event
(self, thread_id, timeout)
return ret
等待事件
等待事件
[ "等待事件" ]
def _wait_for_event(self, thread_id, timeout): """等待事件 """ if self._get_lock(thread_id).is_set(): return time0 = time.time() ret = self._get_lock(thread_id).wait(timeout) if ret: cost_time = time.time() - time0 logger.debug("thread %s wait %s S" % (thread_id, cost_time)) else: # 超时 logger.warn("thread %s wait for sync event timeout" % thread_id) self.resume_thread(thread_id) # 防止出错后一直等待 return ret
[ "def", "_wait_for_event", "(", "self", ",", "thread_id", ",", "timeout", ")", ":", "if", "self", ".", "_get_lock", "(", "thread_id", ")", ".", "is_set", "(", ")", ":", "return", "time0", "=", "time", ".", "time", "(", ")", "ret", "=", "self", ".", "_get_lock", "(", "thread_id", ")", ".", "wait", "(", "timeout", ")", "if", "ret", ":", "cost_time", "=", "time", ".", "time", "(", ")", "-", "time0", "logger", ".", "debug", "(", "\"thread %s wait %s S\"", "%", "(", "thread_id", ",", "cost_time", ")", ")", "else", ":", "# 超时", "logger", ".", "warn", "(", "\"thread %s wait for sync event timeout\"", "%", "thread_id", ")", "self", ".", "resume_thread", "(", "thread_id", ")", "# 防止出错后一直等待", "return", "ret" ]
https://github.com/Tencent/QT4A/blob/cc99ce12bd10f864c95b7bf0675fd1b757bce4bb/qt4a/androiddriver/androiddriver.py#L562-L576
zaxlct/imooc-django
daf1ced745d3d21989e8191b658c293a511b37fd
extra_apps/xadmin/plugins/xversion.py
python
RecoverView.post_response
(self)
return HttpResponseRedirect(self.model_admin_url('change', self.new_obj.pk))
[]
def post_response(self): self.message_user(_('The %(model)s "%(name)s" was recovered successfully. You may edit it again below.') % {"model": force_text(self.opts.verbose_name), "name": smart_text(self.new_obj)}, 'success') return HttpResponseRedirect(self.model_admin_url('change', self.new_obj.pk))
[ "def", "post_response", "(", "self", ")", ":", "self", ".", "message_user", "(", "_", "(", "'The %(model)s \"%(name)s\" was recovered successfully. You may edit it again below.'", ")", "%", "{", "\"model\"", ":", "force_text", "(", "self", ".", "opts", ".", "verbose_name", ")", ",", "\"name\"", ":", "smart_text", "(", "self", ".", "new_obj", ")", "}", ",", "'success'", ")", "return", "HttpResponseRedirect", "(", "self", ".", "model_admin_url", "(", "'change'", ",", "self", ".", "new_obj", ".", "pk", ")", ")" ]
https://github.com/zaxlct/imooc-django/blob/daf1ced745d3d21989e8191b658c293a511b37fd/extra_apps/xadmin/plugins/xversion.py#L477-L480
jython/frozen-mirror
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
lib-python/2.7/plat-mac/gensuitemodule.py
python
identify
(str)
return rv
Turn any string into an identifier: - replace space by _ - replace other illegal chars by _xx_ (hex code) - append _ if the result is a python keyword
Turn any string into an identifier: - replace space by _ - replace other illegal chars by _xx_ (hex code) - append _ if the result is a python keyword
[ "Turn", "any", "string", "into", "an", "identifier", ":", "-", "replace", "space", "by", "_", "-", "replace", "other", "illegal", "chars", "by", "_xx_", "(", "hex", "code", ")", "-", "append", "_", "if", "the", "result", "is", "a", "python", "keyword" ]
def identify(str): """Turn any string into an identifier: - replace space by _ - replace other illegal chars by _xx_ (hex code) - append _ if the result is a python keyword """ if not str: return "empty_ae_name_" rv = '' ok = string.ascii_letters + '_' ok2 = ok + string.digits for c in str: if c in ok: rv = rv + c elif c == ' ': rv = rv + '_' else: rv = rv + '_%02.2x_'%ord(c) ok = ok2 if keyword.iskeyword(rv): rv = rv + '_' return rv
[ "def", "identify", "(", "str", ")", ":", "if", "not", "str", ":", "return", "\"empty_ae_name_\"", "rv", "=", "''", "ok", "=", "string", ".", "ascii_letters", "+", "'_'", "ok2", "=", "ok", "+", "string", ".", "digits", "for", "c", "in", "str", ":", "if", "c", "in", "ok", ":", "rv", "=", "rv", "+", "c", "elif", "c", "==", "' '", ":", "rv", "=", "rv", "+", "'_'", "else", ":", "rv", "=", "rv", "+", "'_%02.2x_'", "%", "ord", "(", "c", ")", "ok", "=", "ok2", "if", "keyword", ".", "iskeyword", "(", "rv", ")", ":", "rv", "=", "rv", "+", "'_'", "return", "rv" ]
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/lib-python/2.7/plat-mac/gensuitemodule.py#L1189-L1210
fluentpython/example-code-2e
80f7f84274a47579e59c29a4657691525152c9d5
15-more-types/protocol/mymax/mymax_demo.py
python
demo_different_key_none
()
[]
def demo_different_key_none() -> None: args = iter('banana kiwi mango apple'.split()) key = None expected = 'mango' result = my.max(args, key=key) print(args, key, expected, result, sep='\n') assert result == expected if TYPE_CHECKING: reveal_type(args) reveal_type(key) reveal_type(expected) reveal_type(result)
[ "def", "demo_different_key_none", "(", ")", "->", "None", ":", "args", "=", "iter", "(", "'banana kiwi mango apple'", ".", "split", "(", ")", ")", "key", "=", "None", "expected", "=", "'mango'", "result", "=", "my", ".", "max", "(", "args", ",", "key", "=", "key", ")", "print", "(", "args", ",", "key", ",", "expected", ",", "result", ",", "sep", "=", "'\\n'", ")", "assert", "result", "==", "expected", "if", "TYPE_CHECKING", ":", "reveal_type", "(", "args", ")", "reveal_type", "(", "key", ")", "reveal_type", "(", "expected", ")", "reveal_type", "(", "result", ")" ]
https://github.com/fluentpython/example-code-2e/blob/80f7f84274a47579e59c29a4657691525152c9d5/15-more-types/protocol/mymax/mymax_demo.py#L82-L93
WangYueFt/rfs
f8c837ba93c62dd0ac68a2f4019c619aa86b8421
models/resnet_new.py
python
conv3x3
(in_planes, out_planes, stride=1)
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
3x3 convolution with padding
3x3 convolution with padding
[ "3x3", "convolution", "with", "padding" ]
def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
[ "def", "conv3x3", "(", "in_planes", ",", "out_planes", ",", "stride", "=", "1", ")", ":", "return", "nn", ".", "Conv2d", "(", "in_planes", ",", "out_planes", ",", "kernel_size", "=", "3", ",", "stride", "=", "stride", ",", "padding", "=", "1", ",", "bias", "=", "False", ")" ]
https://github.com/WangYueFt/rfs/blob/f8c837ba93c62dd0ac68a2f4019c619aa86b8421/models/resnet_new.py#L17-L20
jansel/opentuner
070c5cef6d933eb760a2f9cd5cd08c95f27aee75
opentuner/search/technique.py
python
SearchTechnique.default_generated_name
(self)
return self.base_name()
The default generated name for this technique
The default generated name for this technique
[ "The", "default", "generated", "name", "for", "this", "technique" ]
def default_generated_name(self): """ The default generated name for this technique """ return self.base_name()
[ "def", "default_generated_name", "(", "self", ")", ":", "return", "self", ".", "base_name", "(", ")" ]
https://github.com/jansel/opentuner/blob/070c5cef6d933eb760a2f9cd5cd08c95f27aee75/opentuner/search/technique.py#L129-L131
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/databases/cremona.py
python
MiniCremonaDatabase.elliptic_curve_from_ainvs
(self, ainvs)
return elliptic.EllipticCurve(ainvs, **data)
Return the elliptic curve in the database of with minimal ``ainvs``, if it exists, or raises a ``RuntimeError`` exception otherwise. INPUT: - ``ainvs`` - list (5-tuple of int's); the minimal Weierstrass model for an elliptic curve OUTPUT: EllipticCurve EXAMPLES:: sage: c = CremonaDatabase() sage: c.elliptic_curve_from_ainvs([0, -1, 1, -10, -20]) Elliptic Curve defined by y^2 + y = x^3 - x^2 - 10*x - 20 over Rational Field sage: c.elliptic_curve_from_ainvs([1, 0, 0, -101, 382]) # optional - database_cremona_ellcurve Elliptic Curve defined by y^2 + x*y = x^3 - 101*x + 382 over Rational Field Old (pre-2006) Cremona labels are also allowed:: sage: c.elliptic_curve('9450KKKK1') Elliptic Curve defined by y^2 + x*y + y = x^3 - x^2 - 5*x + 7 over Rational Field Make sure :trac:`12565` is fixed:: sage: c.elliptic_curve('10a1') Traceback (most recent call last): ... ValueError: There is no elliptic curve with label 10a1 in the database
Return the elliptic curve in the database of with minimal ``ainvs``, if it exists, or raises a ``RuntimeError`` exception otherwise.
[ "Return", "the", "elliptic", "curve", "in", "the", "database", "of", "with", "minimal", "ainvs", "if", "it", "exists", "or", "raises", "a", "RuntimeError", "exception", "otherwise", "." ]
def elliptic_curve_from_ainvs(self, ainvs): """ Return the elliptic curve in the database of with minimal ``ainvs``, if it exists, or raises a ``RuntimeError`` exception otherwise. INPUT: - ``ainvs`` - list (5-tuple of int's); the minimal Weierstrass model for an elliptic curve OUTPUT: EllipticCurve EXAMPLES:: sage: c = CremonaDatabase() sage: c.elliptic_curve_from_ainvs([0, -1, 1, -10, -20]) Elliptic Curve defined by y^2 + y = x^3 - x^2 - 10*x - 20 over Rational Field sage: c.elliptic_curve_from_ainvs([1, 0, 0, -101, 382]) # optional - database_cremona_ellcurve Elliptic Curve defined by y^2 + x*y = x^3 - 101*x + 382 over Rational Field Old (pre-2006) Cremona labels are also allowed:: sage: c.elliptic_curve('9450KKKK1') Elliptic Curve defined by y^2 + x*y + y = x^3 - x^2 - 5*x + 7 over Rational Field Make sure :trac:`12565` is fixed:: sage: c.elliptic_curve('10a1') Traceback (most recent call last): ... ValueError: There is no elliptic curve with label 10a1 in the database """ data = self.data_from_coefficients(ainvs) return elliptic.EllipticCurve(ainvs, **data)
[ "def", "elliptic_curve_from_ainvs", "(", "self", ",", "ainvs", ")", ":", "data", "=", "self", ".", "data_from_coefficients", "(", "ainvs", ")", "return", "elliptic", ".", "EllipticCurve", "(", "ainvs", ",", "*", "*", "data", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/databases/cremona.py#L953-L987
adulau/Forban
4b06c8a2e2f18ff872ca20a534587a5f15a692fa
lib/ext/cherrypy/lib/httpauth.py
python
parseAuthorization
(credentials)
return params
parseAuthorization will convert the value of the 'Authorization' key in the HTTP header to a map itself. If the parsing fails 'None' is returned.
parseAuthorization will convert the value of the 'Authorization' key in the HTTP header to a map itself. If the parsing fails 'None' is returned.
[ "parseAuthorization", "will", "convert", "the", "value", "of", "the", "Authorization", "key", "in", "the", "HTTP", "header", "to", "a", "map", "itself", ".", "If", "the", "parsing", "fails", "None", "is", "returned", "." ]
def parseAuthorization (credentials): """parseAuthorization will convert the value of the 'Authorization' key in the HTTP header to a map itself. If the parsing fails 'None' is returned. """ global AUTH_SCHEMES auth_scheme, auth_params = credentials.split(" ", 1) auth_scheme = auth_scheme.lower () parser = AUTH_SCHEMES[auth_scheme] params = parser (auth_params) if params is None: return assert "auth_scheme" not in params params["auth_scheme"] = auth_scheme return params
[ "def", "parseAuthorization", "(", "credentials", ")", ":", "global", "AUTH_SCHEMES", "auth_scheme", ",", "auth_params", "=", "credentials", ".", "split", "(", "\" \"", ",", "1", ")", "auth_scheme", "=", "auth_scheme", ".", "lower", "(", ")", "parser", "=", "AUTH_SCHEMES", "[", "auth_scheme", "]", "params", "=", "parser", "(", "auth_params", ")", "if", "params", "is", "None", ":", "return", "assert", "\"auth_scheme\"", "not", "in", "params", "params", "[", "\"auth_scheme\"", "]", "=", "auth_scheme", "return", "params" ]
https://github.com/adulau/Forban/blob/4b06c8a2e2f18ff872ca20a534587a5f15a692fa/lib/ext/cherrypy/lib/httpauth.py#L164-L182
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/Werkzeug-0.8.3-py2.7.egg/werkzeug/contrib/sessions.py
python
SessionStore.new
(self)
return self.session_class({}, self.generate_key(), True)
Generate a new session.
Generate a new session.
[ "Generate", "a", "new", "session", "." ]
def new(self): """Generate a new session.""" return self.session_class({}, self.generate_key(), True)
[ "def", "new", "(", "self", ")", ":", "return", "self", ".", "session_class", "(", "{", "}", ",", "self", ".", "generate_key", "(", ")", ",", "True", ")" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/Werkzeug-0.8.3-py2.7.egg/werkzeug/contrib/sessions.py#L162-L164
GoogleCloudPlatform/PerfKitBenchmarker
6e3412d7d5e414b8ca30ed5eaf970cef1d919a67
perfkitbenchmarker/providers/docker/docker_container_instance.py
python
DockerContainer._GetContainerInfo
(self)
return info, return_code
Returns information about a container. Gets Container information from Docker Inspect. Returns the information, if there is any and a return code. 0
Returns information about a container.
[ "Returns", "information", "about", "a", "container", "." ]
def _GetContainerInfo(self): """Returns information about a container. Gets Container information from Docker Inspect. Returns the information, if there is any and a return code. 0 """ logging.info('Checking Container Information') inspect_cmd = ['docker', 'inspect', self.name] info, _, return_code = vm_util.IssueCommand(inspect_cmd, suppress_warning=True, raise_on_failure=False) info = json.loads(info) return info, return_code
[ "def", "_GetContainerInfo", "(", "self", ")", ":", "logging", ".", "info", "(", "'Checking Container Information'", ")", "inspect_cmd", "=", "[", "'docker'", ",", "'inspect'", ",", "self", ".", "name", "]", "info", ",", "_", ",", "return_code", "=", "vm_util", ".", "IssueCommand", "(", "inspect_cmd", ",", "suppress_warning", "=", "True", ",", "raise_on_failure", "=", "False", ")", "info", "=", "json", ".", "loads", "(", "info", ")", "return", "info", ",", "return_code" ]
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/6e3412d7d5e414b8ca30ed5eaf970cef1d919a67/perfkitbenchmarker/providers/docker/docker_container_instance.py#L204-L216
Esri/ArcREST
ab240fde2b0200f61d4a5f6df033516e53f2f416
src/arcrest/manageorg/_parameters.py
python
GenerateParameter.enforceOutputJsonSizeLimit
(self, value)
gets/sets the enforceOutputJsonSizeLimit
gets/sets the enforceOutputJsonSizeLimit
[ "gets", "/", "sets", "the", "enforceOutputJsonSizeLimit" ]
def enforceOutputJsonSizeLimit(self, value): """gets/sets the enforceOutputJsonSizeLimit""" if self._enforceOutputJsonSizeLimit != value: self._enforceOutputJsonSizeLimit = value
[ "def", "enforceOutputJsonSizeLimit", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_enforceOutputJsonSizeLimit", "!=", "value", ":", "self", ".", "_enforceOutputJsonSizeLimit", "=", "value" ]
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/_parameters.py#L2241-L2244
oanda/v20-python
f28192f4a31bce038cf6dfa302f5878bec192fe5
src/v20/transaction.py
python
DelayedTradeClosureTransaction.from_dict
(data, ctx)
return DelayedTradeClosureTransaction(**data)
Instantiate a new DelayedTradeClosureTransaction from a dict (generally from loading a JSON response). The data used to instantiate the DelayedTradeClosureTransaction is a shallow copy of the dict passed in, with any complex child types instantiated appropriately.
Instantiate a new DelayedTradeClosureTransaction from a dict (generally from loading a JSON response). The data used to instantiate the DelayedTradeClosureTransaction is a shallow copy of the dict passed in, with any complex child types instantiated appropriately.
[ "Instantiate", "a", "new", "DelayedTradeClosureTransaction", "from", "a", "dict", "(", "generally", "from", "loading", "a", "JSON", "response", ")", ".", "The", "data", "used", "to", "instantiate", "the", "DelayedTradeClosureTransaction", "is", "a", "shallow", "copy", "of", "the", "dict", "passed", "in", "with", "any", "complex", "child", "types", "instantiated", "appropriately", "." ]
def from_dict(data, ctx): """ Instantiate a new DelayedTradeClosureTransaction from a dict (generally from loading a JSON response). The data used to instantiate the DelayedTradeClosureTransaction is a shallow copy of the dict passed in, with any complex child types instantiated appropriately. """ data = data.copy() return DelayedTradeClosureTransaction(**data)
[ "def", "from_dict", "(", "data", ",", "ctx", ")", ":", "data", "=", "data", ".", "copy", "(", ")", "return", "DelayedTradeClosureTransaction", "(", "*", "*", "data", ")" ]
https://github.com/oanda/v20-python/blob/f28192f4a31bce038cf6dfa302f5878bec192fe5/src/v20/transaction.py#L5212-L5222
intel/virtual-storage-manager
00706ab9701acbd0d5e04b19cc80c6b66a2973b8
source/vsm/vsm/db/sqlalchemy/utils.py
python
check_shadow_table
(migrate_engine, table_name)
return True
This method checks that table with ``table_name`` and corresponding shadow table have same columns.
This method checks that table with ``table_name`` and corresponding shadow table have same columns.
[ "This", "method", "checks", "that", "table", "with", "table_name", "and", "corresponding", "shadow", "table", "have", "same", "columns", "." ]
def check_shadow_table(migrate_engine, table_name): """ This method checks that table with ``table_name`` and corresponding shadow table have same columns. """ meta = MetaData() meta.bind = migrate_engine table = Table(table_name, meta, autoload=True) shadow_table = Table(db._SHADOW_TABLE_PREFIX + table_name, meta, autoload=True) columns = dict([(c.name, c) for c in table.columns]) shadow_columns = dict([(c.name, c) for c in shadow_table.columns]) for name, column in columns.iteritems(): if name not in shadow_columns: raise exception.NovaException( _("Missing column %(table)s.%(column)s in shadow table") % {'column': name, 'table': shadow_table.name}) shadow_column = shadow_columns[name] if not isinstance(shadow_column.type, type(column.type)): raise exception.NovaException( _("Different types in %(table)s.%(column)s and shadow table: " "%(c_type)s %(shadow_c_type)s") % {'column': name, 'table': table.name, 'c_type': column.type, 'shadow_c_type': shadow_column.type}) for name, column in shadow_columns.iteritems(): if name not in columns: raise exception.NovaException( _("Extra column %(table)s.%(column)s in shadow table") % {'column': name, 'table': shadow_table.name}) return True
[ "def", "check_shadow_table", "(", "migrate_engine", ",", "table_name", ")", ":", "meta", "=", "MetaData", "(", ")", "meta", ".", "bind", "=", "migrate_engine", "table", "=", "Table", "(", "table_name", ",", "meta", ",", "autoload", "=", "True", ")", "shadow_table", "=", "Table", "(", "db", ".", "_SHADOW_TABLE_PREFIX", "+", "table_name", ",", "meta", ",", "autoload", "=", "True", ")", "columns", "=", "dict", "(", "[", "(", "c", ".", "name", ",", "c", ")", "for", "c", "in", "table", ".", "columns", "]", ")", "shadow_columns", "=", "dict", "(", "[", "(", "c", ".", "name", ",", "c", ")", "for", "c", "in", "shadow_table", ".", "columns", "]", ")", "for", "name", ",", "column", "in", "columns", ".", "iteritems", "(", ")", ":", "if", "name", "not", "in", "shadow_columns", ":", "raise", "exception", ".", "NovaException", "(", "_", "(", "\"Missing column %(table)s.%(column)s in shadow table\"", ")", "%", "{", "'column'", ":", "name", ",", "'table'", ":", "shadow_table", ".", "name", "}", ")", "shadow_column", "=", "shadow_columns", "[", "name", "]", "if", "not", "isinstance", "(", "shadow_column", ".", "type", ",", "type", "(", "column", ".", "type", ")", ")", ":", "raise", "exception", ".", "NovaException", "(", "_", "(", "\"Different types in %(table)s.%(column)s and shadow table: \"", "\"%(c_type)s %(shadow_c_type)s\"", ")", "%", "{", "'column'", ":", "name", ",", "'table'", ":", "table", ".", "name", ",", "'c_type'", ":", "column", ".", "type", ",", "'shadow_c_type'", ":", "shadow_column", ".", "type", "}", ")", "for", "name", ",", "column", "in", "shadow_columns", ".", "iteritems", "(", ")", ":", "if", "name", "not", "in", "columns", ":", "raise", "exception", ".", "NovaException", "(", "_", "(", "\"Extra column %(table)s.%(column)s in shadow table\"", ")", "%", "{", "'column'", ":", "name", ",", "'table'", ":", "shadow_table", ".", "name", "}", ")", "return", "True" ]
https://github.com/intel/virtual-storage-manager/blob/00706ab9701acbd0d5e04b19cc80c6b66a2973b8/source/vsm/vsm/db/sqlalchemy/utils.py#L233-L268