Search is not available for this dataset
identifier
stringlengths 1
155
| parameters
stringlengths 2
6.09k
| docstring
stringlengths 11
63.4k
| docstring_summary
stringlengths 0
63.4k
| function
stringlengths 29
99.8k
| function_tokens
sequence | start_point
sequence | end_point
sequence | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
handle_gather | () | Handle key press from a user. | Handle key press from a user. | def handle_gather():
"""Handle key press from a user."""
digit_pressed = request.values.get('Digits', None)
if digit_pressed == "1":
resp = VoiceResponse()
# Dial (310) 555-1212 - connect that number to the incoming caller.
resp.dial("+13105551212")
# If the dial fails:
resp.say("The call failed, or the remote party hung up. Goodbye.")
return str(resp)
elif digit_pressed == "2":
resp = VoiceResponse()
resp.say("Record your message after the tone.")
resp.record(maxLength="30", action="/handle-recording")
return str(resp)
# If the caller pressed anything but 1, redirect them to the homepage.
else:
return redirect("/") | [
"def",
"handle_gather",
"(",
")",
":",
"digit_pressed",
"=",
"request",
".",
"values",
".",
"get",
"(",
"'Digits'",
",",
"None",
")",
"if",
"digit_pressed",
"==",
"\"1\"",
":",
"resp",
"=",
"VoiceResponse",
"(",
")",
"# Dial (310) 555-1212 - connect that number to the incoming caller.",
"resp",
".",
"dial",
"(",
"\"+13105551212\"",
")",
"# If the dial fails:",
"resp",
".",
"say",
"(",
"\"The call failed, or the remote party hung up. Goodbye.\"",
")",
"return",
"str",
"(",
"resp",
")",
"elif",
"digit_pressed",
"==",
"\"2\"",
":",
"resp",
"=",
"VoiceResponse",
"(",
")",
"resp",
".",
"say",
"(",
"\"Record your message after the tone.\"",
")",
"resp",
".",
"record",
"(",
"maxLength",
"=",
"\"30\"",
",",
"action",
"=",
"\"/handle-recording\"",
")",
"return",
"str",
"(",
"resp",
")",
"# If the caller pressed anything but 1, redirect them to the homepage.",
"else",
":",
"return",
"redirect",
"(",
"\"/\"",
")"
] | [
8,
0
] | [
29,
28
] | python | en | ['en', 'en', 'en'] | True |
connect | (dsn=None, connection_factory=None, cursor_factory=None, **kwargs) |
Create a new database connection.
The connection parameters can be specified as a string:
conn = psycopg2.connect("dbname=test user=postgres password=secret")
or using a set of keyword arguments:
conn = psycopg2.connect(database="test", user="postgres", password="secret")
Or as a mix of both. The basic connection parameters are:
- *dbname*: the database name
- *database*: the database name (only as keyword argument)
- *user*: user name used to authenticate
- *password*: password used to authenticate
- *host*: database host address (defaults to UNIX socket if not provided)
- *port*: connection port number (defaults to 5432 if not provided)
Using the *connection_factory* parameter a different class or connections
factory can be specified. It should be a callable object taking a dsn
argument.
Using the *cursor_factory* parameter, a new default cursor factory will be
used by cursor().
Using *async*=True an asynchronous connection will be created. *async_* is
a valid alias (for Python versions where ``async`` is a keyword).
Any other keyword parameter will be passed to the underlying client
library: the list of supported parameters depends on the library version.
|
Create a new database connection. | def connect(dsn=None, connection_factory=None, cursor_factory=None, **kwargs):
"""
Create a new database connection.
The connection parameters can be specified as a string:
conn = psycopg2.connect("dbname=test user=postgres password=secret")
or using a set of keyword arguments:
conn = psycopg2.connect(database="test", user="postgres", password="secret")
Or as a mix of both. The basic connection parameters are:
- *dbname*: the database name
- *database*: the database name (only as keyword argument)
- *user*: user name used to authenticate
- *password*: password used to authenticate
- *host*: database host address (defaults to UNIX socket if not provided)
- *port*: connection port number (defaults to 5432 if not provided)
Using the *connection_factory* parameter a different class or connections
factory can be specified. It should be a callable object taking a dsn
argument.
Using the *cursor_factory* parameter, a new default cursor factory will be
used by cursor().
Using *async*=True an asynchronous connection will be created. *async_* is
a valid alias (for Python versions where ``async`` is a keyword).
Any other keyword parameter will be passed to the underlying client
library: the list of supported parameters depends on the library version.
"""
kwasync = {}
if 'async' in kwargs:
kwasync['async'] = kwargs.pop('async')
if 'async_' in kwargs:
kwasync['async_'] = kwargs.pop('async_')
dsn = _ext.make_dsn(dsn, **kwargs)
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
if cursor_factory is not None:
conn.cursor_factory = cursor_factory
return conn | [
"def",
"connect",
"(",
"dsn",
"=",
"None",
",",
"connection_factory",
"=",
"None",
",",
"cursor_factory",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwasync",
"=",
"{",
"}",
"if",
"'async'",
"in",
"kwargs",
":",
"kwasync",
"[",
"'async'",
"]",
"=",
"kwargs",
".",
"pop",
"(",
"'async'",
")",
"if",
"'async_'",
"in",
"kwargs",
":",
"kwasync",
"[",
"'async_'",
"]",
"=",
"kwargs",
".",
"pop",
"(",
"'async_'",
")",
"dsn",
"=",
"_ext",
".",
"make_dsn",
"(",
"dsn",
",",
"*",
"*",
"kwargs",
")",
"conn",
"=",
"_connect",
"(",
"dsn",
",",
"connection_factory",
"=",
"connection_factory",
",",
"*",
"*",
"kwasync",
")",
"if",
"cursor_factory",
"is",
"not",
"None",
":",
"conn",
".",
"cursor_factory",
"=",
"cursor_factory",
"return",
"conn"
] | [
79,
0
] | [
125,
15
] | python | en | ['en', 'error', 'th'] | False |
Highchart.__init__ | (self, **kwargs) |
This is the base class for all the charts. The following keywords are
accepted:
:keyword: **display_container** - default: ``True``
**offline - default: ``False``
If True, download all .js and .css file and put them
into the generated .html so it can be viewed offline.
|
This is the base class for all the charts. The following keywords are
accepted:
:keyword: **display_container** - default: ``True``
**offline - default: ``False``
If True, download all .js and .css file and put them
into the generated .html so it can be viewed offline.
| def __init__(self, **kwargs):
"""
This is the base class for all the charts. The following keywords are
accepted:
:keyword: **display_container** - default: ``True``
**offline - default: ``False``
If True, download all .js and .css file and put them
into the generated .html so it can be viewed offline.
"""
# set the model
self.model = self.__class__.__name__ #: The chart model,
self.div_name = kwargs.get("renderTo", "container")
# an Instance of Jinja2 template
self.template_page_highcharts = template_page
self.template_content_highcharts = template_content
# set Javascript src, Highcharts lib needs to make sure it's up to date
self.JSsource = [
'https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js',
'https://code.highcharts.com/6/highcharts.js',
'https://code.highcharts.com/6/highcharts-more.js',
'https://code.highcharts.com/6/modules/heatmap.js',
'https://code.highcharts.com/6/modules/exporting.js'
]
# set CSS src
self.CSSsource = [
'https://www.highcharts.com/highslide/highslide.css',
]
self.offline = kwargs.get("offline", False)
# set data
self.data = []
self.data_temp = []
# Data from jsonp
self.jsonp_data_flag = False
self.jsonp_data_url_list = [] # DEM 2017/07/27: List of JSON data sources
# set drilldown data
self.drilldown_data = []
self.drilldown_data_temp = []
# javascript
self.jscript_head_flag = False
self.jscript_head = kwargs.get('jscript_head', None)
self.jscript_end_flag = False
self.jscript_end = kwargs.get('jscript_end', None)
# accepted keywords
self.div_style = kwargs.get('style', '')
self.drilldown_flag = kwargs.get('drilldown_flag', False)
# None keywords attribute that should be modified by methods
# We should change all these to _attr
self._htmlcontent = '' #: written by buildhtml
self.htmlheader = ''
#: Place holder for the graph (the HTML div)
#: Written by ``buildcontainer``
self.container = u''
#: Header for javascript code
self.containerheader = u''
# Loading message
self.loading = 'Loading....'
# Bind Base Classes to self
self.options = {
"chart": ChartOptions(),
#"colorAxis" : ColorAxisOptions(),
"colors": ColorsOptions(),
"credits": CreditsOptions(),
#"data": #NotImplemented
"drilldown": DrilldownOptions(),
"exporting": ExportingOptions(),
"labels": LabelsOptions(),
"legend": LegendOptions(),
"loading": LoadingOptions(),
"navigation": NavigationOptions(),
"pane": PaneOptions(),
"plotOptions": PlotOptions(),
"series": SeriesData(),
"subtitle": SubtitleOptions(),
"title": TitleOptions(),
"tooltip": TooltipOptions(),
"xAxis": xAxisOptions(),
"yAxis": yAxisOptions(),
}
self.setOptions = {
"global": GlobalOptions(),
"lang": LangOptions(),
}
self.__load_defaults__()
# Process kwargs
allowed_kwargs = [
"width",
"height",
"renderTo",
"backgroundColor",
"events",
"marginBottom",
"marginTop",
"marginRight",
"marginLeft"
]
for keyword in allowed_kwargs:
if keyword in kwargs:
self.options['chart'].update_dict(**{keyword:kwargs[keyword]})
# Some Extra Vals to store:
self.data_set_count = 0
self.drilldown_data_set_count = 0 | [
"def",
"__init__",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# set the model",
"self",
".",
"model",
"=",
"self",
".",
"__class__",
".",
"__name__",
"#: The chart model,",
"self",
".",
"div_name",
"=",
"kwargs",
".",
"get",
"(",
"\"renderTo\"",
",",
"\"container\"",
")",
"# an Instance of Jinja2 template",
"self",
".",
"template_page_highcharts",
"=",
"template_page",
"self",
".",
"template_content_highcharts",
"=",
"template_content",
"# set Javascript src, Highcharts lib needs to make sure it's up to date",
"self",
".",
"JSsource",
"=",
"[",
"'https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'",
",",
"'https://code.highcharts.com/6/highcharts.js'",
",",
"'https://code.highcharts.com/6/highcharts-more.js'",
",",
"'https://code.highcharts.com/6/modules/heatmap.js'",
",",
"'https://code.highcharts.com/6/modules/exporting.js'",
"]",
"# set CSS src",
"self",
".",
"CSSsource",
"=",
"[",
"'https://www.highcharts.com/highslide/highslide.css'",
",",
"]",
"self",
".",
"offline",
"=",
"kwargs",
".",
"get",
"(",
"\"offline\"",
",",
"False",
")",
"# set data",
"self",
".",
"data",
"=",
"[",
"]",
"self",
".",
"data_temp",
"=",
"[",
"]",
"# Data from jsonp",
"self",
".",
"jsonp_data_flag",
"=",
"False",
"self",
".",
"jsonp_data_url_list",
"=",
"[",
"]",
"# DEM 2017/07/27: List of JSON data sources",
"# set drilldown data",
"self",
".",
"drilldown_data",
"=",
"[",
"]",
"self",
".",
"drilldown_data_temp",
"=",
"[",
"]",
"# javascript",
"self",
".",
"jscript_head_flag",
"=",
"False",
"self",
".",
"jscript_head",
"=",
"kwargs",
".",
"get",
"(",
"'jscript_head'",
",",
"None",
")",
"self",
".",
"jscript_end_flag",
"=",
"False",
"self",
".",
"jscript_end",
"=",
"kwargs",
".",
"get",
"(",
"'jscript_end'",
",",
"None",
")",
"# accepted keywords",
"self",
".",
"div_style",
"=",
"kwargs",
".",
"get",
"(",
"'style'",
",",
"''",
")",
"self",
".",
"drilldown_flag",
"=",
"kwargs",
".",
"get",
"(",
"'drilldown_flag'",
",",
"False",
")",
"# None keywords attribute that should be modified by methods",
"# We should change all these to _attr",
"self",
".",
"_htmlcontent",
"=",
"''",
"#: written by buildhtml",
"self",
".",
"htmlheader",
"=",
"''",
"#: Place holder for the graph (the HTML div)",
"#: Written by ``buildcontainer``",
"self",
".",
"container",
"=",
"u''",
"#: Header for javascript code",
"self",
".",
"containerheader",
"=",
"u''",
"# Loading message",
"self",
".",
"loading",
"=",
"'Loading....'",
"# Bind Base Classes to self",
"self",
".",
"options",
"=",
"{",
"\"chart\"",
":",
"ChartOptions",
"(",
")",
",",
"#\"colorAxis\" : ColorAxisOptions(),",
"\"colors\"",
":",
"ColorsOptions",
"(",
")",
",",
"\"credits\"",
":",
"CreditsOptions",
"(",
")",
",",
"#\"data\": #NotImplemented",
"\"drilldown\"",
":",
"DrilldownOptions",
"(",
")",
",",
"\"exporting\"",
":",
"ExportingOptions",
"(",
")",
",",
"\"labels\"",
":",
"LabelsOptions",
"(",
")",
",",
"\"legend\"",
":",
"LegendOptions",
"(",
")",
",",
"\"loading\"",
":",
"LoadingOptions",
"(",
")",
",",
"\"navigation\"",
":",
"NavigationOptions",
"(",
")",
",",
"\"pane\"",
":",
"PaneOptions",
"(",
")",
",",
"\"plotOptions\"",
":",
"PlotOptions",
"(",
")",
",",
"\"series\"",
":",
"SeriesData",
"(",
")",
",",
"\"subtitle\"",
":",
"SubtitleOptions",
"(",
")",
",",
"\"title\"",
":",
"TitleOptions",
"(",
")",
",",
"\"tooltip\"",
":",
"TooltipOptions",
"(",
")",
",",
"\"xAxis\"",
":",
"xAxisOptions",
"(",
")",
",",
"\"yAxis\"",
":",
"yAxisOptions",
"(",
")",
",",
"}",
"self",
".",
"setOptions",
"=",
"{",
"\"global\"",
":",
"GlobalOptions",
"(",
")",
",",
"\"lang\"",
":",
"LangOptions",
"(",
")",
",",
"}",
"self",
".",
"__load_defaults__",
"(",
")",
"# Process kwargs",
"allowed_kwargs",
"=",
"[",
"\"width\"",
",",
"\"height\"",
",",
"\"renderTo\"",
",",
"\"backgroundColor\"",
",",
"\"events\"",
",",
"\"marginBottom\"",
",",
"\"marginTop\"",
",",
"\"marginRight\"",
",",
"\"marginLeft\"",
"]",
"for",
"keyword",
"in",
"allowed_kwargs",
":",
"if",
"keyword",
"in",
"kwargs",
":",
"self",
".",
"options",
"[",
"'chart'",
"]",
".",
"update_dict",
"(",
"*",
"*",
"{",
"keyword",
":",
"kwargs",
"[",
"keyword",
"]",
"}",
")",
"# Some Extra Vals to store:",
"self",
".",
"data_set_count",
"=",
"0",
"self",
".",
"drilldown_data_set_count",
"=",
"0"
] | [
49,
4
] | [
166,
41
] | python | en | ['en', 'error', 'th'] | False |
Highchart.add_JSsource | (self, new_src) | add additional js script source(s) | add additional js script source(s) | def add_JSsource(self, new_src):
"""add additional js script source(s)"""
if isinstance(new_src, list):
for h in new_src:
self.JSsource.append(h)
elif isinstance(new_src, basestring):
self.JSsource.append(new_src)
else:
raise OptionTypeError("Option: %s Not Allowed For Series Type: %s" % type(new_src)) | [
"def",
"add_JSsource",
"(",
"self",
",",
"new_src",
")",
":",
"if",
"isinstance",
"(",
"new_src",
",",
"list",
")",
":",
"for",
"h",
"in",
"new_src",
":",
"self",
".",
"JSsource",
".",
"append",
"(",
"h",
")",
"elif",
"isinstance",
"(",
"new_src",
",",
"basestring",
")",
":",
"self",
".",
"JSsource",
".",
"append",
"(",
"new_src",
")",
"else",
":",
"raise",
"OptionTypeError",
"(",
"\"Option: %s Not Allowed For Series Type: %s\"",
"%",
"type",
"(",
"new_src",
")",
")"
] | [
175,
4
] | [
183,
95
] | python | en | ['en', 'co', 'en'] | True |
Highchart.add_CSSsource | (self, new_src) | add additional css source(s) | add additional css source(s) | def add_CSSsource(self, new_src):
"""add additional css source(s)"""
if isinstance(new_src, list):
for h in new_src:
self.CSSsource.append(h)
elif isinstance(new_src, basestring):
self.CSSsource.append(new_src)
else:
raise OptionTypeError("Option: %s Not Allowed For Series Type: %s" % type(new_src)) | [
"def",
"add_CSSsource",
"(",
"self",
",",
"new_src",
")",
":",
"if",
"isinstance",
"(",
"new_src",
",",
"list",
")",
":",
"for",
"h",
"in",
"new_src",
":",
"self",
".",
"CSSsource",
".",
"append",
"(",
"h",
")",
"elif",
"isinstance",
"(",
"new_src",
",",
"basestring",
")",
":",
"self",
".",
"CSSsource",
".",
"append",
"(",
"new_src",
")",
"else",
":",
"raise",
"OptionTypeError",
"(",
"\"Option: %s Not Allowed For Series Type: %s\"",
"%",
"type",
"(",
"new_src",
")",
")"
] | [
186,
4
] | [
194,
95
] | python | en | ['en', 'en', 'en'] | True |
Highchart.add_data_set | (self, data, series_type="line", name=None, **kwargs) | set data for series option in highcharts | set data for series option in highcharts | def add_data_set(self, data, series_type="line", name=None, **kwargs):
"""set data for series option in highcharts"""
self.data_set_count += 1
if not name:
name = "Series %d" % self.data_set_count
kwargs.update({'name':name})
if series_type == 'treemap':
self.add_JSsource('http://code.highcharts.com/modules/treemap.js')
series_data = Series(data, series_type=series_type, **kwargs)
series_data.__options__().update(SeriesOptions(series_type=series_type, **kwargs).__options__())
self.data_temp.append(series_data) | [
"def",
"add_data_set",
"(",
"self",
",",
"data",
",",
"series_type",
"=",
"\"line\"",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"data_set_count",
"+=",
"1",
"if",
"not",
"name",
":",
"name",
"=",
"\"Series %d\"",
"%",
"self",
".",
"data_set_count",
"kwargs",
".",
"update",
"(",
"{",
"'name'",
":",
"name",
"}",
")",
"if",
"series_type",
"==",
"'treemap'",
":",
"self",
".",
"add_JSsource",
"(",
"'http://code.highcharts.com/modules/treemap.js'",
")",
"series_data",
"=",
"Series",
"(",
"data",
",",
"series_type",
"=",
"series_type",
",",
"*",
"*",
"kwargs",
")",
"series_data",
".",
"__options__",
"(",
")",
".",
"update",
"(",
"SeriesOptions",
"(",
"series_type",
"=",
"series_type",
",",
"*",
"*",
"kwargs",
")",
".",
"__options__",
"(",
")",
")",
"self",
".",
"data_temp",
".",
"append",
"(",
"series_data",
")"
] | [
200,
4
] | [
214,
42
] | python | en | ['en', 'en', 'en'] | True |
Highchart.add_drilldown_data_set | (self, data, series_type, id, **kwargs) | set data for drilldown option in highcharts | set data for drilldown option in highcharts | def add_drilldown_data_set(self, data, series_type, id, **kwargs):
"""set data for drilldown option in highcharts"""
self.drilldown_data_set_count += 1
if self.drilldown_flag == False:
self.drilldown_flag = True
kwargs.update({'id':id})
series_data = Series(data, series_type=series_type, **kwargs)
series_data.__options__().update(SeriesOptions(series_type=series_type, **kwargs).__options__())
self.drilldown_data_temp.append(series_data) | [
"def",
"add_drilldown_data_set",
"(",
"self",
",",
"data",
",",
"series_type",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"drilldown_data_set_count",
"+=",
"1",
"if",
"self",
".",
"drilldown_flag",
"==",
"False",
":",
"self",
".",
"drilldown_flag",
"=",
"True",
"kwargs",
".",
"update",
"(",
"{",
"'id'",
":",
"id",
"}",
")",
"series_data",
"=",
"Series",
"(",
"data",
",",
"series_type",
"=",
"series_type",
",",
"*",
"*",
"kwargs",
")",
"series_data",
".",
"__options__",
"(",
")",
".",
"update",
"(",
"SeriesOptions",
"(",
"series_type",
"=",
"series_type",
",",
"*",
"*",
"kwargs",
")",
".",
"__options__",
"(",
")",
")",
"self",
".",
"drilldown_data_temp",
".",
"append",
"(",
"series_data",
")"
] | [
217,
4
] | [
228,
52
] | python | en | ['en', 'en', 'en'] | True |
Highchart.add_data_from_jsonp | (self, data_src, data_name='json_data', series_type="line", name=None, **kwargs) | set map data directly from a https source
the data_src is the https link for data
and it must be in jsonp format
| set map data directly from a https source
the data_src is the https link for data
and it must be in jsonp format
| def add_data_from_jsonp(self, data_src, data_name='json_data', series_type="line", name=None, **kwargs):
"""set map data directly from a https source
the data_src is the https link for data
and it must be in jsonp format
"""
if not self.jsonp_data_flag:
self.jsonp_data_flag = True
if data_name == 'data':
data_name = 'json_'+ data_name
self.jsonp_data = data_name
self.add_data_set(RawJavaScriptText(data_name), series_type, name=name, **kwargs)
# DEM 2017/07/27: Append new JSON data source to a list instead of
# replacing whatever already exists
self.jsonp_data_url_list.append(json.dumps(data_src)) | [
"def",
"add_data_from_jsonp",
"(",
"self",
",",
"data_src",
",",
"data_name",
"=",
"'json_data'",
",",
"series_type",
"=",
"\"line\"",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"jsonp_data_flag",
":",
"self",
".",
"jsonp_data_flag",
"=",
"True",
"if",
"data_name",
"==",
"'data'",
":",
"data_name",
"=",
"'json_'",
"+",
"data_name",
"self",
".",
"jsonp_data",
"=",
"data_name",
"self",
".",
"add_data_set",
"(",
"RawJavaScriptText",
"(",
"data_name",
")",
",",
"series_type",
",",
"name",
"=",
"name",
",",
"*",
"*",
"kwargs",
")",
"# DEM 2017/07/27: Append new JSON data source to a list instead of",
"# replacing whatever already exists",
"self",
".",
"jsonp_data_url_list",
".",
"append",
"(",
"json",
".",
"dumps",
"(",
"data_src",
")",
")"
] | [
231,
4
] | [
246,
61
] | python | en | ['en', 'en', 'en'] | True |
Highchart.add_JSscript | (self, js_script, js_loc) | add (highcharts) javascript in the beginning or at the end of script
use only if necessary
| add (highcharts) javascript in the beginning or at the end of script
use only if necessary
| def add_JSscript(self, js_script, js_loc):
"""add (highcharts) javascript in the beginning or at the end of script
use only if necessary
"""
if js_loc == 'head':
self.jscript_head_flag = True
if self.jscript_head:
self.jscript_head = self.jscript_head + '\n' + js_script
else:
self.jscript_head = js_script
elif js_loc == 'end':
self.jscript_end_flag = True
if self.jscript_end:
self.jscript_end = self.jscript_end + '\n' + js_script
else:
self.jscript_end = js_script
else:
raise OptionTypeError("Not An Accepted script location: %s, either 'head' or 'end'"
% js_loc) | [
"def",
"add_JSscript",
"(",
"self",
",",
"js_script",
",",
"js_loc",
")",
":",
"if",
"js_loc",
"==",
"'head'",
":",
"self",
".",
"jscript_head_flag",
"=",
"True",
"if",
"self",
".",
"jscript_head",
":",
"self",
".",
"jscript_head",
"=",
"self",
".",
"jscript_head",
"+",
"'\\n'",
"+",
"js_script",
"else",
":",
"self",
".",
"jscript_head",
"=",
"js_script",
"elif",
"js_loc",
"==",
"'end'",
":",
"self",
".",
"jscript_end_flag",
"=",
"True",
"if",
"self",
".",
"jscript_end",
":",
"self",
".",
"jscript_end",
"=",
"self",
".",
"jscript_end",
"+",
"'\\n'",
"+",
"js_script",
"else",
":",
"self",
".",
"jscript_end",
"=",
"js_script",
"else",
":",
"raise",
"OptionTypeError",
"(",
"\"Not An Accepted script location: %s, either 'head' or 'end'\"",
"%",
"js_loc",
")"
] | [
249,
4
] | [
267,
41
] | python | en | ['en', 'en', 'en'] | True |
Highchart.set_options | (self, option_type, option_dict, force_options=False) | set plot options | set plot options | def set_options(self, option_type, option_dict, force_options=False):
"""set plot options """
if force_options:
self.options[option_type].update(option_dict)
elif (option_type == 'yAxis' or option_type == 'xAxis') and isinstance(option_dict, list):
# For multi-Axis
self.options[option_type] = MultiAxis(option_type)
for each_dict in option_dict:
self.options[option_type].update(**each_dict)
elif option_type == 'colors':
self.options["colors"].set_colors(option_dict) # option_dict should be a list
elif option_type == 'zAxis':
self.options.update({'zAxis': zAxisOptions()})
self.options[option_type].update_dict(**option_dict)
elif option_type in ["global" , "lang"]: #Highcharts.setOptions:
self.setOptions[option_type].update_dict(**option_dict)
elif option_type == 'colorAxis':
self.options.update({'colorAxis': ColorAxisOptions()})
self.options[option_type].update_dict(**option_dict)
else:
self.options[option_type].update_dict(**option_dict)
if option_type == 'chart' and 'options3d' in option_dict:
# Add 3d.js into Javascript source header
self.add_JSsource("http://code.highcharts.com/highcharts-3d.js") | [
"def",
"set_options",
"(",
"self",
",",
"option_type",
",",
"option_dict",
",",
"force_options",
"=",
"False",
")",
":",
"if",
"force_options",
":",
"self",
".",
"options",
"[",
"option_type",
"]",
".",
"update",
"(",
"option_dict",
")",
"elif",
"(",
"option_type",
"==",
"'yAxis'",
"or",
"option_type",
"==",
"'xAxis'",
")",
"and",
"isinstance",
"(",
"option_dict",
",",
"list",
")",
":",
"# For multi-Axis",
"self",
".",
"options",
"[",
"option_type",
"]",
"=",
"MultiAxis",
"(",
"option_type",
")",
"for",
"each_dict",
"in",
"option_dict",
":",
"self",
".",
"options",
"[",
"option_type",
"]",
".",
"update",
"(",
"*",
"*",
"each_dict",
")",
"elif",
"option_type",
"==",
"'colors'",
":",
"self",
".",
"options",
"[",
"\"colors\"",
"]",
".",
"set_colors",
"(",
"option_dict",
")",
"# option_dict should be a list",
"elif",
"option_type",
"==",
"'zAxis'",
":",
"self",
".",
"options",
".",
"update",
"(",
"{",
"'zAxis'",
":",
"zAxisOptions",
"(",
")",
"}",
")",
"self",
".",
"options",
"[",
"option_type",
"]",
".",
"update_dict",
"(",
"*",
"*",
"option_dict",
")",
"elif",
"option_type",
"in",
"[",
"\"global\"",
",",
"\"lang\"",
"]",
":",
"#Highcharts.setOptions: ",
"self",
".",
"setOptions",
"[",
"option_type",
"]",
".",
"update_dict",
"(",
"*",
"*",
"option_dict",
")",
"elif",
"option_type",
"==",
"'colorAxis'",
":",
"self",
".",
"options",
".",
"update",
"(",
"{",
"'colorAxis'",
":",
"ColorAxisOptions",
"(",
")",
"}",
")",
"self",
".",
"options",
"[",
"option_type",
"]",
".",
"update_dict",
"(",
"*",
"*",
"option_dict",
")",
"else",
":",
"self",
".",
"options",
"[",
"option_type",
"]",
".",
"update_dict",
"(",
"*",
"*",
"option_dict",
")",
"if",
"option_type",
"==",
"'chart'",
"and",
"'options3d'",
"in",
"option_dict",
":",
"# Add 3d.js into Javascript source header",
"self",
".",
"add_JSsource",
"(",
"\"http://code.highcharts.com/highcharts-3d.js\"",
")"
] | [
270,
4
] | [
294,
76
] | python | en | ['en', 'bg', 'en'] | True |
Highchart.set_dict_options | (self, options) | for dictionary-like inputs (as object in Javascript)
options must be in python dictionary format
| for dictionary-like inputs (as object in Javascript)
options must be in python dictionary format
| def set_dict_options(self, options):
"""for dictionary-like inputs (as object in Javascript)
options must be in python dictionary format
"""
if isinstance(options, dict):
for key, option_data in options.items():
self.set_options(key, option_data)
else:
raise OptionTypeError("Not An Accepted Input Format: %s. Must be Dictionary" %type(options)) | [
"def",
"set_dict_options",
"(",
"self",
",",
"options",
")",
":",
"if",
"isinstance",
"(",
"options",
",",
"dict",
")",
":",
"for",
"key",
",",
"option_data",
"in",
"options",
".",
"items",
"(",
")",
":",
"self",
".",
"set_options",
"(",
"key",
",",
"option_data",
")",
"else",
":",
"raise",
"OptionTypeError",
"(",
"\"Not An Accepted Input Format: %s. Must be Dictionary\"",
"%",
"type",
"(",
"options",
")",
")"
] | [
297,
4
] | [
305,
104
] | python | en | ['en', 'en', 'en'] | True |
Highchart.buildcontent | (self) | build HTML content only, no header or body tags | build HTML content only, no header or body tags | def buildcontent(self):
"""build HTML content only, no header or body tags"""
self.buildcontainer()
self.option = json.dumps(self.options, cls = HighchartsEncoder)
self.setoption = json.dumps(self.setOptions, cls = HighchartsEncoder)
self.data = json.dumps(self.data_temp, cls = HighchartsEncoder)
# DEM 2017/04/25: Make 'data' available as an array
# ... this permits jinja2 array access to each data definition
# ... which is useful for looping over multiple data sources
self.data_list = [json.dumps(x, cls = HighchartsEncoder) for x in self.data_temp]
if self.drilldown_flag:
self.drilldown_data = json.dumps(self.drilldown_data_temp, cls = HighchartsEncoder)
self._htmlcontent = self.template_content_highcharts.render(chart=self).encode('utf-8') | [
"def",
"buildcontent",
"(",
"self",
")",
":",
"self",
".",
"buildcontainer",
"(",
")",
"self",
".",
"option",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"options",
",",
"cls",
"=",
"HighchartsEncoder",
")",
"self",
".",
"setoption",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"setOptions",
",",
"cls",
"=",
"HighchartsEncoder",
")",
"self",
".",
"data",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"data_temp",
",",
"cls",
"=",
"HighchartsEncoder",
")",
"# DEM 2017/04/25: Make 'data' available as an array",
"# ... this permits jinja2 array access to each data definition",
"# ... which is useful for looping over multiple data sources",
"self",
".",
"data_list",
"=",
"[",
"json",
".",
"dumps",
"(",
"x",
",",
"cls",
"=",
"HighchartsEncoder",
")",
"for",
"x",
"in",
"self",
".",
"data_temp",
"]",
"if",
"self",
".",
"drilldown_flag",
":",
"self",
".",
"drilldown_data",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"drilldown_data_temp",
",",
"cls",
"=",
"HighchartsEncoder",
")",
"self",
".",
"_htmlcontent",
"=",
"self",
".",
"template_content_highcharts",
".",
"render",
"(",
"chart",
"=",
"self",
")",
".",
"encode",
"(",
"'utf-8'",
")"
] | [
308,
4
] | [
323,
95
] | python | en | ['en', 'en', 'en'] | True |
Highchart.buildhtml | (self) | build the HTML page
create the htmlheader with css / js
create html page
| build the HTML page
create the htmlheader with css / js
create html page
| def buildhtml(self):
"""build the HTML page
create the htmlheader with css / js
create html page
"""
self.buildcontent()
self.buildhtmlheader()
self.content = self._htmlcontent.decode('utf-8') # need to ensure unicode
self._htmlcontent = self.template_page_highcharts.render(chart=self)
return self._htmlcontent | [
"def",
"buildhtml",
"(",
"self",
")",
":",
"self",
".",
"buildcontent",
"(",
")",
"self",
".",
"buildhtmlheader",
"(",
")",
"self",
".",
"content",
"=",
"self",
".",
"_htmlcontent",
".",
"decode",
"(",
"'utf-8'",
")",
"# need to ensure unicode",
"self",
".",
"_htmlcontent",
"=",
"self",
".",
"template_page_highcharts",
".",
"render",
"(",
"chart",
"=",
"self",
")",
"return",
"self",
".",
"_htmlcontent"
] | [
326,
4
] | [
335,
32
] | python | en | ['en', 'en', 'en'] | True |
Highchart.buildhtmlheader | (self) | generate HTML header content | generate HTML header content | def buildhtmlheader(self):
"""generate HTML header content"""
if self.drilldown_flag:
self.add_JSsource('http://code.highcharts.com/modules/drilldown.js')
if self.offline:
opener = urllib.request.build_opener()
opener.addheaders = [('User-Agent', 'Mozilla/5.0')]
self.header_css = [
'<style>%s</style>' % opener.open(h).read() for h in self.CSSsource
]
self.header_js = [
'<script type="text/javascript">%s</script>' % opener.open(h).read() for h in self.JSsource
]
else:
self.header_css = [
'<link href="%s" rel="stylesheet" />' % h for h in self.CSSsource
]
self.header_js = [
'<script type="text/javascript" src="%s"></script>' % h for h in self.JSsource
]
self.htmlheader = ''
for css in self.header_css:
self.htmlheader += css
for js in self.header_js:
self.htmlheader += js | [
"def",
"buildhtmlheader",
"(",
"self",
")",
":",
"if",
"self",
".",
"drilldown_flag",
":",
"self",
".",
"add_JSsource",
"(",
"'http://code.highcharts.com/modules/drilldown.js'",
")",
"if",
"self",
".",
"offline",
":",
"opener",
"=",
"urllib",
".",
"request",
".",
"build_opener",
"(",
")",
"opener",
".",
"addheaders",
"=",
"[",
"(",
"'User-Agent'",
",",
"'Mozilla/5.0'",
")",
"]",
"self",
".",
"header_css",
"=",
"[",
"'<style>%s</style>'",
"%",
"opener",
".",
"open",
"(",
"h",
")",
".",
"read",
"(",
")",
"for",
"h",
"in",
"self",
".",
"CSSsource",
"]",
"self",
".",
"header_js",
"=",
"[",
"'<script type=\"text/javascript\">%s</script>'",
"%",
"opener",
".",
"open",
"(",
"h",
")",
".",
"read",
"(",
")",
"for",
"h",
"in",
"self",
".",
"JSsource",
"]",
"else",
":",
"self",
".",
"header_css",
"=",
"[",
"'<link href=\"%s\" rel=\"stylesheet\" />'",
"%",
"h",
"for",
"h",
"in",
"self",
".",
"CSSsource",
"]",
"self",
".",
"header_js",
"=",
"[",
"'<script type=\"text/javascript\" src=\"%s\"></script>'",
"%",
"h",
"for",
"h",
"in",
"self",
".",
"JSsource",
"]",
"self",
".",
"htmlheader",
"=",
"''",
"for",
"css",
"in",
"self",
".",
"header_css",
":",
"self",
".",
"htmlheader",
"+=",
"css",
"for",
"js",
"in",
"self",
".",
"header_js",
":",
"self",
".",
"htmlheader",
"+=",
"js"
] | [
338,
4
] | [
370,
33
] | python | en | ['en', 'en', 'en'] | True |
Highchart.buildcontainer | (self) | generate HTML div | generate HTML div | def buildcontainer(self):
"""generate HTML div"""
if self.container:
return
# Create HTML div with style
if self.options['chart'].width:
if str(self.options['chart'].width)[-1] != '%':
self.div_style += 'width:%spx;' % self.options['chart'].width
else:
self.div_style += 'width:%s;' % self.options['chart'].width
if self.options['chart'].height:
if str(self.options['chart'].height)[-1] != '%':
self.div_style += 'height:%spx;' % self.options['chart'].height
else:
self.div_style += 'height:%s;' % self.options['chart'].height
self.div_name = self.options['chart'].__dict__['renderTo'] # recheck div name
self.container = self.containerheader + \
'<div id="%s" style="%s">%s</div>\n' % (self.div_name, self.div_style, self.loading) | [
"def",
"buildcontainer",
"(",
"self",
")",
":",
"if",
"self",
".",
"container",
":",
"return",
"# Create HTML div with style",
"if",
"self",
".",
"options",
"[",
"'chart'",
"]",
".",
"width",
":",
"if",
"str",
"(",
"self",
".",
"options",
"[",
"'chart'",
"]",
".",
"width",
")",
"[",
"-",
"1",
"]",
"!=",
"'%'",
":",
"self",
".",
"div_style",
"+=",
"'width:%spx;'",
"%",
"self",
".",
"options",
"[",
"'chart'",
"]",
".",
"width",
"else",
":",
"self",
".",
"div_style",
"+=",
"'width:%s;'",
"%",
"self",
".",
"options",
"[",
"'chart'",
"]",
".",
"width",
"if",
"self",
".",
"options",
"[",
"'chart'",
"]",
".",
"height",
":",
"if",
"str",
"(",
"self",
".",
"options",
"[",
"'chart'",
"]",
".",
"height",
")",
"[",
"-",
"1",
"]",
"!=",
"'%'",
":",
"self",
".",
"div_style",
"+=",
"'height:%spx;'",
"%",
"self",
".",
"options",
"[",
"'chart'",
"]",
".",
"height",
"else",
":",
"self",
".",
"div_style",
"+=",
"'height:%s;'",
"%",
"self",
".",
"options",
"[",
"'chart'",
"]",
".",
"height",
"self",
".",
"div_name",
"=",
"self",
".",
"options",
"[",
"'chart'",
"]",
".",
"__dict__",
"[",
"'renderTo'",
"]",
"# recheck div name",
"self",
".",
"container",
"=",
"self",
".",
"containerheader",
"+",
"'<div id=\"%s\" style=\"%s\">%s</div>\\n'",
"%",
"(",
"self",
".",
"div_name",
",",
"self",
".",
"div_style",
",",
"self",
".",
"loading",
")"
] | [
373,
4
] | [
391,
96
] | python | en | ['en', 'en', 'en'] | True |
Highchart.__str__ | (self) | return htmlcontent | return htmlcontent | def __str__(self):
"""return htmlcontent"""
#self.buildhtml()
return self.htmlcontent | [
"def",
"__str__",
"(",
"self",
")",
":",
"#self.buildhtml()",
"return",
"self",
".",
"htmlcontent"
] | [
415,
4
] | [
418,
31
] | python | en | ['en', 'no', 'en'] | False |
Highchart.save_file | (self, filename = 'Chart') | save htmlcontent as .html file | save htmlcontent as .html file | def save_file(self, filename = 'Chart'):
""" save htmlcontent as .html file """
filename = filename + '.html'
with open(filename, 'w') as f:
#self.buildhtml()
f.write(self.htmlcontent)
f.closed | [
"def",
"save_file",
"(",
"self",
",",
"filename",
"=",
"'Chart'",
")",
":",
"filename",
"=",
"filename",
"+",
"'.html'",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"#self.buildhtml()",
"f",
".",
"write",
"(",
"self",
".",
"htmlcontent",
")",
"f",
".",
"closed"
] | [
420,
4
] | [
428,
16
] | python | en | ['en', 'en', 'en'] | True |
load_pyproject_toml | (
use_pep517, # type: Optional[bool]
pyproject_toml, # type: str
setup_py, # type: str
req_name # type: str
) | Load the pyproject.toml file.
Parameters:
use_pep517 - Has the user requested PEP 517 processing? None
means the user hasn't explicitly specified.
pyproject_toml - Location of the project's pyproject.toml file
setup_py - Location of the project's setup.py file
req_name - The name of the requirement we're processing (for
error reporting)
Returns:
None if we should use the legacy code path, otherwise a tuple
(
requirements from pyproject.toml,
name of PEP 517 backend,
requirements we should check are installed after setting
up the build environment
directory paths to import the backend from (backend-path),
relative to the project root.
)
| Load the pyproject.toml file. | def load_pyproject_toml(
use_pep517, # type: Optional[bool]
pyproject_toml, # type: str
setup_py, # type: str
req_name # type: str
):
# type: (...) -> Optional[BuildSystemDetails]
"""Load the pyproject.toml file.
Parameters:
use_pep517 - Has the user requested PEP 517 processing? None
means the user hasn't explicitly specified.
pyproject_toml - Location of the project's pyproject.toml file
setup_py - Location of the project's setup.py file
req_name - The name of the requirement we're processing (for
error reporting)
Returns:
None if we should use the legacy code path, otherwise a tuple
(
requirements from pyproject.toml,
name of PEP 517 backend,
requirements we should check are installed after setting
up the build environment
directory paths to import the backend from (backend-path),
relative to the project root.
)
"""
has_pyproject = os.path.isfile(pyproject_toml)
has_setup = os.path.isfile(setup_py)
if has_pyproject:
with open(pyproject_toml, encoding="utf-8") as f:
pp_toml = tomli.load(f)
build_system = pp_toml.get("build-system")
else:
build_system = None
# The following cases must use PEP 517
# We check for use_pep517 being non-None and falsey because that means
# the user explicitly requested --no-use-pep517. The value 0 as
# opposed to False can occur when the value is provided via an
# environment variable or config file option (due to the quirk of
# strtobool() returning an integer in pip's configuration code).
if has_pyproject and not has_setup:
if use_pep517 is not None and not use_pep517:
raise InstallationError(
"Disabling PEP 517 processing is invalid: "
"project does not have a setup.py"
)
use_pep517 = True
elif build_system and "build-backend" in build_system:
if use_pep517 is not None and not use_pep517:
raise InstallationError(
"Disabling PEP 517 processing is invalid: "
"project specifies a build backend of {} "
"in pyproject.toml".format(
build_system["build-backend"]
)
)
use_pep517 = True
# If we haven't worked out whether to use PEP 517 yet,
# and the user hasn't explicitly stated a preference,
# we do so if the project has a pyproject.toml file.
elif use_pep517 is None:
use_pep517 = has_pyproject
# At this point, we know whether we're going to use PEP 517.
assert use_pep517 is not None
# If we're using the legacy code path, there is nothing further
# for us to do here.
if not use_pep517:
return None
if build_system is None:
# Either the user has a pyproject.toml with no build-system
# section, or the user has no pyproject.toml, but has opted in
# explicitly via --use-pep517.
# In the absence of any explicit backend specification, we
# assume the setuptools backend that most closely emulates the
# traditional direct setup.py execution, and require wheel and
# a version of setuptools that supports that backend.
build_system = {
"requires": ["setuptools>=40.8.0", "wheel"],
"build-backend": "setuptools.build_meta:__legacy__",
}
# If we're using PEP 517, we have build system information (either
# from pyproject.toml, or defaulted by the code above).
# Note that at this point, we do not know if the user has actually
# specified a backend, though.
assert build_system is not None
# Ensure that the build-system section in pyproject.toml conforms
# to PEP 518.
error_template = (
"{package} has a pyproject.toml file that does not comply "
"with PEP 518: {reason}"
)
# Specifying the build-system table but not the requires key is invalid
if "requires" not in build_system:
raise InstallationError(
error_template.format(package=req_name, reason=(
"it has a 'build-system' table but not "
"'build-system.requires' which is mandatory in the table"
))
)
# Error out if requires is not a list of strings
requires = build_system["requires"]
if not _is_list_of_str(requires):
raise InstallationError(error_template.format(
package=req_name,
reason="'build-system.requires' is not a list of strings.",
))
# Each requirement must be valid as per PEP 508
for requirement in requires:
try:
Requirement(requirement)
except InvalidRequirement:
raise InstallationError(
error_template.format(
package=req_name,
reason=(
"'build-system.requires' contains an invalid "
"requirement: {!r}".format(requirement)
),
)
)
backend = build_system.get("build-backend")
backend_path = build_system.get("backend-path", [])
check = [] # type: List[str]
if backend is None:
# If the user didn't specify a backend, we assume they want to use
# the setuptools backend. But we can't be sure they have included
# a version of setuptools which supplies the backend, or wheel
# (which is needed by the backend) in their requirements. So we
# make a note to check that those requirements are present once
# we have set up the environment.
# This is quite a lot of work to check for a very specific case. But
# the problem is, that case is potentially quite common - projects that
# adopted PEP 518 early for the ability to specify requirements to
# execute setup.py, but never considered needing to mention the build
# tools themselves. The original PEP 518 code had a similar check (but
# implemented in a different way).
backend = "setuptools.build_meta:__legacy__"
check = ["setuptools>=40.8.0", "wheel"]
return BuildSystemDetails(requires, backend, check, backend_path) | [
"def",
"load_pyproject_toml",
"(",
"use_pep517",
",",
"# type: Optional[bool]",
"pyproject_toml",
",",
"# type: str",
"setup_py",
",",
"# type: str",
"req_name",
"# type: str",
")",
":",
"# type: (...) -> Optional[BuildSystemDetails]",
"has_pyproject",
"=",
"os",
".",
"path",
".",
"isfile",
"(",
"pyproject_toml",
")",
"has_setup",
"=",
"os",
".",
"path",
".",
"isfile",
"(",
"setup_py",
")",
"if",
"has_pyproject",
":",
"with",
"open",
"(",
"pyproject_toml",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"f",
":",
"pp_toml",
"=",
"tomli",
".",
"load",
"(",
"f",
")",
"build_system",
"=",
"pp_toml",
".",
"get",
"(",
"\"build-system\"",
")",
"else",
":",
"build_system",
"=",
"None",
"# The following cases must use PEP 517",
"# We check for use_pep517 being non-None and falsey because that means",
"# the user explicitly requested --no-use-pep517. The value 0 as",
"# opposed to False can occur when the value is provided via an",
"# environment variable or config file option (due to the quirk of",
"# strtobool() returning an integer in pip's configuration code).",
"if",
"has_pyproject",
"and",
"not",
"has_setup",
":",
"if",
"use_pep517",
"is",
"not",
"None",
"and",
"not",
"use_pep517",
":",
"raise",
"InstallationError",
"(",
"\"Disabling PEP 517 processing is invalid: \"",
"\"project does not have a setup.py\"",
")",
"use_pep517",
"=",
"True",
"elif",
"build_system",
"and",
"\"build-backend\"",
"in",
"build_system",
":",
"if",
"use_pep517",
"is",
"not",
"None",
"and",
"not",
"use_pep517",
":",
"raise",
"InstallationError",
"(",
"\"Disabling PEP 517 processing is invalid: \"",
"\"project specifies a build backend of {} \"",
"\"in pyproject.toml\"",
".",
"format",
"(",
"build_system",
"[",
"\"build-backend\"",
"]",
")",
")",
"use_pep517",
"=",
"True",
"# If we haven't worked out whether to use PEP 517 yet,",
"# and the user hasn't explicitly stated a preference,",
"# we do so if the project has a pyproject.toml file.",
"elif",
"use_pep517",
"is",
"None",
":",
"use_pep517",
"=",
"has_pyproject",
"# At this point, we know whether we're going to use PEP 517.",
"assert",
"use_pep517",
"is",
"not",
"None",
"# If we're using the legacy code path, there is nothing further",
"# for us to do here.",
"if",
"not",
"use_pep517",
":",
"return",
"None",
"if",
"build_system",
"is",
"None",
":",
"# Either the user has a pyproject.toml with no build-system",
"# section, or the user has no pyproject.toml, but has opted in",
"# explicitly via --use-pep517.",
"# In the absence of any explicit backend specification, we",
"# assume the setuptools backend that most closely emulates the",
"# traditional direct setup.py execution, and require wheel and",
"# a version of setuptools that supports that backend.",
"build_system",
"=",
"{",
"\"requires\"",
":",
"[",
"\"setuptools>=40.8.0\"",
",",
"\"wheel\"",
"]",
",",
"\"build-backend\"",
":",
"\"setuptools.build_meta:__legacy__\"",
",",
"}",
"# If we're using PEP 517, we have build system information (either",
"# from pyproject.toml, or defaulted by the code above).",
"# Note that at this point, we do not know if the user has actually",
"# specified a backend, though.",
"assert",
"build_system",
"is",
"not",
"None",
"# Ensure that the build-system section in pyproject.toml conforms",
"# to PEP 518.",
"error_template",
"=",
"(",
"\"{package} has a pyproject.toml file that does not comply \"",
"\"with PEP 518: {reason}\"",
")",
"# Specifying the build-system table but not the requires key is invalid",
"if",
"\"requires\"",
"not",
"in",
"build_system",
":",
"raise",
"InstallationError",
"(",
"error_template",
".",
"format",
"(",
"package",
"=",
"req_name",
",",
"reason",
"=",
"(",
"\"it has a 'build-system' table but not \"",
"\"'build-system.requires' which is mandatory in the table\"",
")",
")",
")",
"# Error out if requires is not a list of strings",
"requires",
"=",
"build_system",
"[",
"\"requires\"",
"]",
"if",
"not",
"_is_list_of_str",
"(",
"requires",
")",
":",
"raise",
"InstallationError",
"(",
"error_template",
".",
"format",
"(",
"package",
"=",
"req_name",
",",
"reason",
"=",
"\"'build-system.requires' is not a list of strings.\"",
",",
")",
")",
"# Each requirement must be valid as per PEP 508",
"for",
"requirement",
"in",
"requires",
":",
"try",
":",
"Requirement",
"(",
"requirement",
")",
"except",
"InvalidRequirement",
":",
"raise",
"InstallationError",
"(",
"error_template",
".",
"format",
"(",
"package",
"=",
"req_name",
",",
"reason",
"=",
"(",
"\"'build-system.requires' contains an invalid \"",
"\"requirement: {!r}\"",
".",
"format",
"(",
"requirement",
")",
")",
",",
")",
")",
"backend",
"=",
"build_system",
".",
"get",
"(",
"\"build-backend\"",
")",
"backend_path",
"=",
"build_system",
".",
"get",
"(",
"\"backend-path\"",
",",
"[",
"]",
")",
"check",
"=",
"[",
"]",
"# type: List[str]",
"if",
"backend",
"is",
"None",
":",
"# If the user didn't specify a backend, we assume they want to use",
"# the setuptools backend. But we can't be sure they have included",
"# a version of setuptools which supplies the backend, or wheel",
"# (which is needed by the backend) in their requirements. So we",
"# make a note to check that those requirements are present once",
"# we have set up the environment.",
"# This is quite a lot of work to check for a very specific case. But",
"# the problem is, that case is potentially quite common - projects that",
"# adopted PEP 518 early for the ability to specify requirements to",
"# execute setup.py, but never considered needing to mention the build",
"# tools themselves. The original PEP 518 code had a similar check (but",
"# implemented in a different way).",
"backend",
"=",
"\"setuptools.build_meta:__legacy__\"",
"check",
"=",
"[",
"\"setuptools>=40.8.0\"",
",",
"\"wheel\"",
"]",
"return",
"BuildSystemDetails",
"(",
"requires",
",",
"backend",
",",
"check",
",",
"backend_path",
")"
] | [
28,
0
] | [
182,
69
] | python | en | ['en', 'en', 'en'] | True |
receiver | (signal, **kwargs) |
A decorator for connecting receivers to signals. Used by passing in the
signal (or list of signals) and keyword arguments to connect::
@receiver(post_save, sender=MyModel)
def signal_receiver(sender, **kwargs):
...
@receiver([post_save, post_delete], sender=MyModel)
def signals_receiver(sender, **kwargs):
...
|
A decorator for connecting receivers to signals. Used by passing in the
signal (or list of signals) and keyword arguments to connect:: | def receiver(signal, **kwargs):
"""
A decorator for connecting receivers to signals. Used by passing in the
signal (or list of signals) and keyword arguments to connect::
@receiver(post_save, sender=MyModel)
def signal_receiver(sender, **kwargs):
...
@receiver([post_save, post_delete], sender=MyModel)
def signals_receiver(sender, **kwargs):
...
"""
def _decorator(func):
if isinstance(signal, (list, tuple)):
for s in signal:
s.connect(func, **kwargs)
else:
signal.connect(func, **kwargs)
return func
return _decorator | [
"def",
"receiver",
"(",
"signal",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_decorator",
"(",
"func",
")",
":",
"if",
"isinstance",
"(",
"signal",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"s",
"in",
"signal",
":",
"s",
".",
"connect",
"(",
"func",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"signal",
".",
"connect",
"(",
"func",
",",
"*",
"*",
"kwargs",
")",
"return",
"func",
"return",
"_decorator"
] | [
282,
0
] | [
302,
21
] | python | en | ['en', 'error', 'th'] | False |
Signal.__init__ | (self, providing_args=None, use_caching=False) |
Create a new signal.
|
Create a new signal.
| def __init__(self, providing_args=None, use_caching=False):
"""
Create a new signal.
"""
self.receivers = []
if providing_args is not None:
warnings.warn(
'The providing_args argument is deprecated. As it is purely '
'documentational, it has no replacement. If you rely on this '
'argument as documentation, you can move the text to a code '
'comment or docstring.',
RemovedInDjango40Warning, stacklevel=2,
)
self.lock = threading.Lock()
self.use_caching = use_caching
# For convenience we create empty caches even if they are not used.
# A note about caching: if use_caching is defined, then for each
# distinct sender we cache the receivers that sender has in
# 'sender_receivers_cache'. The cache is cleaned when .connect() or
# .disconnect() is called and populated on send().
self.sender_receivers_cache = weakref.WeakKeyDictionary() if use_caching else {}
self._dead_receivers = False | [
"def",
"__init__",
"(",
"self",
",",
"providing_args",
"=",
"None",
",",
"use_caching",
"=",
"False",
")",
":",
"self",
".",
"receivers",
"=",
"[",
"]",
"if",
"providing_args",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"'The providing_args argument is deprecated. As it is purely '",
"'documentational, it has no replacement. If you rely on this '",
"'argument as documentation, you can move the text to a code '",
"'comment or docstring.'",
",",
"RemovedInDjango40Warning",
",",
"stacklevel",
"=",
"2",
",",
")",
"self",
".",
"lock",
"=",
"threading",
".",
"Lock",
"(",
")",
"self",
".",
"use_caching",
"=",
"use_caching",
"# For convenience we create empty caches even if they are not used.",
"# A note about caching: if use_caching is defined, then for each",
"# distinct sender we cache the receivers that sender has in",
"# 'sender_receivers_cache'. The cache is cleaned when .connect() or",
"# .disconnect() is called and populated on send().",
"self",
".",
"sender_receivers_cache",
"=",
"weakref",
".",
"WeakKeyDictionary",
"(",
")",
"if",
"use_caching",
"else",
"{",
"}",
"self",
".",
"_dead_receivers",
"=",
"False"
] | [
32,
4
] | [
53,
36
] | python | en | ['en', 'error', 'th'] | False |
Signal.connect | (self, receiver, sender=None, weak=True, dispatch_uid=None) |
Connect receiver to sender for signal.
Arguments:
receiver
A function or an instance method which is to receive signals.
Receivers must be hashable objects.
If weak is True, then receiver must be weak referenceable.
Receivers must be able to accept keyword arguments.
If a receiver is connected with a dispatch_uid argument, it
will not be added if another receiver was already connected
with that dispatch_uid.
sender
The sender to which the receiver should respond. Must either be
a Python object, or None to receive events from any sender.
weak
Whether to use weak references to the receiver. By default, the
module will attempt to use weak references to the receiver
objects. If this parameter is false, then strong references will
be used.
dispatch_uid
An identifier used to uniquely identify a particular instance of
a receiver. This will usually be a string, though it may be
anything hashable.
|
Connect receiver to sender for signal. | def connect(self, receiver, sender=None, weak=True, dispatch_uid=None):
"""
Connect receiver to sender for signal.
Arguments:
receiver
A function or an instance method which is to receive signals.
Receivers must be hashable objects.
If weak is True, then receiver must be weak referenceable.
Receivers must be able to accept keyword arguments.
If a receiver is connected with a dispatch_uid argument, it
will not be added if another receiver was already connected
with that dispatch_uid.
sender
The sender to which the receiver should respond. Must either be
a Python object, or None to receive events from any sender.
weak
Whether to use weak references to the receiver. By default, the
module will attempt to use weak references to the receiver
objects. If this parameter is false, then strong references will
be used.
dispatch_uid
An identifier used to uniquely identify a particular instance of
a receiver. This will usually be a string, though it may be
anything hashable.
"""
from django.conf import settings
# If DEBUG is on, check that we got a good receiver
if settings.configured and settings.DEBUG:
assert callable(receiver), "Signal receivers must be callable."
# Check for **kwargs
if not func_accepts_kwargs(receiver):
raise ValueError("Signal receivers must accept keyword arguments (**kwargs).")
if dispatch_uid:
lookup_key = (dispatch_uid, _make_id(sender))
else:
lookup_key = (_make_id(receiver), _make_id(sender))
if weak:
ref = weakref.ref
receiver_object = receiver
# Check for bound methods
if hasattr(receiver, '__self__') and hasattr(receiver, '__func__'):
ref = weakref.WeakMethod
receiver_object = receiver.__self__
receiver = ref(receiver)
weakref.finalize(receiver_object, self._remove_receiver)
with self.lock:
self._clear_dead_receivers()
if not any(r_key == lookup_key for r_key, _ in self.receivers):
self.receivers.append((lookup_key, receiver))
self.sender_receivers_cache.clear() | [
"def",
"connect",
"(",
"self",
",",
"receiver",
",",
"sender",
"=",
"None",
",",
"weak",
"=",
"True",
",",
"dispatch_uid",
"=",
"None",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"# If DEBUG is on, check that we got a good receiver",
"if",
"settings",
".",
"configured",
"and",
"settings",
".",
"DEBUG",
":",
"assert",
"callable",
"(",
"receiver",
")",
",",
"\"Signal receivers must be callable.\"",
"# Check for **kwargs",
"if",
"not",
"func_accepts_kwargs",
"(",
"receiver",
")",
":",
"raise",
"ValueError",
"(",
"\"Signal receivers must accept keyword arguments (**kwargs).\"",
")",
"if",
"dispatch_uid",
":",
"lookup_key",
"=",
"(",
"dispatch_uid",
",",
"_make_id",
"(",
"sender",
")",
")",
"else",
":",
"lookup_key",
"=",
"(",
"_make_id",
"(",
"receiver",
")",
",",
"_make_id",
"(",
"sender",
")",
")",
"if",
"weak",
":",
"ref",
"=",
"weakref",
".",
"ref",
"receiver_object",
"=",
"receiver",
"# Check for bound methods",
"if",
"hasattr",
"(",
"receiver",
",",
"'__self__'",
")",
"and",
"hasattr",
"(",
"receiver",
",",
"'__func__'",
")",
":",
"ref",
"=",
"weakref",
".",
"WeakMethod",
"receiver_object",
"=",
"receiver",
".",
"__self__",
"receiver",
"=",
"ref",
"(",
"receiver",
")",
"weakref",
".",
"finalize",
"(",
"receiver_object",
",",
"self",
".",
"_remove_receiver",
")",
"with",
"self",
".",
"lock",
":",
"self",
".",
"_clear_dead_receivers",
"(",
")",
"if",
"not",
"any",
"(",
"r_key",
"==",
"lookup_key",
"for",
"r_key",
",",
"_",
"in",
"self",
".",
"receivers",
")",
":",
"self",
".",
"receivers",
".",
"append",
"(",
"(",
"lookup_key",
",",
"receiver",
")",
")",
"self",
".",
"sender_receivers_cache",
".",
"clear",
"(",
")"
] | [
55,
4
] | [
117,
47
] | python | en | ['en', 'error', 'th'] | False |
Signal.disconnect | (self, receiver=None, sender=None, dispatch_uid=None) |
Disconnect receiver from sender for signal.
If weak references are used, disconnect need not be called. The receiver
will be removed from dispatch automatically.
Arguments:
receiver
The registered receiver to disconnect. May be none if
dispatch_uid is specified.
sender
The registered sender to disconnect
dispatch_uid
the unique identifier of the receiver to disconnect
|
Disconnect receiver from sender for signal. | def disconnect(self, receiver=None, sender=None, dispatch_uid=None):
"""
Disconnect receiver from sender for signal.
If weak references are used, disconnect need not be called. The receiver
will be removed from dispatch automatically.
Arguments:
receiver
The registered receiver to disconnect. May be none if
dispatch_uid is specified.
sender
The registered sender to disconnect
dispatch_uid
the unique identifier of the receiver to disconnect
"""
if dispatch_uid:
lookup_key = (dispatch_uid, _make_id(sender))
else:
lookup_key = (_make_id(receiver), _make_id(sender))
disconnected = False
with self.lock:
self._clear_dead_receivers()
for index in range(len(self.receivers)):
(r_key, _) = self.receivers[index]
if r_key == lookup_key:
disconnected = True
del self.receivers[index]
break
self.sender_receivers_cache.clear()
return disconnected | [
"def",
"disconnect",
"(",
"self",
",",
"receiver",
"=",
"None",
",",
"sender",
"=",
"None",
",",
"dispatch_uid",
"=",
"None",
")",
":",
"if",
"dispatch_uid",
":",
"lookup_key",
"=",
"(",
"dispatch_uid",
",",
"_make_id",
"(",
"sender",
")",
")",
"else",
":",
"lookup_key",
"=",
"(",
"_make_id",
"(",
"receiver",
")",
",",
"_make_id",
"(",
"sender",
")",
")",
"disconnected",
"=",
"False",
"with",
"self",
".",
"lock",
":",
"self",
".",
"_clear_dead_receivers",
"(",
")",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"receivers",
")",
")",
":",
"(",
"r_key",
",",
"_",
")",
"=",
"self",
".",
"receivers",
"[",
"index",
"]",
"if",
"r_key",
"==",
"lookup_key",
":",
"disconnected",
"=",
"True",
"del",
"self",
".",
"receivers",
"[",
"index",
"]",
"break",
"self",
".",
"sender_receivers_cache",
".",
"clear",
"(",
")",
"return",
"disconnected"
] | [
119,
4
] | [
153,
27
] | python | en | ['en', 'error', 'th'] | False |
Signal.send | (self, sender, **named) |
Send signal from sender to all connected receivers.
If any receiver raises an error, the error propagates back through send,
terminating the dispatch loop. So it's possible that all receivers
won't be called if an error is raised.
Arguments:
sender
The sender of the signal. Either a specific object or None.
named
Named arguments which will be passed to receivers.
Return a list of tuple pairs [(receiver, response), ... ].
|
Send signal from sender to all connected receivers. | def send(self, sender, **named):
"""
Send signal from sender to all connected receivers.
If any receiver raises an error, the error propagates back through send,
terminating the dispatch loop. So it's possible that all receivers
won't be called if an error is raised.
Arguments:
sender
The sender of the signal. Either a specific object or None.
named
Named arguments which will be passed to receivers.
Return a list of tuple pairs [(receiver, response), ... ].
"""
if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:
return []
return [
(receiver, receiver(signal=self, sender=sender, **named))
for receiver in self._live_receivers(sender)
] | [
"def",
"send",
"(",
"self",
",",
"sender",
",",
"*",
"*",
"named",
")",
":",
"if",
"not",
"self",
".",
"receivers",
"or",
"self",
".",
"sender_receivers_cache",
".",
"get",
"(",
"sender",
")",
"is",
"NO_RECEIVERS",
":",
"return",
"[",
"]",
"return",
"[",
"(",
"receiver",
",",
"receiver",
"(",
"signal",
"=",
"self",
",",
"sender",
"=",
"sender",
",",
"*",
"*",
"named",
")",
")",
"for",
"receiver",
"in",
"self",
".",
"_live_receivers",
"(",
"sender",
")",
"]"
] | [
158,
4
] | [
182,
9
] | python | en | ['en', 'error', 'th'] | False |
Signal.send_robust | (self, sender, **named) |
Send signal from sender to all connected receivers catching errors.
Arguments:
sender
The sender of the signal. Can be any Python object (normally one
registered with a connect if you actually want something to
occur).
named
Named arguments which will be passed to receivers.
Return a list of tuple pairs [(receiver, response), ... ].
If any receiver raises an error (specifically any subclass of
Exception), return the error instance as the result for that receiver.
|
Send signal from sender to all connected receivers catching errors. | def send_robust(self, sender, **named):
"""
Send signal from sender to all connected receivers catching errors.
Arguments:
sender
The sender of the signal. Can be any Python object (normally one
registered with a connect if you actually want something to
occur).
named
Named arguments which will be passed to receivers.
Return a list of tuple pairs [(receiver, response), ... ].
If any receiver raises an error (specifically any subclass of
Exception), return the error instance as the result for that receiver.
"""
if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:
return []
# Call each receiver with whatever arguments it can accept.
# Return a list of tuple pairs [(receiver, response), ... ].
responses = []
for receiver in self._live_receivers(sender):
try:
response = receiver(signal=self, sender=sender, **named)
except Exception as err:
logger.error(
'Error calling %s in Signal.send_robust() (%s)',
receiver.__qualname__,
err,
exc_info=err,
)
responses.append((receiver, err))
else:
responses.append((receiver, response))
return responses | [
"def",
"send_robust",
"(",
"self",
",",
"sender",
",",
"*",
"*",
"named",
")",
":",
"if",
"not",
"self",
".",
"receivers",
"or",
"self",
".",
"sender_receivers_cache",
".",
"get",
"(",
"sender",
")",
"is",
"NO_RECEIVERS",
":",
"return",
"[",
"]",
"# Call each receiver with whatever arguments it can accept.",
"# Return a list of tuple pairs [(receiver, response), ... ].",
"responses",
"=",
"[",
"]",
"for",
"receiver",
"in",
"self",
".",
"_live_receivers",
"(",
"sender",
")",
":",
"try",
":",
"response",
"=",
"receiver",
"(",
"signal",
"=",
"self",
",",
"sender",
"=",
"sender",
",",
"*",
"*",
"named",
")",
"except",
"Exception",
"as",
"err",
":",
"logger",
".",
"error",
"(",
"'Error calling %s in Signal.send_robust() (%s)'",
",",
"receiver",
".",
"__qualname__",
",",
"err",
",",
"exc_info",
"=",
"err",
",",
")",
"responses",
".",
"append",
"(",
"(",
"receiver",
",",
"err",
")",
")",
"else",
":",
"responses",
".",
"append",
"(",
"(",
"receiver",
",",
"response",
")",
")",
"return",
"responses"
] | [
184,
4
] | [
222,
24
] | python | en | ['en', 'error', 'th'] | False |
Signal._live_receivers | (self, sender) |
Filter sequence of receivers to get resolved, live receivers.
This checks for weak references and resolves them, then returning only
live receivers.
|
Filter sequence of receivers to get resolved, live receivers. | def _live_receivers(self, sender):
"""
Filter sequence of receivers to get resolved, live receivers.
This checks for weak references and resolves them, then returning only
live receivers.
"""
receivers = None
if self.use_caching and not self._dead_receivers:
receivers = self.sender_receivers_cache.get(sender)
# We could end up here with NO_RECEIVERS even if we do check this case in
# .send() prior to calling _live_receivers() due to concurrent .send() call.
if receivers is NO_RECEIVERS:
return []
if receivers is None:
with self.lock:
self._clear_dead_receivers()
senderkey = _make_id(sender)
receivers = []
for (receiverkey, r_senderkey), receiver in self.receivers:
if r_senderkey == NONE_ID or r_senderkey == senderkey:
receivers.append(receiver)
if self.use_caching:
if not receivers:
self.sender_receivers_cache[sender] = NO_RECEIVERS
else:
# Note, we must cache the weakref versions.
self.sender_receivers_cache[sender] = receivers
non_weak_receivers = []
for receiver in receivers:
if isinstance(receiver, weakref.ReferenceType):
# Dereference the weak reference.
receiver = receiver()
if receiver is not None:
non_weak_receivers.append(receiver)
else:
non_weak_receivers.append(receiver)
return non_weak_receivers | [
"def",
"_live_receivers",
"(",
"self",
",",
"sender",
")",
":",
"receivers",
"=",
"None",
"if",
"self",
".",
"use_caching",
"and",
"not",
"self",
".",
"_dead_receivers",
":",
"receivers",
"=",
"self",
".",
"sender_receivers_cache",
".",
"get",
"(",
"sender",
")",
"# We could end up here with NO_RECEIVERS even if we do check this case in",
"# .send() prior to calling _live_receivers() due to concurrent .send() call.",
"if",
"receivers",
"is",
"NO_RECEIVERS",
":",
"return",
"[",
"]",
"if",
"receivers",
"is",
"None",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"_clear_dead_receivers",
"(",
")",
"senderkey",
"=",
"_make_id",
"(",
"sender",
")",
"receivers",
"=",
"[",
"]",
"for",
"(",
"receiverkey",
",",
"r_senderkey",
")",
",",
"receiver",
"in",
"self",
".",
"receivers",
":",
"if",
"r_senderkey",
"==",
"NONE_ID",
"or",
"r_senderkey",
"==",
"senderkey",
":",
"receivers",
".",
"append",
"(",
"receiver",
")",
"if",
"self",
".",
"use_caching",
":",
"if",
"not",
"receivers",
":",
"self",
".",
"sender_receivers_cache",
"[",
"sender",
"]",
"=",
"NO_RECEIVERS",
"else",
":",
"# Note, we must cache the weakref versions.",
"self",
".",
"sender_receivers_cache",
"[",
"sender",
"]",
"=",
"receivers",
"non_weak_receivers",
"=",
"[",
"]",
"for",
"receiver",
"in",
"receivers",
":",
"if",
"isinstance",
"(",
"receiver",
",",
"weakref",
".",
"ReferenceType",
")",
":",
"# Dereference the weak reference.",
"receiver",
"=",
"receiver",
"(",
")",
"if",
"receiver",
"is",
"not",
"None",
":",
"non_weak_receivers",
".",
"append",
"(",
"receiver",
")",
"else",
":",
"non_weak_receivers",
".",
"append",
"(",
"receiver",
")",
"return",
"non_weak_receivers"
] | [
233,
4
] | [
270,
33
] | python | en | ['en', 'error', 'th'] | False |
module_to_dict | (module, omittable=lambda k: k.startswith('_') or not k.isupper()) | Convert a module namespace to a Python dictionary. | Convert a module namespace to a Python dictionary. | def module_to_dict(module, omittable=lambda k: k.startswith('_') or not k.isupper()):
"""Convert a module namespace to a Python dictionary."""
return {k: repr(getattr(module, k)) for k in dir(module) if not omittable(k)} | [
"def",
"module_to_dict",
"(",
"module",
",",
"omittable",
"=",
"lambda",
"k",
":",
"k",
".",
"startswith",
"(",
"'_'",
")",
"or",
"not",
"k",
".",
"isupper",
"(",
")",
")",
":",
"return",
"{",
"k",
":",
"repr",
"(",
"getattr",
"(",
"module",
",",
"k",
")",
")",
"for",
"k",
"in",
"dir",
"(",
"module",
")",
"if",
"not",
"omittable",
"(",
"k",
")",
"}"
] | [
3,
0
] | [
5,
81
] | python | en | ['en', 'en', 'en'] | True |
feed | (request, url, feed_dict=None) | Provided for backwards compatibility. | Provided for backwards compatibility. | def feed(request, url, feed_dict=None):
"""Provided for backwards compatibility."""
if not feed_dict:
raise Http404(_("No feeds are registered."))
slug = url.partition('/')[0]
try:
f = feed_dict[slug]
except KeyError:
raise Http404(_('Slug %r isn’t registered.') % slug)
instance = f()
instance.feed_url = getattr(f, 'feed_url', None) or request.path
instance.title_template = f.title_template or ('feeds/%s_title.html' % slug)
instance.description_template = f.description_template or ('feeds/%s_description.html' % slug)
return instance(request) | [
"def",
"feed",
"(",
"request",
",",
"url",
",",
"feed_dict",
"=",
"None",
")",
":",
"if",
"not",
"feed_dict",
":",
"raise",
"Http404",
"(",
"_",
"(",
"\"No feeds are registered.\"",
")",
")",
"slug",
"=",
"url",
".",
"partition",
"(",
"'/'",
")",
"[",
"0",
"]",
"try",
":",
"f",
"=",
"feed_dict",
"[",
"slug",
"]",
"except",
"KeyError",
":",
"raise",
"Http404",
"(",
"_",
"(",
"'Slug %r isn’t registered.') ",
"%",
"s",
"ug)",
"",
"instance",
"=",
"f",
"(",
")",
"instance",
".",
"feed_url",
"=",
"getattr",
"(",
"f",
",",
"'feed_url'",
",",
"None",
")",
"or",
"request",
".",
"path",
"instance",
".",
"title_template",
"=",
"f",
".",
"title_template",
"or",
"(",
"'feeds/%s_title.html'",
"%",
"slug",
")",
"instance",
".",
"description_template",
"=",
"f",
".",
"description_template",
"or",
"(",
"'feeds/%s_description.html'",
"%",
"slug",
")",
"return",
"instance",
"(",
"request",
")"
] | [
4,
0
] | [
19,
28
] | python | en | ['en', 'en', 'en'] | True |
_covert_legacy_entry | (entry: Tuple[str, ...], info: Tuple[str, ...]) | Convert a legacy installed-files.txt path into modern RECORD path.
The legacy format stores paths relative to the info directory, while the
modern format stores paths relative to the package root, e.g. the
site-packages directory.
:param entry: Path parts of the installed-files.txt entry.
:param info: Path parts of the egg-info directory relative to package root.
:returns: The converted entry.
For best compatibility with symlinks, this does not use ``abspath()`` or
``Path.resolve()``, but tries to work with path parts:
1. While ``entry`` starts with ``..``, remove the equal amounts of parts
from ``info``; if ``info`` is empty, start appending ``..`` instead.
2. Join the two directly.
| Convert a legacy installed-files.txt path into modern RECORD path. | def _covert_legacy_entry(entry: Tuple[str, ...], info: Tuple[str, ...]) -> str:
"""Convert a legacy installed-files.txt path into modern RECORD path.
The legacy format stores paths relative to the info directory, while the
modern format stores paths relative to the package root, e.g. the
site-packages directory.
:param entry: Path parts of the installed-files.txt entry.
:param info: Path parts of the egg-info directory relative to package root.
:returns: The converted entry.
For best compatibility with symlinks, this does not use ``abspath()`` or
``Path.resolve()``, but tries to work with path parts:
1. While ``entry`` starts with ``..``, remove the equal amounts of parts
from ``info``; if ``info`` is empty, start appending ``..`` instead.
2. Join the two directly.
"""
while entry and entry[0] == "..":
if not info or info[-1] == "..":
info += ("..",)
else:
info = info[:-1]
entry = entry[1:]
return str(pathlib.Path(*info, *entry)) | [
"def",
"_covert_legacy_entry",
"(",
"entry",
":",
"Tuple",
"[",
"str",
",",
"...",
"]",
",",
"info",
":",
"Tuple",
"[",
"str",
",",
"...",
"]",
")",
"->",
"str",
":",
"while",
"entry",
"and",
"entry",
"[",
"0",
"]",
"==",
"\"..\"",
":",
"if",
"not",
"info",
"or",
"info",
"[",
"-",
"1",
"]",
"==",
"\"..\"",
":",
"info",
"+=",
"(",
"\"..\"",
",",
")",
"else",
":",
"info",
"=",
"info",
"[",
":",
"-",
"1",
"]",
"entry",
"=",
"entry",
"[",
"1",
":",
"]",
"return",
"str",
"(",
"pathlib",
".",
"Path",
"(",
"*",
"info",
",",
"*",
"entry",
")",
")"
] | [
68,
0
] | [
92,
43
] | python | en | ['en', 'en', 'en'] | True |
search_packages_info | (query: List[str]) |
Gather details from installed distributions. Print distribution name,
version, location, and installed files. Installed files requires a
pip generated 'installed-files.txt' in the distributions '.egg-info'
directory.
|
Gather details from installed distributions. Print distribution name,
version, location, and installed files. Installed files requires a
pip generated 'installed-files.txt' in the distributions '.egg-info'
directory.
| def search_packages_info(query: List[str]) -> Iterator[_PackageInfo]:
"""
Gather details from installed distributions. Print distribution name,
version, location, and installed files. Installed files requires a
pip generated 'installed-files.txt' in the distributions '.egg-info'
directory.
"""
env = get_default_environment()
installed = {
dist.canonical_name: dist
for dist in env.iter_distributions()
}
query_names = [canonicalize_name(name) for name in query]
missing = sorted(
[name for name, pkg in zip(query, query_names) if pkg not in installed]
)
if missing:
logger.warning('Package(s) not found: %s', ', '.join(missing))
def _get_requiring_packages(current_dist: BaseDistribution) -> List[str]:
return [
dist.metadata["Name"] or "UNKNOWN"
for dist in installed.values()
if current_dist.canonical_name in {
canonicalize_name(d.name) for d in dist.iter_dependencies()
}
]
def _files_from_record(dist: BaseDistribution) -> Optional[Iterator[str]]:
try:
text = dist.read_text('RECORD')
except FileNotFoundError:
return None
# This extra Path-str cast normalizes entries.
return (str(pathlib.Path(row[0])) for row in csv.reader(text.splitlines()))
def _files_from_legacy(dist: BaseDistribution) -> Optional[Iterator[str]]:
try:
text = dist.read_text('installed-files.txt')
except FileNotFoundError:
return None
paths = (p for p in text.splitlines(keepends=False) if p)
root = dist.location
info = dist.info_directory
if root is None or info is None:
return paths
try:
info_rel = pathlib.Path(info).relative_to(root)
except ValueError: # info is not relative to root.
return paths
if not info_rel.parts: # info *is* root.
return paths
return (
_covert_legacy_entry(pathlib.Path(p).parts, info_rel.parts)
for p in paths
)
for query_name in query_names:
try:
dist = installed[query_name]
except KeyError:
continue
try:
entry_points_text = dist.read_text('entry_points.txt')
entry_points = entry_points_text.splitlines(keepends=False)
except FileNotFoundError:
entry_points = []
files_iter = _files_from_record(dist) or _files_from_legacy(dist)
if files_iter is None:
files: Optional[List[str]] = None
else:
files = sorted(files_iter)
metadata = dist.metadata
yield _PackageInfo(
name=dist.raw_name,
version=str(dist.version),
location=dist.location or "",
requires=[req.name for req in dist.iter_dependencies()],
required_by=_get_requiring_packages(dist),
installer=dist.installer,
metadata_version=dist.metadata_version or "",
classifiers=metadata.get_all("Classifier", []),
summary=metadata.get("Summary", ""),
homepage=metadata.get("Home-page", ""),
author=metadata.get("Author", ""),
author_email=metadata.get("Author-email", ""),
license=metadata.get("License", ""),
entry_points=entry_points,
files=files,
) | [
"def",
"search_packages_info",
"(",
"query",
":",
"List",
"[",
"str",
"]",
")",
"->",
"Iterator",
"[",
"_PackageInfo",
"]",
":",
"env",
"=",
"get_default_environment",
"(",
")",
"installed",
"=",
"{",
"dist",
".",
"canonical_name",
":",
"dist",
"for",
"dist",
"in",
"env",
".",
"iter_distributions",
"(",
")",
"}",
"query_names",
"=",
"[",
"canonicalize_name",
"(",
"name",
")",
"for",
"name",
"in",
"query",
"]",
"missing",
"=",
"sorted",
"(",
"[",
"name",
"for",
"name",
",",
"pkg",
"in",
"zip",
"(",
"query",
",",
"query_names",
")",
"if",
"pkg",
"not",
"in",
"installed",
"]",
")",
"if",
"missing",
":",
"logger",
".",
"warning",
"(",
"'Package(s) not found: %s'",
",",
"', '",
".",
"join",
"(",
"missing",
")",
")",
"def",
"_get_requiring_packages",
"(",
"current_dist",
":",
"BaseDistribution",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"dist",
".",
"metadata",
"[",
"\"Name\"",
"]",
"or",
"\"UNKNOWN\"",
"for",
"dist",
"in",
"installed",
".",
"values",
"(",
")",
"if",
"current_dist",
".",
"canonical_name",
"in",
"{",
"canonicalize_name",
"(",
"d",
".",
"name",
")",
"for",
"d",
"in",
"dist",
".",
"iter_dependencies",
"(",
")",
"}",
"]",
"def",
"_files_from_record",
"(",
"dist",
":",
"BaseDistribution",
")",
"->",
"Optional",
"[",
"Iterator",
"[",
"str",
"]",
"]",
":",
"try",
":",
"text",
"=",
"dist",
".",
"read_text",
"(",
"'RECORD'",
")",
"except",
"FileNotFoundError",
":",
"return",
"None",
"# This extra Path-str cast normalizes entries.",
"return",
"(",
"str",
"(",
"pathlib",
".",
"Path",
"(",
"row",
"[",
"0",
"]",
")",
")",
"for",
"row",
"in",
"csv",
".",
"reader",
"(",
"text",
".",
"splitlines",
"(",
")",
")",
")",
"def",
"_files_from_legacy",
"(",
"dist",
":",
"BaseDistribution",
")",
"->",
"Optional",
"[",
"Iterator",
"[",
"str",
"]",
"]",
":",
"try",
":",
"text",
"=",
"dist",
".",
"read_text",
"(",
"'installed-files.txt'",
")",
"except",
"FileNotFoundError",
":",
"return",
"None",
"paths",
"=",
"(",
"p",
"for",
"p",
"in",
"text",
".",
"splitlines",
"(",
"keepends",
"=",
"False",
")",
"if",
"p",
")",
"root",
"=",
"dist",
".",
"location",
"info",
"=",
"dist",
".",
"info_directory",
"if",
"root",
"is",
"None",
"or",
"info",
"is",
"None",
":",
"return",
"paths",
"try",
":",
"info_rel",
"=",
"pathlib",
".",
"Path",
"(",
"info",
")",
".",
"relative_to",
"(",
"root",
")",
"except",
"ValueError",
":",
"# info is not relative to root.",
"return",
"paths",
"if",
"not",
"info_rel",
".",
"parts",
":",
"# info *is* root.",
"return",
"paths",
"return",
"(",
"_covert_legacy_entry",
"(",
"pathlib",
".",
"Path",
"(",
"p",
")",
".",
"parts",
",",
"info_rel",
".",
"parts",
")",
"for",
"p",
"in",
"paths",
")",
"for",
"query_name",
"in",
"query_names",
":",
"try",
":",
"dist",
"=",
"installed",
"[",
"query_name",
"]",
"except",
"KeyError",
":",
"continue",
"try",
":",
"entry_points_text",
"=",
"dist",
".",
"read_text",
"(",
"'entry_points.txt'",
")",
"entry_points",
"=",
"entry_points_text",
".",
"splitlines",
"(",
"keepends",
"=",
"False",
")",
"except",
"FileNotFoundError",
":",
"entry_points",
"=",
"[",
"]",
"files_iter",
"=",
"_files_from_record",
"(",
"dist",
")",
"or",
"_files_from_legacy",
"(",
"dist",
")",
"if",
"files_iter",
"is",
"None",
":",
"files",
":",
"Optional",
"[",
"List",
"[",
"str",
"]",
"]",
"=",
"None",
"else",
":",
"files",
"=",
"sorted",
"(",
"files_iter",
")",
"metadata",
"=",
"dist",
".",
"metadata",
"yield",
"_PackageInfo",
"(",
"name",
"=",
"dist",
".",
"raw_name",
",",
"version",
"=",
"str",
"(",
"dist",
".",
"version",
")",
",",
"location",
"=",
"dist",
".",
"location",
"or",
"\"\"",
",",
"requires",
"=",
"[",
"req",
".",
"name",
"for",
"req",
"in",
"dist",
".",
"iter_dependencies",
"(",
")",
"]",
",",
"required_by",
"=",
"_get_requiring_packages",
"(",
"dist",
")",
",",
"installer",
"=",
"dist",
".",
"installer",
",",
"metadata_version",
"=",
"dist",
".",
"metadata_version",
"or",
"\"\"",
",",
"classifiers",
"=",
"metadata",
".",
"get_all",
"(",
"\"Classifier\"",
",",
"[",
"]",
")",
",",
"summary",
"=",
"metadata",
".",
"get",
"(",
"\"Summary\"",
",",
"\"\"",
")",
",",
"homepage",
"=",
"metadata",
".",
"get",
"(",
"\"Home-page\"",
",",
"\"\"",
")",
",",
"author",
"=",
"metadata",
".",
"get",
"(",
"\"Author\"",
",",
"\"\"",
")",
",",
"author_email",
"=",
"metadata",
".",
"get",
"(",
"\"Author-email\"",
",",
"\"\"",
")",
",",
"license",
"=",
"metadata",
".",
"get",
"(",
"\"License\"",
",",
"\"\"",
")",
",",
"entry_points",
"=",
"entry_points",
",",
"files",
"=",
"files",
",",
")"
] | [
95,
0
] | [
189,
9
] | python | en | ['en', 'error', 'th'] | False |
print_results | (
distributions: Iterator[_PackageInfo],
list_files: bool,
verbose: bool,
) |
Print the information from installed distributions found.
|
Print the information from installed distributions found.
| def print_results(
distributions: Iterator[_PackageInfo],
list_files: bool,
verbose: bool,
) -> bool:
"""
Print the information from installed distributions found.
"""
results_printed = False
for i, dist in enumerate(distributions):
results_printed = True
if i > 0:
write_output("---")
write_output("Name: %s", dist.name)
write_output("Version: %s", dist.version)
write_output("Summary: %s", dist.summary)
write_output("Home-page: %s", dist.homepage)
write_output("Author: %s", dist.author)
write_output("Author-email: %s", dist.author_email)
write_output("License: %s", dist.license)
write_output("Location: %s", dist.location)
write_output("Requires: %s", ', '.join(dist.requires))
write_output("Required-by: %s", ', '.join(dist.required_by))
if verbose:
write_output("Metadata-Version: %s", dist.metadata_version)
write_output("Installer: %s", dist.installer)
write_output("Classifiers:")
for classifier in dist.classifiers:
write_output(" %s", classifier)
write_output("Entry-points:")
for entry in dist.entry_points:
write_output(" %s", entry.strip())
if list_files:
write_output("Files:")
if dist.files is None:
write_output("Cannot locate RECORD or installed-files.txt")
else:
for line in dist.files:
write_output(" %s", line.strip())
return results_printed | [
"def",
"print_results",
"(",
"distributions",
":",
"Iterator",
"[",
"_PackageInfo",
"]",
",",
"list_files",
":",
"bool",
",",
"verbose",
":",
"bool",
",",
")",
"->",
"bool",
":",
"results_printed",
"=",
"False",
"for",
"i",
",",
"dist",
"in",
"enumerate",
"(",
"distributions",
")",
":",
"results_printed",
"=",
"True",
"if",
"i",
">",
"0",
":",
"write_output",
"(",
"\"---\"",
")",
"write_output",
"(",
"\"Name: %s\"",
",",
"dist",
".",
"name",
")",
"write_output",
"(",
"\"Version: %s\"",
",",
"dist",
".",
"version",
")",
"write_output",
"(",
"\"Summary: %s\"",
",",
"dist",
".",
"summary",
")",
"write_output",
"(",
"\"Home-page: %s\"",
",",
"dist",
".",
"homepage",
")",
"write_output",
"(",
"\"Author: %s\"",
",",
"dist",
".",
"author",
")",
"write_output",
"(",
"\"Author-email: %s\"",
",",
"dist",
".",
"author_email",
")",
"write_output",
"(",
"\"License: %s\"",
",",
"dist",
".",
"license",
")",
"write_output",
"(",
"\"Location: %s\"",
",",
"dist",
".",
"location",
")",
"write_output",
"(",
"\"Requires: %s\"",
",",
"', '",
".",
"join",
"(",
"dist",
".",
"requires",
")",
")",
"write_output",
"(",
"\"Required-by: %s\"",
",",
"', '",
".",
"join",
"(",
"dist",
".",
"required_by",
")",
")",
"if",
"verbose",
":",
"write_output",
"(",
"\"Metadata-Version: %s\"",
",",
"dist",
".",
"metadata_version",
")",
"write_output",
"(",
"\"Installer: %s\"",
",",
"dist",
".",
"installer",
")",
"write_output",
"(",
"\"Classifiers:\"",
")",
"for",
"classifier",
"in",
"dist",
".",
"classifiers",
":",
"write_output",
"(",
"\" %s\"",
",",
"classifier",
")",
"write_output",
"(",
"\"Entry-points:\"",
")",
"for",
"entry",
"in",
"dist",
".",
"entry_points",
":",
"write_output",
"(",
"\" %s\"",
",",
"entry",
".",
"strip",
"(",
")",
")",
"if",
"list_files",
":",
"write_output",
"(",
"\"Files:\"",
")",
"if",
"dist",
".",
"files",
"is",
"None",
":",
"write_output",
"(",
"\"Cannot locate RECORD or installed-files.txt\"",
")",
"else",
":",
"for",
"line",
"in",
"dist",
".",
"files",
":",
"write_output",
"(",
"\" %s\"",
",",
"line",
".",
"strip",
"(",
")",
")",
"return",
"results_printed"
] | [
192,
0
] | [
233,
26
] | python | en | ['en', 'error', 'th'] | False |
call_metadata_api | (method, uri, params, **options) | Private function that assists with performing an API call to the
metadata_fields part of the Admin API
:param method: The HTTP method. Valid methods: get, post, put, delete
:param uri: REST endpoint of the API (without 'metadata_fields')
:param params: Query/body parameters passed to the method
:param options: Additional options
:rtype: Response
| Private function that assists with performing an API call to the
metadata_fields part of the Admin API
:param method: The HTTP method. Valid methods: get, post, put, delete
:param uri: REST endpoint of the API (without 'metadata_fields')
:param params: Query/body parameters passed to the method
:param options: Additional options
:rtype: Response
| def call_metadata_api(method, uri, params, **options):
"""Private function that assists with performing an API call to the
metadata_fields part of the Admin API
:param method: The HTTP method. Valid methods: get, post, put, delete
:param uri: REST endpoint of the API (without 'metadata_fields')
:param params: Query/body parameters passed to the method
:param options: Additional options
:rtype: Response
"""
uri = ["metadata_fields"] + (uri or [])
return call_json_api(method, uri, params, **options) | [
"def",
"call_metadata_api",
"(",
"method",
",",
"uri",
",",
"params",
",",
"*",
"*",
"options",
")",
":",
"uri",
"=",
"[",
"\"metadata_fields\"",
"]",
"+",
"(",
"uri",
"or",
"[",
"]",
")",
"return",
"call_json_api",
"(",
"method",
",",
"uri",
",",
"params",
",",
"*",
"*",
"options",
")"
] | [
11,
0
] | [
21,
56
] | python | en | ['en', 'en', 'en'] | True |
KeyValueCacheAdapter.__init__ | (self, storage) | Create a new adapter for the provided storage interface | Create a new adapter for the provided storage interface | def __init__(self, storage):
"""Create a new adapter for the provided storage interface"""
if not isinstance(storage, KeyValueStorage):
raise ValueError("An instance of valid KeyValueStorage must be provided")
self._key_value_storage = storage | [
"def",
"__init__",
"(",
"self",
",",
"storage",
")",
":",
"if",
"not",
"isinstance",
"(",
"storage",
",",
"KeyValueStorage",
")",
":",
"raise",
"ValueError",
"(",
"\"An instance of valid KeyValueStorage must be provided\"",
")",
"self",
".",
"_key_value_storage",
"=",
"storage"
] | [
12,
4
] | [
17,
41
] | python | en | ['en', 'en', 'en'] | True |
KeyValueCacheAdapter.generate_cache_key | (public_id, type, resource_type, transformation, format) |
Generates key-value storage key from parameters
:param public_id: The public ID of the resource
:param type: The storage type
:param resource_type: The type of the resource
:param transformation: The transformation string
:param format: The format of the resource
:return: Resulting cache key
|
Generates key-value storage key from parameters | def generate_cache_key(public_id, type, resource_type, transformation, format):
"""
Generates key-value storage key from parameters
:param public_id: The public ID of the resource
:param type: The storage type
:param resource_type: The type of the resource
:param transformation: The transformation string
:param format: The format of the resource
:return: Resulting cache key
"""
valid_params = [p for p in [public_id, type, resource_type, transformation, format] if p]
return sha1("/".join(valid_params).encode("utf-8")).hexdigest() | [
"def",
"generate_cache_key",
"(",
"public_id",
",",
"type",
",",
"resource_type",
",",
"transformation",
",",
"format",
")",
":",
"valid_params",
"=",
"[",
"p",
"for",
"p",
"in",
"[",
"public_id",
",",
"type",
",",
"resource_type",
",",
"transformation",
",",
"format",
"]",
"if",
"p",
"]",
"return",
"sha1",
"(",
"\"/\"",
".",
"join",
"(",
"valid_params",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
"hexdigest",
"(",
")"
] | [
45,
4
] | [
60,
71
] | python | en | ['en', 'error', 'th'] | False |
_attr_key | (attr) | Return an appropriate key for an attribute for sorting
Attributes have a namespace that can be either ``None`` or a string. We
can't compare the two because they're different types, so we convert
``None`` to an empty string first.
| Return an appropriate key for an attribute for sorting | def _attr_key(attr):
"""Return an appropriate key for an attribute for sorting
Attributes have a namespace that can be either ``None`` or a string. We
can't compare the two because they're different types, so we convert
``None`` to an empty string first.
"""
return (attr[0][0] or ''), attr[0][1] | [
"def",
"_attr_key",
"(",
"attr",
")",
":",
"return",
"(",
"attr",
"[",
"0",
"]",
"[",
"0",
"]",
"or",
"''",
")",
",",
"attr",
"[",
"0",
"]",
"[",
"1",
"]"
] | [
7,
0
] | [
15,
41
] | python | en | ['en', 'en', 'en'] | True |
RemoteUserMiddleware.clean_username | (self, username, request) |
Allow the backend to clean the username, if the backend defines a
clean_username method.
|
Allow the backend to clean the username, if the backend defines a
clean_username method.
| def clean_username(self, username, request):
"""
Allow the backend to clean the username, if the backend defines a
clean_username method.
"""
backend_str = request.session[auth.BACKEND_SESSION_KEY]
backend = auth.load_backend(backend_str)
try:
username = backend.clean_username(username)
except AttributeError: # Backend has no clean_username method.
pass
return username | [
"def",
"clean_username",
"(",
"self",
",",
"username",
",",
"request",
")",
":",
"backend_str",
"=",
"request",
".",
"session",
"[",
"auth",
".",
"BACKEND_SESSION_KEY",
"]",
"backend",
"=",
"auth",
".",
"load_backend",
"(",
"backend_str",
")",
"try",
":",
"username",
"=",
"backend",
".",
"clean_username",
"(",
"username",
")",
"except",
"AttributeError",
":",
"# Backend has no clean_username method.",
"pass",
"return",
"username"
] | [
83,
4
] | [
94,
23
] | python | en | ['en', 'error', 'th'] | False |
RemoteUserMiddleware._remove_invalid_user | (self, request) |
Remove the current authenticated user in the request which is invalid
but only if the user is authenticated via the RemoteUserBackend.
|
Remove the current authenticated user in the request which is invalid
but only if the user is authenticated via the RemoteUserBackend.
| def _remove_invalid_user(self, request):
"""
Remove the current authenticated user in the request which is invalid
but only if the user is authenticated via the RemoteUserBackend.
"""
try:
stored_backend = load_backend(request.session.get(auth.BACKEND_SESSION_KEY, ''))
except ImportError:
# backend failed to load
auth.logout(request)
else:
if isinstance(stored_backend, RemoteUserBackend):
auth.logout(request) | [
"def",
"_remove_invalid_user",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"stored_backend",
"=",
"load_backend",
"(",
"request",
".",
"session",
".",
"get",
"(",
"auth",
".",
"BACKEND_SESSION_KEY",
",",
"''",
")",
")",
"except",
"ImportError",
":",
"# backend failed to load",
"auth",
".",
"logout",
"(",
"request",
")",
"else",
":",
"if",
"isinstance",
"(",
"stored_backend",
",",
"RemoteUserBackend",
")",
":",
"auth",
".",
"logout",
"(",
"request",
")"
] | [
96,
4
] | [
108,
36
] | python | en | ['en', 'error', 'th'] | False |
Command.write_migration_files | (self, changes) |
Take a changes dict and write them out as migration files.
|
Take a changes dict and write them out as migration files.
| def write_migration_files(self, changes):
"""
Take a changes dict and write them out as migration files.
"""
directory_created = {}
for app_label, app_migrations in changes.items():
if self.verbosity >= 1:
self.stdout.write(self.style.MIGRATE_HEADING("Migrations for '%s':" % app_label))
for migration in app_migrations:
# Describe the migration
writer = MigrationWriter(migration, self.include_header)
if self.verbosity >= 1:
# Display a relative path if it's below the current working
# directory, or an absolute path otherwise.
try:
migration_string = os.path.relpath(writer.path)
except ValueError:
migration_string = writer.path
if migration_string.startswith('..'):
migration_string = writer.path
self.stdout.write(' %s\n' % self.style.MIGRATE_LABEL(migration_string))
for operation in migration.operations:
self.stdout.write(' - %s' % operation.describe())
if not self.dry_run:
# Write the migrations file to the disk.
migrations_directory = os.path.dirname(writer.path)
if not directory_created.get(app_label):
os.makedirs(migrations_directory, exist_ok=True)
init_path = os.path.join(migrations_directory, "__init__.py")
if not os.path.isfile(init_path):
open(init_path, "w").close()
# We just do this once per app
directory_created[app_label] = True
migration_string = writer.as_string()
with open(writer.path, "w", encoding='utf-8') as fh:
fh.write(migration_string)
elif self.verbosity == 3:
# Alternatively, makemigrations --dry-run --verbosity 3
# will output the migrations to stdout rather than saving
# the file to the disk.
self.stdout.write(self.style.MIGRATE_HEADING(
"Full migrations file '%s':" % writer.filename
))
self.stdout.write(writer.as_string()) | [
"def",
"write_migration_files",
"(",
"self",
",",
"changes",
")",
":",
"directory_created",
"=",
"{",
"}",
"for",
"app_label",
",",
"app_migrations",
"in",
"changes",
".",
"items",
"(",
")",
":",
"if",
"self",
".",
"verbosity",
">=",
"1",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"self",
".",
"style",
".",
"MIGRATE_HEADING",
"(",
"\"Migrations for '%s':\"",
"%",
"app_label",
")",
")",
"for",
"migration",
"in",
"app_migrations",
":",
"# Describe the migration",
"writer",
"=",
"MigrationWriter",
"(",
"migration",
",",
"self",
".",
"include_header",
")",
"if",
"self",
".",
"verbosity",
">=",
"1",
":",
"# Display a relative path if it's below the current working",
"# directory, or an absolute path otherwise.",
"try",
":",
"migration_string",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"writer",
".",
"path",
")",
"except",
"ValueError",
":",
"migration_string",
"=",
"writer",
".",
"path",
"if",
"migration_string",
".",
"startswith",
"(",
"'..'",
")",
":",
"migration_string",
"=",
"writer",
".",
"path",
"self",
".",
"stdout",
".",
"write",
"(",
"' %s\\n'",
"%",
"self",
".",
"style",
".",
"MIGRATE_LABEL",
"(",
"migration_string",
")",
")",
"for",
"operation",
"in",
"migration",
".",
"operations",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"' - %s'",
"%",
"operation",
".",
"describe",
"(",
")",
")",
"if",
"not",
"self",
".",
"dry_run",
":",
"# Write the migrations file to the disk.",
"migrations_directory",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"writer",
".",
"path",
")",
"if",
"not",
"directory_created",
".",
"get",
"(",
"app_label",
")",
":",
"os",
".",
"makedirs",
"(",
"migrations_directory",
",",
"exist_ok",
"=",
"True",
")",
"init_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"migrations_directory",
",",
"\"__init__.py\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"init_path",
")",
":",
"open",
"(",
"init_path",
",",
"\"w\"",
")",
".",
"close",
"(",
")",
"# We just do this once per app",
"directory_created",
"[",
"app_label",
"]",
"=",
"True",
"migration_string",
"=",
"writer",
".",
"as_string",
"(",
")",
"with",
"open",
"(",
"writer",
".",
"path",
",",
"\"w\"",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"fh",
":",
"fh",
".",
"write",
"(",
"migration_string",
")",
"elif",
"self",
".",
"verbosity",
"==",
"3",
":",
"# Alternatively, makemigrations --dry-run --verbosity 3",
"# will output the migrations to stdout rather than saving",
"# the file to the disk.",
"self",
".",
"stdout",
".",
"write",
"(",
"self",
".",
"style",
".",
"MIGRATE_HEADING",
"(",
"\"Full migrations file '%s':\"",
"%",
"writer",
".",
"filename",
")",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"writer",
".",
"as_string",
"(",
")",
")"
] | [
193,
4
] | [
236,
57
] | python | en | ['en', 'error', 'th'] | False |
Command.handle_merge | (self, loader, conflicts) |
Handles merging together conflicted migrations interactively,
if it's safe; otherwise, advises on how to fix it.
|
Handles merging together conflicted migrations interactively,
if it's safe; otherwise, advises on how to fix it.
| def handle_merge(self, loader, conflicts):
"""
Handles merging together conflicted migrations interactively,
if it's safe; otherwise, advises on how to fix it.
"""
if self.interactive:
questioner = InteractiveMigrationQuestioner()
else:
questioner = MigrationQuestioner(defaults={'ask_merge': True})
for app_label, migration_names in conflicts.items():
# Grab out the migrations in question, and work out their
# common ancestor.
merge_migrations = []
for migration_name in migration_names:
migration = loader.get_migration(app_label, migration_name)
migration.ancestry = [
mig for mig in loader.graph.forwards_plan((app_label, migration_name))
if mig[0] == migration.app_label
]
merge_migrations.append(migration)
def all_items_equal(seq):
return all(item == seq[0] for item in seq[1:])
merge_migrations_generations = zip(*(m.ancestry for m in merge_migrations))
common_ancestor_count = sum(1 for common_ancestor_generation
in takewhile(all_items_equal, merge_migrations_generations))
if not common_ancestor_count:
raise ValueError("Could not find common ancestor of %s" % migration_names)
# Now work out the operations along each divergent branch
for migration in merge_migrations:
migration.branch = migration.ancestry[common_ancestor_count:]
migrations_ops = (loader.get_migration(node_app, node_name).operations
for node_app, node_name in migration.branch)
migration.merged_operations = sum(migrations_ops, [])
# In future, this could use some of the Optimizer code
# (can_optimize_through) to automatically see if they're
# mergeable. For now, we always just prompt the user.
if self.verbosity > 0:
self.stdout.write(self.style.MIGRATE_HEADING("Merging %s" % app_label))
for migration in merge_migrations:
self.stdout.write(self.style.MIGRATE_LABEL(" Branch %s" % migration.name))
for operation in migration.merged_operations:
self.stdout.write(' - %s' % operation.describe())
if questioner.ask_merge(app_label):
# If they still want to merge it, then write out an empty
# file depending on the migrations needing merging.
numbers = [
MigrationAutodetector.parse_number(migration.name)
for migration in merge_migrations
]
try:
biggest_number = max(x for x in numbers if x is not None)
except ValueError:
biggest_number = 1
subclass = type("Migration", (Migration,), {
"dependencies": [(app_label, migration.name) for migration in merge_migrations],
})
parts = ['%04i' % (biggest_number + 1)]
if self.migration_name:
parts.append(self.migration_name)
else:
parts.append('merge')
leaf_names = '_'.join(sorted(migration.name for migration in merge_migrations))
if len(leaf_names) > 47:
parts.append(get_migration_name_timestamp())
else:
parts.append(leaf_names)
migration_name = '_'.join(parts)
new_migration = subclass(migration_name, app_label)
writer = MigrationWriter(new_migration, self.include_header)
if not self.dry_run:
# Write the merge migrations file to the disk
with open(writer.path, "w", encoding='utf-8') as fh:
fh.write(writer.as_string())
if self.verbosity > 0:
self.stdout.write("\nCreated new merge migration %s" % writer.path)
elif self.verbosity == 3:
# Alternatively, makemigrations --merge --dry-run --verbosity 3
# will output the merge migrations to stdout rather than saving
# the file to the disk.
self.stdout.write(self.style.MIGRATE_HEADING(
"Full merge migrations file '%s':" % writer.filename
))
self.stdout.write(writer.as_string()) | [
"def",
"handle_merge",
"(",
"self",
",",
"loader",
",",
"conflicts",
")",
":",
"if",
"self",
".",
"interactive",
":",
"questioner",
"=",
"InteractiveMigrationQuestioner",
"(",
")",
"else",
":",
"questioner",
"=",
"MigrationQuestioner",
"(",
"defaults",
"=",
"{",
"'ask_merge'",
":",
"True",
"}",
")",
"for",
"app_label",
",",
"migration_names",
"in",
"conflicts",
".",
"items",
"(",
")",
":",
"# Grab out the migrations in question, and work out their",
"# common ancestor.",
"merge_migrations",
"=",
"[",
"]",
"for",
"migration_name",
"in",
"migration_names",
":",
"migration",
"=",
"loader",
".",
"get_migration",
"(",
"app_label",
",",
"migration_name",
")",
"migration",
".",
"ancestry",
"=",
"[",
"mig",
"for",
"mig",
"in",
"loader",
".",
"graph",
".",
"forwards_plan",
"(",
"(",
"app_label",
",",
"migration_name",
")",
")",
"if",
"mig",
"[",
"0",
"]",
"==",
"migration",
".",
"app_label",
"]",
"merge_migrations",
".",
"append",
"(",
"migration",
")",
"def",
"all_items_equal",
"(",
"seq",
")",
":",
"return",
"all",
"(",
"item",
"==",
"seq",
"[",
"0",
"]",
"for",
"item",
"in",
"seq",
"[",
"1",
":",
"]",
")",
"merge_migrations_generations",
"=",
"zip",
"(",
"*",
"(",
"m",
".",
"ancestry",
"for",
"m",
"in",
"merge_migrations",
")",
")",
"common_ancestor_count",
"=",
"sum",
"(",
"1",
"for",
"common_ancestor_generation",
"in",
"takewhile",
"(",
"all_items_equal",
",",
"merge_migrations_generations",
")",
")",
"if",
"not",
"common_ancestor_count",
":",
"raise",
"ValueError",
"(",
"\"Could not find common ancestor of %s\"",
"%",
"migration_names",
")",
"# Now work out the operations along each divergent branch",
"for",
"migration",
"in",
"merge_migrations",
":",
"migration",
".",
"branch",
"=",
"migration",
".",
"ancestry",
"[",
"common_ancestor_count",
":",
"]",
"migrations_ops",
"=",
"(",
"loader",
".",
"get_migration",
"(",
"node_app",
",",
"node_name",
")",
".",
"operations",
"for",
"node_app",
",",
"node_name",
"in",
"migration",
".",
"branch",
")",
"migration",
".",
"merged_operations",
"=",
"sum",
"(",
"migrations_ops",
",",
"[",
"]",
")",
"# In future, this could use some of the Optimizer code",
"# (can_optimize_through) to automatically see if they're",
"# mergeable. For now, we always just prompt the user.",
"if",
"self",
".",
"verbosity",
">",
"0",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"self",
".",
"style",
".",
"MIGRATE_HEADING",
"(",
"\"Merging %s\"",
"%",
"app_label",
")",
")",
"for",
"migration",
"in",
"merge_migrations",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"self",
".",
"style",
".",
"MIGRATE_LABEL",
"(",
"\" Branch %s\"",
"%",
"migration",
".",
"name",
")",
")",
"for",
"operation",
"in",
"migration",
".",
"merged_operations",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"' - %s'",
"%",
"operation",
".",
"describe",
"(",
")",
")",
"if",
"questioner",
".",
"ask_merge",
"(",
"app_label",
")",
":",
"# If they still want to merge it, then write out an empty",
"# file depending on the migrations needing merging.",
"numbers",
"=",
"[",
"MigrationAutodetector",
".",
"parse_number",
"(",
"migration",
".",
"name",
")",
"for",
"migration",
"in",
"merge_migrations",
"]",
"try",
":",
"biggest_number",
"=",
"max",
"(",
"x",
"for",
"x",
"in",
"numbers",
"if",
"x",
"is",
"not",
"None",
")",
"except",
"ValueError",
":",
"biggest_number",
"=",
"1",
"subclass",
"=",
"type",
"(",
"\"Migration\"",
",",
"(",
"Migration",
",",
")",
",",
"{",
"\"dependencies\"",
":",
"[",
"(",
"app_label",
",",
"migration",
".",
"name",
")",
"for",
"migration",
"in",
"merge_migrations",
"]",
",",
"}",
")",
"parts",
"=",
"[",
"'%04i'",
"%",
"(",
"biggest_number",
"+",
"1",
")",
"]",
"if",
"self",
".",
"migration_name",
":",
"parts",
".",
"append",
"(",
"self",
".",
"migration_name",
")",
"else",
":",
"parts",
".",
"append",
"(",
"'merge'",
")",
"leaf_names",
"=",
"'_'",
".",
"join",
"(",
"sorted",
"(",
"migration",
".",
"name",
"for",
"migration",
"in",
"merge_migrations",
")",
")",
"if",
"len",
"(",
"leaf_names",
")",
">",
"47",
":",
"parts",
".",
"append",
"(",
"get_migration_name_timestamp",
"(",
")",
")",
"else",
":",
"parts",
".",
"append",
"(",
"leaf_names",
")",
"migration_name",
"=",
"'_'",
".",
"join",
"(",
"parts",
")",
"new_migration",
"=",
"subclass",
"(",
"migration_name",
",",
"app_label",
")",
"writer",
"=",
"MigrationWriter",
"(",
"new_migration",
",",
"self",
".",
"include_header",
")",
"if",
"not",
"self",
".",
"dry_run",
":",
"# Write the merge migrations file to the disk",
"with",
"open",
"(",
"writer",
".",
"path",
",",
"\"w\"",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"fh",
":",
"fh",
".",
"write",
"(",
"writer",
".",
"as_string",
"(",
")",
")",
"if",
"self",
".",
"verbosity",
">",
"0",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"\"\\nCreated new merge migration %s\"",
"%",
"writer",
".",
"path",
")",
"elif",
"self",
".",
"verbosity",
"==",
"3",
":",
"# Alternatively, makemigrations --merge --dry-run --verbosity 3",
"# will output the merge migrations to stdout rather than saving",
"# the file to the disk.",
"self",
".",
"stdout",
".",
"write",
"(",
"self",
".",
"style",
".",
"MIGRATE_HEADING",
"(",
"\"Full merge migrations file '%s':\"",
"%",
"writer",
".",
"filename",
")",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"writer",
".",
"as_string",
"(",
")",
")"
] | [
238,
4
] | [
324,
57
] | python | en | ['en', 'error', 'th'] | False |
matches_patterns | (path, patterns) |
Return True or False depending on whether the ``path`` should be
ignored (if it matches any pattern in ``ignore_patterns``).
|
Return True or False depending on whether the ``path`` should be
ignored (if it matches any pattern in ``ignore_patterns``).
| def matches_patterns(path, patterns):
"""
Return True or False depending on whether the ``path`` should be
ignored (if it matches any pattern in ``ignore_patterns``).
"""
return any(fnmatch.fnmatchcase(path, pattern) for pattern in patterns) | [
"def",
"matches_patterns",
"(",
"path",
",",
"patterns",
")",
":",
"return",
"any",
"(",
"fnmatch",
".",
"fnmatchcase",
"(",
"path",
",",
"pattern",
")",
"for",
"pattern",
"in",
"patterns",
")"
] | [
7,
0
] | [
12,
74
] | python | en | ['en', 'error', 'th'] | False |
get_files | (storage, ignore_patterns=None, location='') |
Recursively walk the storage directories yielding the paths
of all files that should be copied.
|
Recursively walk the storage directories yielding the paths
of all files that should be copied.
| def get_files(storage, ignore_patterns=None, location=''):
"""
Recursively walk the storage directories yielding the paths
of all files that should be copied.
"""
if ignore_patterns is None:
ignore_patterns = []
directories, files = storage.listdir(location)
for fn in files:
# Match only the basename.
if matches_patterns(fn, ignore_patterns):
continue
if location:
fn = os.path.join(location, fn)
# Match the full file path.
if matches_patterns(fn, ignore_patterns):
continue
yield fn
for dir in directories:
if matches_patterns(dir, ignore_patterns):
continue
if location:
dir = os.path.join(location, dir)
yield from get_files(storage, ignore_patterns, dir) | [
"def",
"get_files",
"(",
"storage",
",",
"ignore_patterns",
"=",
"None",
",",
"location",
"=",
"''",
")",
":",
"if",
"ignore_patterns",
"is",
"None",
":",
"ignore_patterns",
"=",
"[",
"]",
"directories",
",",
"files",
"=",
"storage",
".",
"listdir",
"(",
"location",
")",
"for",
"fn",
"in",
"files",
":",
"# Match only the basename.",
"if",
"matches_patterns",
"(",
"fn",
",",
"ignore_patterns",
")",
":",
"continue",
"if",
"location",
":",
"fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"location",
",",
"fn",
")",
"# Match the full file path.",
"if",
"matches_patterns",
"(",
"fn",
",",
"ignore_patterns",
")",
":",
"continue",
"yield",
"fn",
"for",
"dir",
"in",
"directories",
":",
"if",
"matches_patterns",
"(",
"dir",
",",
"ignore_patterns",
")",
":",
"continue",
"if",
"location",
":",
"dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"location",
",",
"dir",
")",
"yield",
"from",
"get_files",
"(",
"storage",
",",
"ignore_patterns",
",",
"dir",
")"
] | [
15,
0
] | [
38,
59
] | python | en | ['en', 'error', 'th'] | False |
check_settings | (base_url=None) |
Check if the staticfiles settings have sane values.
|
Check if the staticfiles settings have sane values.
| def check_settings(base_url=None):
"""
Check if the staticfiles settings have sane values.
"""
if base_url is None:
base_url = settings.STATIC_URL
if not base_url:
raise ImproperlyConfigured(
"You're using the staticfiles app "
"without having set the required STATIC_URL setting.")
if settings.MEDIA_URL == base_url:
raise ImproperlyConfigured("The MEDIA_URL and STATIC_URL "
"settings must have different values")
if (settings.DEBUG and settings.MEDIA_URL and settings.STATIC_URL and
settings.MEDIA_URL.startswith(settings.STATIC_URL)):
raise ImproperlyConfigured(
"runserver can't serve media if MEDIA_URL is within STATIC_URL."
)
if ((settings.MEDIA_ROOT and settings.STATIC_ROOT) and
(settings.MEDIA_ROOT == settings.STATIC_ROOT)):
raise ImproperlyConfigured("The MEDIA_ROOT and STATIC_ROOT "
"settings must have different values") | [
"def",
"check_settings",
"(",
"base_url",
"=",
"None",
")",
":",
"if",
"base_url",
"is",
"None",
":",
"base_url",
"=",
"settings",
".",
"STATIC_URL",
"if",
"not",
"base_url",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"You're using the staticfiles app \"",
"\"without having set the required STATIC_URL setting.\"",
")",
"if",
"settings",
".",
"MEDIA_URL",
"==",
"base_url",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"The MEDIA_URL and STATIC_URL \"",
"\"settings must have different values\"",
")",
"if",
"(",
"settings",
".",
"DEBUG",
"and",
"settings",
".",
"MEDIA_URL",
"and",
"settings",
".",
"STATIC_URL",
"and",
"settings",
".",
"MEDIA_URL",
".",
"startswith",
"(",
"settings",
".",
"STATIC_URL",
")",
")",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"runserver can't serve media if MEDIA_URL is within STATIC_URL.\"",
")",
"if",
"(",
"(",
"settings",
".",
"MEDIA_ROOT",
"and",
"settings",
".",
"STATIC_ROOT",
")",
"and",
"(",
"settings",
".",
"MEDIA_ROOT",
"==",
"settings",
".",
"STATIC_ROOT",
")",
")",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"The MEDIA_ROOT and STATIC_ROOT \"",
"\"settings must have different values\"",
")"
] | [
41,
0
] | [
62,
73
] | python | en | ['en', 'error', 'th'] | False |
freeze_base | (model) |
Our models are build in such way that a backbone model is a layer in the final model.
This function finds the model and freezes it,
Do not forget to compile your model after freezing!
:param model: model which base will be frozen
:return Whether the base was found and frozen.
|
Our models are build in such way that a backbone model is a layer in the final model.
This function finds the model and freezes it, | def freeze_base(model):
"""
Our models are build in such way that a backbone model is a layer in the final model.
This function finds the model and freezes it,
Do not forget to compile your model after freezing!
:param model: model which base will be frozen
:return Whether the base was found and frozen.
"""
return unfreeze_base(model, 0) | [
"def",
"freeze_base",
"(",
"model",
")",
":",
"return",
"unfreeze_base",
"(",
"model",
",",
"0",
")"
] | [
3,
0
] | [
13,
34
] | python | en | ['en', 'error', 'th'] | False |
unfreeze_base | (model, fraction=1.0) |
Make the full model trainable. If there is a model inside the the layers, all is unfroze.
Do not forget to compile your model after freezing!
:param model: model which base will be (partially) frozen
:param fraction: how many layers from top should be unfroze
:return Whether the base was found and frozen.
|
Make the full model trainable. If there is a model inside the the layers, all is unfroze. | def unfreeze_base(model, fraction=1.0):
"""
Make the full model trainable. If there is a model inside the the layers, all is unfroze.
Do not forget to compile your model after freezing!
:param model: model which base will be (partially) frozen
:param fraction: how many layers from top should be unfroze
:return Whether the base was found and frozen.
"""
base = None
for id, layer in enumerate(model.layers):
if isinstance(layer, tf.keras.Model):
base = layer
break
if not base:
return False
frozed_layers = int(len(base.layers) * (1.0 - fraction))
for id, layer in enumerate(base.layers):
layer.trainable = id >= frozed_layers
return True | [
"def",
"unfreeze_base",
"(",
"model",
",",
"fraction",
"=",
"1.0",
")",
":",
"base",
"=",
"None",
"for",
"id",
",",
"layer",
"in",
"enumerate",
"(",
"model",
".",
"layers",
")",
":",
"if",
"isinstance",
"(",
"layer",
",",
"tf",
".",
"keras",
".",
"Model",
")",
":",
"base",
"=",
"layer",
"break",
"if",
"not",
"base",
":",
"return",
"False",
"frozed_layers",
"=",
"int",
"(",
"len",
"(",
"base",
".",
"layers",
")",
"*",
"(",
"1.0",
"-",
"fraction",
")",
")",
"for",
"id",
",",
"layer",
"in",
"enumerate",
"(",
"base",
".",
"layers",
")",
":",
"layer",
".",
"trainable",
"=",
"id",
">=",
"frozed_layers",
"return",
"True"
] | [
16,
0
] | [
39,
15
] | python | en | ['en', 'error', 'th'] | False |
parse_cookie | (cookie) |
Return a dictionary parsed from a `Cookie:` header string.
|
Return a dictionary parsed from a `Cookie:` header string.
| def parse_cookie(cookie):
"""
Return a dictionary parsed from a `Cookie:` header string.
"""
cookiedict = {}
for chunk in cookie.split(';'):
if '=' in chunk:
key, val = chunk.split('=', 1)
else:
# Assume an empty name per
# https://bugzilla.mozilla.org/show_bug.cgi?id=169091
key, val = '', chunk
key, val = key.strip(), val.strip()
if key or val:
# unquote using Python's algorithm.
cookiedict[key] = cookies._unquote(val)
return cookiedict | [
"def",
"parse_cookie",
"(",
"cookie",
")",
":",
"cookiedict",
"=",
"{",
"}",
"for",
"chunk",
"in",
"cookie",
".",
"split",
"(",
"';'",
")",
":",
"if",
"'='",
"in",
"chunk",
":",
"key",
",",
"val",
"=",
"chunk",
".",
"split",
"(",
"'='",
",",
"1",
")",
"else",
":",
"# Assume an empty name per",
"# https://bugzilla.mozilla.org/show_bug.cgi?id=169091",
"key",
",",
"val",
"=",
"''",
",",
"chunk",
"key",
",",
"val",
"=",
"key",
".",
"strip",
"(",
")",
",",
"val",
".",
"strip",
"(",
")",
"if",
"key",
"or",
"val",
":",
"# unquote using Python's algorithm.",
"cookiedict",
"[",
"key",
"]",
"=",
"cookies",
".",
"_unquote",
"(",
"val",
")",
"return",
"cookiedict"
] | [
9,
0
] | [
25,
21
] | python | en | ['en', 'error', 'th'] | False |
parse_arguments | () | Parse job arguments. | Parse job arguments. | def parse_arguments():
"""Parse job arguments."""
parser = argparse.ArgumentParser()
# required input arguments
parser.add_argument(
'--train-files',
help='GCS or local paths to training data',
nargs='+',
required=True
)
parser.add_argument(
'--job-dir',
help='GCS location to write checkpoints and export models',
required=True
)
# hyper params for model
parser.add_argument(
'--latent_factors',
type=int,
help='Number of latent factors',
)
parser.add_argument(
'--num_iters',
type=int,
help='Number of iterations for alternating least squares factorization',
)
parser.add_argument(
'--regularization',
type=float,
help='L2 regularization factor',
)
parser.add_argument(
'--unobs_weight',
type=float,
help='Weight for unobserved values',
)
parser.add_argument(
'--wt_type',
type=int,
help='Rating weight type (0=linear, 1=log)',
default=wals.LINEAR_RATINGS
)
parser.add_argument(
'--feature_wt_factor',
type=float,
help='Feature weight factor (linear ratings)',
)
parser.add_argument(
'--feature_wt_exp',
type=float,
help='Feature weight exponent (log ratings)',
)
# other args
parser.add_argument(
'--output-dir',
help='GCS location to write model, overriding job-dir',
)
parser.add_argument(
'--verbose-logging',
default=False,
action='store_true',
help='Switch to turn on or off verbose logging and warnings'
)
parser.add_argument(
'--hypertune',
default=False,
action='store_true',
help='Switch to turn on or off hyperparam tuning'
)
parser.add_argument(
'--data-type',
type=str,
default='ratings',
help='Data type, one of ratings (e.g. MovieLens) or web_views (GA data)'
)
parser.add_argument(
'--delimiter',
type=str,
default='\t',
help='Delimiter for csv data files'
)
parser.add_argument(
'--headers',
default=False,
action='store_true',
help='Input file has a header row'
)
parser.add_argument(
'--use-optimized',
default=False,
action='store_true',
help='Use optimized hyperparameters'
)
args = parser.parse_args()
arguments = args.__dict__
# set job name as job directory name
job_dir = args.job_dir
job_dir = job_dir[:-1] if job_dir.endswith('/') else job_dir
job_name = os.path.basename(job_dir)
# set output directory for model
if args.hypertune:
# if tuning, join the trial number to the output path
config = json.loads(os.environ.get('TF_CONFIG', '{}'))
trial = config.get('task', {}).get('trial', '')
output_dir = os.path.join(job_dir, trial)
elif args.output_dir:
output_dir = args.output_dir
else:
output_dir = job_dir
if args.verbose_logging:
tf.logging.set_verbosity(tf.logging.INFO)
# Find out if there's a task value on the environment variable.
# If there is none or it is empty define a default one.
env = json.loads(os.environ.get('TF_CONFIG', '{}'))
task_data = env.get('task') or {'type': 'master', 'index': 0}
# update default params with any args provided to task
params = model.DEFAULT_PARAMS
params.update({k: arg for k, arg in arguments.iteritems() if arg is not None})
if args.use_optimized:
if args.data_type == 'web_views':
params.update(model.OPTIMIZED_PARAMS_WEB)
else:
params.update(model.OPTIMIZED_PARAMS)
params.update(task_data)
params.update({'output_dir': output_dir})
params.update({'job_name': job_name})
# For web_view data, default to using the exponential weight formula
# with feature weight exp.
# For movie lens data, default to the linear weight formula.
if args.data_type == 'web_views':
params.update({'wt_type': wals.LOG_RATINGS})
return params | [
"def",
"parse_arguments",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"# required input arguments",
"parser",
".",
"add_argument",
"(",
"'--train-files'",
",",
"help",
"=",
"'GCS or local paths to training data'",
",",
"nargs",
"=",
"'+'",
",",
"required",
"=",
"True",
")",
"parser",
".",
"add_argument",
"(",
"'--job-dir'",
",",
"help",
"=",
"'GCS location to write checkpoints and export models'",
",",
"required",
"=",
"True",
")",
"# hyper params for model",
"parser",
".",
"add_argument",
"(",
"'--latent_factors'",
",",
"type",
"=",
"int",
",",
"help",
"=",
"'Number of latent factors'",
",",
")",
"parser",
".",
"add_argument",
"(",
"'--num_iters'",
",",
"type",
"=",
"int",
",",
"help",
"=",
"'Number of iterations for alternating least squares factorization'",
",",
")",
"parser",
".",
"add_argument",
"(",
"'--regularization'",
",",
"type",
"=",
"float",
",",
"help",
"=",
"'L2 regularization factor'",
",",
")",
"parser",
".",
"add_argument",
"(",
"'--unobs_weight'",
",",
"type",
"=",
"float",
",",
"help",
"=",
"'Weight for unobserved values'",
",",
")",
"parser",
".",
"add_argument",
"(",
"'--wt_type'",
",",
"type",
"=",
"int",
",",
"help",
"=",
"'Rating weight type (0=linear, 1=log)'",
",",
"default",
"=",
"wals",
".",
"LINEAR_RATINGS",
")",
"parser",
".",
"add_argument",
"(",
"'--feature_wt_factor'",
",",
"type",
"=",
"float",
",",
"help",
"=",
"'Feature weight factor (linear ratings)'",
",",
")",
"parser",
".",
"add_argument",
"(",
"'--feature_wt_exp'",
",",
"type",
"=",
"float",
",",
"help",
"=",
"'Feature weight exponent (log ratings)'",
",",
")",
"# other args",
"parser",
".",
"add_argument",
"(",
"'--output-dir'",
",",
"help",
"=",
"'GCS location to write model, overriding job-dir'",
",",
")",
"parser",
".",
"add_argument",
"(",
"'--verbose-logging'",
",",
"default",
"=",
"False",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'Switch to turn on or off verbose logging and warnings'",
")",
"parser",
".",
"add_argument",
"(",
"'--hypertune'",
",",
"default",
"=",
"False",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'Switch to turn on or off hyperparam tuning'",
")",
"parser",
".",
"add_argument",
"(",
"'--data-type'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'ratings'",
",",
"help",
"=",
"'Data type, one of ratings (e.g. MovieLens) or web_views (GA data)'",
")",
"parser",
".",
"add_argument",
"(",
"'--delimiter'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'\\t'",
",",
"help",
"=",
"'Delimiter for csv data files'",
")",
"parser",
".",
"add_argument",
"(",
"'--headers'",
",",
"default",
"=",
"False",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'Input file has a header row'",
")",
"parser",
".",
"add_argument",
"(",
"'--use-optimized'",
",",
"default",
"=",
"False",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'Use optimized hyperparameters'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"arguments",
"=",
"args",
".",
"__dict__",
"# set job name as job directory name",
"job_dir",
"=",
"args",
".",
"job_dir",
"job_dir",
"=",
"job_dir",
"[",
":",
"-",
"1",
"]",
"if",
"job_dir",
".",
"endswith",
"(",
"'/'",
")",
"else",
"job_dir",
"job_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"job_dir",
")",
"# set output directory for model",
"if",
"args",
".",
"hypertune",
":",
"# if tuning, join the trial number to the output path",
"config",
"=",
"json",
".",
"loads",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'TF_CONFIG'",
",",
"'{}'",
")",
")",
"trial",
"=",
"config",
".",
"get",
"(",
"'task'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'trial'",
",",
"''",
")",
"output_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"job_dir",
",",
"trial",
")",
"elif",
"args",
".",
"output_dir",
":",
"output_dir",
"=",
"args",
".",
"output_dir",
"else",
":",
"output_dir",
"=",
"job_dir",
"if",
"args",
".",
"verbose_logging",
":",
"tf",
".",
"logging",
".",
"set_verbosity",
"(",
"tf",
".",
"logging",
".",
"INFO",
")",
"# Find out if there's a task value on the environment variable.",
"# If there is none or it is empty define a default one.",
"env",
"=",
"json",
".",
"loads",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'TF_CONFIG'",
",",
"'{}'",
")",
")",
"task_data",
"=",
"env",
".",
"get",
"(",
"'task'",
")",
"or",
"{",
"'type'",
":",
"'master'",
",",
"'index'",
":",
"0",
"}",
"# update default params with any args provided to task",
"params",
"=",
"model",
".",
"DEFAULT_PARAMS",
"params",
".",
"update",
"(",
"{",
"k",
":",
"arg",
"for",
"k",
",",
"arg",
"in",
"arguments",
".",
"iteritems",
"(",
")",
"if",
"arg",
"is",
"not",
"None",
"}",
")",
"if",
"args",
".",
"use_optimized",
":",
"if",
"args",
".",
"data_type",
"==",
"'web_views'",
":",
"params",
".",
"update",
"(",
"model",
".",
"OPTIMIZED_PARAMS_WEB",
")",
"else",
":",
"params",
".",
"update",
"(",
"model",
".",
"OPTIMIZED_PARAMS",
")",
"params",
".",
"update",
"(",
"task_data",
")",
"params",
".",
"update",
"(",
"{",
"'output_dir'",
":",
"output_dir",
"}",
")",
"params",
".",
"update",
"(",
"{",
"'job_name'",
":",
"job_name",
"}",
")",
"# For web_view data, default to using the exponential weight formula",
"# with feature weight exp.",
"# For movie lens data, default to the linear weight formula.",
"if",
"args",
".",
"data_type",
"==",
"'web_views'",
":",
"params",
".",
"update",
"(",
"{",
"'wt_type'",
":",
"wals",
".",
"LOG_RATINGS",
"}",
")",
"return",
"params"
] | [
50,
0
] | [
192,
15
] | python | en | ['en', 'fr', 'en'] | True |
lazy | (func, *resultclasses) |
Turn any callable into a lazy evaluated callable. result classes or types
is required -- at least one is needed so that the automatic forcing of
the lazy evaluation code is triggered. Results are not memoized; the
function is evaluated on every access.
|
Turn any callable into a lazy evaluated callable. result classes or types
is required -- at least one is needed so that the automatic forcing of
the lazy evaluation code is triggered. Results are not memoized; the
function is evaluated on every access.
| def lazy(func, *resultclasses):
"""
Turn any callable into a lazy evaluated callable. result classes or types
is required -- at least one is needed so that the automatic forcing of
the lazy evaluation code is triggered. Results are not memoized; the
function is evaluated on every access.
"""
@total_ordering
class __proxy__(Promise):
"""
Encapsulate a function call and act as a proxy for methods that are
called on the result of that function. The function is not evaluated
until one of the methods on the result is called.
"""
__prepared = False
def __init__(self, args, kw):
self.__args = args
self.__kw = kw
if not self.__prepared:
self.__prepare_class__()
self.__class__.__prepared = True
def __reduce__(self):
return (
_lazy_proxy_unpickle,
(func, self.__args, self.__kw) + resultclasses
)
def __repr__(self):
return repr(self.__cast())
@classmethod
def __prepare_class__(cls):
for resultclass in resultclasses:
for type_ in resultclass.mro():
for method_name in type_.__dict__:
# All __promise__ return the same wrapper method, they
# look up the correct implementation when called.
if hasattr(cls, method_name):
continue
meth = cls.__promise__(method_name)
setattr(cls, method_name, meth)
cls._delegate_bytes = bytes in resultclasses
cls._delegate_text = str in resultclasses
assert not (cls._delegate_bytes and cls._delegate_text), (
"Cannot call lazy() with both bytes and text return types.")
if cls._delegate_text:
cls.__str__ = cls.__text_cast
elif cls._delegate_bytes:
cls.__bytes__ = cls.__bytes_cast
@classmethod
def __promise__(cls, method_name):
# Builds a wrapper around some magic method
def __wrapper__(self, *args, **kw):
# Automatically triggers the evaluation of a lazy value and
# applies the given magic method of the result type.
res = func(*self.__args, **self.__kw)
return getattr(res, method_name)(*args, **kw)
return __wrapper__
def __text_cast(self):
return func(*self.__args, **self.__kw)
def __bytes_cast(self):
return bytes(func(*self.__args, **self.__kw))
def __bytes_cast_encoded(self):
return func(*self.__args, **self.__kw).encode()
def __cast(self):
if self._delegate_bytes:
return self.__bytes_cast()
elif self._delegate_text:
return self.__text_cast()
else:
return func(*self.__args, **self.__kw)
def __str__(self):
# object defines __str__(), so __prepare_class__() won't overload
# a __str__() method from the proxied class.
return str(self.__cast())
def __eq__(self, other):
if isinstance(other, Promise):
other = other.__cast()
return self.__cast() == other
def __lt__(self, other):
if isinstance(other, Promise):
other = other.__cast()
return self.__cast() < other
def __hash__(self):
return hash(self.__cast())
def __mod__(self, rhs):
if self._delegate_text:
return str(self) % rhs
return self.__cast() % rhs
def __add__(self, other):
return self.__cast() + other
def __radd__(self, other):
return other + self.__cast()
def __deepcopy__(self, memo):
# Instances of this class are effectively immutable. It's just a
# collection of functions. So we don't need to do anything
# complicated for copying.
memo[id(self)] = self
return self
@wraps(func)
def __wrapper__(*args, **kw):
# Creates the proxy object, instead of the actual value.
return __proxy__(args, kw)
return __wrapper__ | [
"def",
"lazy",
"(",
"func",
",",
"*",
"resultclasses",
")",
":",
"@",
"total_ordering",
"class",
"__proxy__",
"(",
"Promise",
")",
":",
"\"\"\"\n Encapsulate a function call and act as a proxy for methods that are\n called on the result of that function. The function is not evaluated\n until one of the methods on the result is called.\n \"\"\"",
"__prepared",
"=",
"False",
"def",
"__init__",
"(",
"self",
",",
"args",
",",
"kw",
")",
":",
"self",
".",
"__args",
"=",
"args",
"self",
".",
"__kw",
"=",
"kw",
"if",
"not",
"self",
".",
"__prepared",
":",
"self",
".",
"__prepare_class__",
"(",
")",
"self",
".",
"__class__",
".",
"__prepared",
"=",
"True",
"def",
"__reduce__",
"(",
"self",
")",
":",
"return",
"(",
"_lazy_proxy_unpickle",
",",
"(",
"func",
",",
"self",
".",
"__args",
",",
"self",
".",
"__kw",
")",
"+",
"resultclasses",
")",
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"repr",
"(",
"self",
".",
"__cast",
"(",
")",
")",
"@",
"classmethod",
"def",
"__prepare_class__",
"(",
"cls",
")",
":",
"for",
"resultclass",
"in",
"resultclasses",
":",
"for",
"type_",
"in",
"resultclass",
".",
"mro",
"(",
")",
":",
"for",
"method_name",
"in",
"type_",
".",
"__dict__",
":",
"# All __promise__ return the same wrapper method, they",
"# look up the correct implementation when called.",
"if",
"hasattr",
"(",
"cls",
",",
"method_name",
")",
":",
"continue",
"meth",
"=",
"cls",
".",
"__promise__",
"(",
"method_name",
")",
"setattr",
"(",
"cls",
",",
"method_name",
",",
"meth",
")",
"cls",
".",
"_delegate_bytes",
"=",
"bytes",
"in",
"resultclasses",
"cls",
".",
"_delegate_text",
"=",
"str",
"in",
"resultclasses",
"assert",
"not",
"(",
"cls",
".",
"_delegate_bytes",
"and",
"cls",
".",
"_delegate_text",
")",
",",
"(",
"\"Cannot call lazy() with both bytes and text return types.\"",
")",
"if",
"cls",
".",
"_delegate_text",
":",
"cls",
".",
"__str__",
"=",
"cls",
".",
"__text_cast",
"elif",
"cls",
".",
"_delegate_bytes",
":",
"cls",
".",
"__bytes__",
"=",
"cls",
".",
"__bytes_cast",
"@",
"classmethod",
"def",
"__promise__",
"(",
"cls",
",",
"method_name",
")",
":",
"# Builds a wrapper around some magic method",
"def",
"__wrapper__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# Automatically triggers the evaluation of a lazy value and",
"# applies the given magic method of the result type.",
"res",
"=",
"func",
"(",
"*",
"self",
".",
"__args",
",",
"*",
"*",
"self",
".",
"__kw",
")",
"return",
"getattr",
"(",
"res",
",",
"method_name",
")",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"return",
"__wrapper__",
"def",
"__text_cast",
"(",
"self",
")",
":",
"return",
"func",
"(",
"*",
"self",
".",
"__args",
",",
"*",
"*",
"self",
".",
"__kw",
")",
"def",
"__bytes_cast",
"(",
"self",
")",
":",
"return",
"bytes",
"(",
"func",
"(",
"*",
"self",
".",
"__args",
",",
"*",
"*",
"self",
".",
"__kw",
")",
")",
"def",
"__bytes_cast_encoded",
"(",
"self",
")",
":",
"return",
"func",
"(",
"*",
"self",
".",
"__args",
",",
"*",
"*",
"self",
".",
"__kw",
")",
".",
"encode",
"(",
")",
"def",
"__cast",
"(",
"self",
")",
":",
"if",
"self",
".",
"_delegate_bytes",
":",
"return",
"self",
".",
"__bytes_cast",
"(",
")",
"elif",
"self",
".",
"_delegate_text",
":",
"return",
"self",
".",
"__text_cast",
"(",
")",
"else",
":",
"return",
"func",
"(",
"*",
"self",
".",
"__args",
",",
"*",
"*",
"self",
".",
"__kw",
")",
"def",
"__str__",
"(",
"self",
")",
":",
"# object defines __str__(), so __prepare_class__() won't overload",
"# a __str__() method from the proxied class.",
"return",
"str",
"(",
"self",
".",
"__cast",
"(",
")",
")",
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"Promise",
")",
":",
"other",
"=",
"other",
".",
"__cast",
"(",
")",
"return",
"self",
".",
"__cast",
"(",
")",
"==",
"other",
"def",
"__lt__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"Promise",
")",
":",
"other",
"=",
"other",
".",
"__cast",
"(",
")",
"return",
"self",
".",
"__cast",
"(",
")",
"<",
"other",
"def",
"__hash__",
"(",
"self",
")",
":",
"return",
"hash",
"(",
"self",
".",
"__cast",
"(",
")",
")",
"def",
"__mod__",
"(",
"self",
",",
"rhs",
")",
":",
"if",
"self",
".",
"_delegate_text",
":",
"return",
"str",
"(",
"self",
")",
"%",
"rhs",
"return",
"self",
".",
"__cast",
"(",
")",
"%",
"rhs",
"def",
"__add__",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"__cast",
"(",
")",
"+",
"other",
"def",
"__radd__",
"(",
"self",
",",
"other",
")",
":",
"return",
"other",
"+",
"self",
".",
"__cast",
"(",
")",
"def",
"__deepcopy__",
"(",
"self",
",",
"memo",
")",
":",
"# Instances of this class are effectively immutable. It's just a",
"# collection of functions. So we don't need to do anything",
"# complicated for copying.",
"memo",
"[",
"id",
"(",
"self",
")",
"]",
"=",
"self",
"return",
"self",
"@",
"wraps",
"(",
"func",
")",
"def",
"__wrapper__",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# Creates the proxy object, instead of the actual value.",
"return",
"__proxy__",
"(",
"args",
",",
"kw",
")",
"return",
"__wrapper__"
] | [
75,
0
] | [
196,
22
] | python | en | ['en', 'error', 'th'] | False |
lazystr | (text) |
Shortcut for the common case of a lazy callable that returns str.
|
Shortcut for the common case of a lazy callable that returns str.
| def lazystr(text):
"""
Shortcut for the common case of a lazy callable that returns str.
"""
return lazy(str, str)(text) | [
"def",
"lazystr",
"(",
"text",
")",
":",
"return",
"lazy",
"(",
"str",
",",
"str",
")",
"(",
"text",
")"
] | [
203,
0
] | [
207,
31
] | python | en | ['en', 'error', 'th'] | False |
keep_lazy | (*resultclasses) |
A decorator that allows a function to be called with one or more lazy
arguments. If none of the args are lazy, the function is evaluated
immediately, otherwise a __proxy__ is returned that will evaluate the
function when needed.
|
A decorator that allows a function to be called with one or more lazy
arguments. If none of the args are lazy, the function is evaluated
immediately, otherwise a __proxy__ is returned that will evaluate the
function when needed.
| def keep_lazy(*resultclasses):
"""
A decorator that allows a function to be called with one or more lazy
arguments. If none of the args are lazy, the function is evaluated
immediately, otherwise a __proxy__ is returned that will evaluate the
function when needed.
"""
if not resultclasses:
raise TypeError("You must pass at least one argument to keep_lazy().")
def decorator(func):
lazy_func = lazy(func, *resultclasses)
@wraps(func)
def wrapper(*args, **kwargs):
if any(isinstance(arg, Promise) for arg in itertools.chain(args, kwargs.values())):
return lazy_func(*args, **kwargs)
return func(*args, **kwargs)
return wrapper
return decorator | [
"def",
"keep_lazy",
"(",
"*",
"resultclasses",
")",
":",
"if",
"not",
"resultclasses",
":",
"raise",
"TypeError",
"(",
"\"You must pass at least one argument to keep_lazy().\"",
")",
"def",
"decorator",
"(",
"func",
")",
":",
"lazy_func",
"=",
"lazy",
"(",
"func",
",",
"*",
"resultclasses",
")",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"any",
"(",
"isinstance",
"(",
"arg",
",",
"Promise",
")",
"for",
"arg",
"in",
"itertools",
".",
"chain",
"(",
"args",
",",
"kwargs",
".",
"values",
"(",
")",
")",
")",
":",
"return",
"lazy_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper",
"return",
"decorator"
] | [
210,
0
] | [
229,
20
] | python | en | ['en', 'error', 'th'] | False |
keep_lazy_text | (func) |
A decorator for functions that accept lazy arguments and return text.
|
A decorator for functions that accept lazy arguments and return text.
| def keep_lazy_text(func):
"""
A decorator for functions that accept lazy arguments and return text.
"""
return keep_lazy(str)(func) | [
"def",
"keep_lazy_text",
"(",
"func",
")",
":",
"return",
"keep_lazy",
"(",
"str",
")",
"(",
"func",
")"
] | [
232,
0
] | [
236,
31
] | python | en | ['en', 'error', 'th'] | False |
unpickle_lazyobject | (wrapped) |
Used to unpickle lazy objects. Just return its argument, which will be the
wrapped object.
|
Used to unpickle lazy objects. Just return its argument, which will be the
wrapped object.
| def unpickle_lazyobject(wrapped):
"""
Used to unpickle lazy objects. Just return its argument, which will be the
wrapped object.
"""
return wrapped | [
"def",
"unpickle_lazyobject",
"(",
"wrapped",
")",
":",
"return",
"wrapped"
] | [
353,
0
] | [
358,
18
] | python | en | ['en', 'error', 'th'] | False |
partition | (predicate, values) |
Split the values into two sets, based on the return value of the function
(True/False). e.g.:
>>> partition(lambda x: x > 3, range(5))
[0, 1, 2, 3], [4]
|
Split the values into two sets, based on the return value of the function
(True/False). e.g.: | def partition(predicate, values):
"""
Split the values into two sets, based on the return value of the function
(True/False). e.g.:
>>> partition(lambda x: x > 3, range(5))
[0, 1, 2, 3], [4]
"""
results = ([], [])
for item in values:
results[predicate(item)].append(item)
return results | [
"def",
"partition",
"(",
"predicate",
",",
"values",
")",
":",
"results",
"=",
"(",
"[",
"]",
",",
"[",
"]",
")",
"for",
"item",
"in",
"values",
":",
"results",
"[",
"predicate",
"(",
"item",
")",
"]",
".",
"append",
"(",
"item",
")",
"return",
"results"
] | [
411,
0
] | [
422,
18
] | python | en | ['en', 'error', 'th'] | False |
cached_property.__get__ | (self, instance, cls=None) |
Call the function and put the return value in instance.__dict__ so that
subsequent attribute access on the instance returns the cached value
instead of calling cached_property.__get__().
|
Call the function and put the return value in instance.__dict__ so that
subsequent attribute access on the instance returns the cached value
instead of calling cached_property.__get__().
| def __get__(self, instance, cls=None):
"""
Call the function and put the return value in instance.__dict__ so that
subsequent attribute access on the instance returns the cached value
instead of calling cached_property.__get__().
"""
if instance is None:
return self
res = instance.__dict__[self.name] = self.func(instance)
return res | [
"def",
"__get__",
"(",
"self",
",",
"instance",
",",
"cls",
"=",
"None",
")",
":",
"if",
"instance",
"is",
"None",
":",
"return",
"self",
"res",
"=",
"instance",
".",
"__dict__",
"[",
"self",
".",
"name",
"]",
"=",
"self",
".",
"func",
"(",
"instance",
")",
"return",
"res"
] | [
39,
4
] | [
48,
18
] | python | en | ['en', 'error', 'th'] | False |
LazyObject._setup | (self) |
Must be implemented by subclasses to initialize the wrapped object.
|
Must be implemented by subclasses to initialize the wrapped object.
| def _setup(self):
"""
Must be implemented by subclasses to initialize the wrapped object.
"""
raise NotImplementedError('subclasses of LazyObject must provide a _setup() method') | [
"def",
"_setup",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of LazyObject must provide a _setup() method'",
")"
] | [
285,
4
] | [
289,
92
] | python | en | ['en', 'error', 'th'] | False |
SimpleLazyObject.__init__ | (self, func) |
Pass in a callable that returns the object to be wrapped.
If copies are made of the resulting SimpleLazyObject, which can happen
in various circumstances within Django, then you must ensure that the
callable can be safely run more than once and will return the same
value.
|
Pass in a callable that returns the object to be wrapped. | def __init__(self, func):
"""
Pass in a callable that returns the object to be wrapped.
If copies are made of the resulting SimpleLazyObject, which can happen
in various circumstances within Django, then you must ensure that the
callable can be safely run more than once and will return the same
value.
"""
self.__dict__['_setupfunc'] = func
super().__init__() | [
"def",
"__init__",
"(",
"self",
",",
"func",
")",
":",
"self",
".",
"__dict__",
"[",
"'_setupfunc'",
"]",
"=",
"func",
"super",
"(",
")",
".",
"__init__",
"(",
")"
] | [
368,
4
] | [
378,
26
] | python | en | ['en', 'error', 'th'] | False |
_multi_decorate | (decorators, method) |
Decorate `method` with one or more function decorators. `decorators` can be
a single decorator or an iterable of decorators.
|
Decorate `method` with one or more function decorators. `decorators` can be
a single decorator or an iterable of decorators.
| def _multi_decorate(decorators, method):
"""
Decorate `method` with one or more function decorators. `decorators` can be
a single decorator or an iterable of decorators.
"""
if hasattr(decorators, '__iter__'):
# Apply a list/tuple of decorators if 'decorators' is one. Decorator
# functions are applied so that the call order is the same as the
# order in which they appear in the iterable.
decorators = decorators[::-1]
else:
decorators = [decorators]
def _wrapper(self, *args, **kwargs):
# bound_method has the signature that 'decorator' expects i.e. no
# 'self' argument, but it's a closure over self so it can call
# 'func'. Also, wrap method.__get__() in a function because new
# attributes can't be set on bound method objects, only on functions.
bound_method = partial(method.__get__(self, type(self)))
for dec in decorators:
bound_method = dec(bound_method)
return bound_method(*args, **kwargs)
# Copy any attributes that a decorator adds to the function it decorates.
for dec in decorators:
_update_method_wrapper(_wrapper, dec)
# Preserve any existing attributes of 'method', including the name.
update_wrapper(_wrapper, method)
return _wrapper | [
"def",
"_multi_decorate",
"(",
"decorators",
",",
"method",
")",
":",
"if",
"hasattr",
"(",
"decorators",
",",
"'__iter__'",
")",
":",
"# Apply a list/tuple of decorators if 'decorators' is one. Decorator",
"# functions are applied so that the call order is the same as the",
"# order in which they appear in the iterable.",
"decorators",
"=",
"decorators",
"[",
":",
":",
"-",
"1",
"]",
"else",
":",
"decorators",
"=",
"[",
"decorators",
"]",
"def",
"_wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# bound_method has the signature that 'decorator' expects i.e. no",
"# 'self' argument, but it's a closure over self so it can call",
"# 'func'. Also, wrap method.__get__() in a function because new",
"# attributes can't be set on bound method objects, only on functions.",
"bound_method",
"=",
"partial",
"(",
"method",
".",
"__get__",
"(",
"self",
",",
"type",
"(",
"self",
")",
")",
")",
"for",
"dec",
"in",
"decorators",
":",
"bound_method",
"=",
"dec",
"(",
"bound_method",
")",
"return",
"bound_method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Copy any attributes that a decorator adds to the function it decorates.",
"for",
"dec",
"in",
"decorators",
":",
"_update_method_wrapper",
"(",
"_wrapper",
",",
"dec",
")",
"# Preserve any existing attributes of 'method', including the name.",
"update_wrapper",
"(",
"_wrapper",
",",
"method",
")",
"return",
"_wrapper"
] | [
21,
0
] | [
49,
19
] | python | en | ['en', 'error', 'th'] | False |
method_decorator | (decorator, name='') |
Convert a function decorator into a method decorator
|
Convert a function decorator into a method decorator
| def method_decorator(decorator, name=''):
"""
Convert a function decorator into a method decorator
"""
# 'obj' can be a class or a function. If 'obj' is a function at the time it
# is passed to _dec, it will eventually be a method of the class it is
# defined on. If 'obj' is a class, the 'name' is required to be the name
# of the method that will be decorated.
def _dec(obj):
if not isinstance(obj, type):
return _multi_decorate(decorator, obj)
if not (name and hasattr(obj, name)):
raise ValueError(
"The keyword argument `name` must be the name of a method "
"of the decorated class: %s. Got '%s' instead." % (obj, name)
)
method = getattr(obj, name)
if not callable(method):
raise TypeError(
"Cannot decorate '%s' as it isn't a callable attribute of "
"%s (%s)." % (name, obj, method)
)
_wrapper = _multi_decorate(decorator, method)
setattr(obj, name, _wrapper)
return obj
# Don't worry about making _dec look similar to a list/tuple as it's rather
# meaningless.
if not hasattr(decorator, '__iter__'):
update_wrapper(_dec, decorator)
# Change the name to aid debugging.
obj = decorator if hasattr(decorator, '__name__') else decorator.__class__
_dec.__name__ = 'method_decorator(%s)' % obj.__name__
return _dec | [
"def",
"method_decorator",
"(",
"decorator",
",",
"name",
"=",
"''",
")",
":",
"# 'obj' can be a class or a function. If 'obj' is a function at the time it",
"# is passed to _dec, it will eventually be a method of the class it is",
"# defined on. If 'obj' is a class, the 'name' is required to be the name",
"# of the method that will be decorated.",
"def",
"_dec",
"(",
"obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"type",
")",
":",
"return",
"_multi_decorate",
"(",
"decorator",
",",
"obj",
")",
"if",
"not",
"(",
"name",
"and",
"hasattr",
"(",
"obj",
",",
"name",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"The keyword argument `name` must be the name of a method \"",
"\"of the decorated class: %s. Got '%s' instead.\"",
"%",
"(",
"obj",
",",
"name",
")",
")",
"method",
"=",
"getattr",
"(",
"obj",
",",
"name",
")",
"if",
"not",
"callable",
"(",
"method",
")",
":",
"raise",
"TypeError",
"(",
"\"Cannot decorate '%s' as it isn't a callable attribute of \"",
"\"%s (%s).\"",
"%",
"(",
"name",
",",
"obj",
",",
"method",
")",
")",
"_wrapper",
"=",
"_multi_decorate",
"(",
"decorator",
",",
"method",
")",
"setattr",
"(",
"obj",
",",
"name",
",",
"_wrapper",
")",
"return",
"obj",
"# Don't worry about making _dec look similar to a list/tuple as it's rather",
"# meaningless.",
"if",
"not",
"hasattr",
"(",
"decorator",
",",
"'__iter__'",
")",
":",
"update_wrapper",
"(",
"_dec",
",",
"decorator",
")",
"# Change the name to aid debugging.",
"obj",
"=",
"decorator",
"if",
"hasattr",
"(",
"decorator",
",",
"'__name__'",
")",
"else",
"decorator",
".",
"__class__",
"_dec",
".",
"__name__",
"=",
"'method_decorator(%s)'",
"%",
"obj",
".",
"__name__",
"return",
"_dec"
] | [
52,
0
] | [
85,
15
] | python | en | ['en', 'error', 'th'] | False |
decorator_from_middleware_with_args | (middleware_class) |
Like decorator_from_middleware, but return a function
that accepts the arguments to be passed to the middleware_class.
Use like::
cache_page = decorator_from_middleware_with_args(CacheMiddleware)
# ...
@cache_page(3600)
def my_view(request):
# ...
|
Like decorator_from_middleware, but return a function
that accepts the arguments to be passed to the middleware_class.
Use like:: | def decorator_from_middleware_with_args(middleware_class):
"""
Like decorator_from_middleware, but return a function
that accepts the arguments to be passed to the middleware_class.
Use like::
cache_page = decorator_from_middleware_with_args(CacheMiddleware)
# ...
@cache_page(3600)
def my_view(request):
# ...
"""
return make_middleware_decorator(middleware_class) | [
"def",
"decorator_from_middleware_with_args",
"(",
"middleware_class",
")",
":",
"return",
"make_middleware_decorator",
"(",
"middleware_class",
")"
] | [
88,
0
] | [
101,
54
] | python | en | ['en', 'error', 'th'] | False |
decorator_from_middleware | (middleware_class) |
Given a middleware class (not an instance), return a view decorator. This
lets you use middleware functionality on a per-view basis. The middleware
is created with no params passed.
|
Given a middleware class (not an instance), return a view decorator. This
lets you use middleware functionality on a per-view basis. The middleware
is created with no params passed.
| def decorator_from_middleware(middleware_class):
"""
Given a middleware class (not an instance), return a view decorator. This
lets you use middleware functionality on a per-view basis. The middleware
is created with no params passed.
"""
return make_middleware_decorator(middleware_class)() | [
"def",
"decorator_from_middleware",
"(",
"middleware_class",
")",
":",
"return",
"make_middleware_decorator",
"(",
"middleware_class",
")",
"(",
")"
] | [
104,
0
] | [
110,
56
] | python | en | ['en', 'error', 'th'] | False |
sync_and_async_middleware | (func) |
Mark a middleware factory as returning a hybrid middleware supporting both
types of request.
|
Mark a middleware factory as returning a hybrid middleware supporting both
types of request.
| def sync_and_async_middleware(func):
"""
Mark a middleware factory as returning a hybrid middleware supporting both
types of request.
"""
func.sync_capable = True
func.async_capable = True
return func | [
"def",
"sync_and_async_middleware",
"(",
"func",
")",
":",
"func",
".",
"sync_capable",
"=",
"True",
"func",
".",
"async_capable",
"=",
"True",
"return",
"func"
] | [
154,
0
] | [
161,
15
] | python | en | ['en', 'error', 'th'] | False |
sync_only_middleware | (func) |
Mark a middleware factory as returning a sync middleware.
This is the default.
|
Mark a middleware factory as returning a sync middleware.
This is the default.
| def sync_only_middleware(func):
"""
Mark a middleware factory as returning a sync middleware.
This is the default.
"""
func.sync_capable = True
func.async_capable = False
return func | [
"def",
"sync_only_middleware",
"(",
"func",
")",
":",
"func",
".",
"sync_capable",
"=",
"True",
"func",
".",
"async_capable",
"=",
"False",
"return",
"func"
] | [
164,
0
] | [
171,
15
] | python | en | ['en', 'error', 'th'] | False |
async_only_middleware | (func) | Mark a middleware factory as returning an async middleware. | Mark a middleware factory as returning an async middleware. | def async_only_middleware(func):
"""Mark a middleware factory as returning an async middleware."""
func.sync_capable = False
func.async_capable = True
return func | [
"def",
"async_only_middleware",
"(",
"func",
")",
":",
"func",
".",
"sync_capable",
"=",
"False",
"func",
".",
"async_capable",
"=",
"True",
"return",
"func"
] | [
174,
0
] | [
178,
15
] | python | en | ['en', 'en', 'en'] | True |
require_http_methods | (request_method_list) |
Decorator to make a view only accept particular request methods. Usage::
@require_http_methods(["GET", "POST"])
def my_view(request):
# I can assume now that only GET or POST requests make it this far
# ...
Note that request methods should be in uppercase.
|
Decorator to make a view only accept particular request methods. Usage:: | def require_http_methods(request_method_list):
"""
Decorator to make a view only accept particular request methods. Usage::
@require_http_methods(["GET", "POST"])
def my_view(request):
# I can assume now that only GET or POST requests make it this far
# ...
Note that request methods should be in uppercase.
"""
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
if request.method not in request_method_list:
response = HttpResponseNotAllowed(request_method_list)
log_response(
'Method Not Allowed (%s): %s', request.method, request.path,
response=response,
request=request,
)
return response
return func(request, *args, **kwargs)
return inner
return decorator | [
"def",
"require_http_methods",
"(",
"request_method_list",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"request",
".",
"method",
"not",
"in",
"request_method_list",
":",
"response",
"=",
"HttpResponseNotAllowed",
"(",
"request_method_list",
")",
"log_response",
"(",
"'Method Not Allowed (%s): %s'",
",",
"request",
".",
"method",
",",
"request",
".",
"path",
",",
"response",
"=",
"response",
",",
"request",
"=",
"request",
",",
")",
"return",
"response",
"return",
"func",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"inner",
"return",
"decorator"
] | [
17,
0
] | [
41,
20
] | python | en | ['en', 'error', 'th'] | False |
condition | (etag_func=None, last_modified_func=None) |
Decorator to support conditional retrieval (or change) for a view
function.
The parameters are callables to compute the ETag and last modified time for
the requested resource, respectively. The callables are passed the same
parameters as the view itself. The ETag function should return a string (or
None if the resource doesn't exist), while the last_modified function
should return a datetime object (or None if the resource doesn't exist).
The ETag function should return a complete ETag, including quotes (e.g.
'"etag"'), since that's the only way to distinguish between weak and strong
ETags. If an unquoted ETag is returned (e.g. 'etag'), it will be converted
to a strong ETag by adding quotes.
This decorator will either pass control to the wrapped view function or
return an HTTP 304 response (unmodified) or 412 response (precondition
failed), depending upon the request method. In either case, the decorator
will add the generated ETag and Last-Modified headers to the response if
the headers aren't already set and if the request's method is safe.
|
Decorator to support conditional retrieval (or change) for a view
function. | def condition(etag_func=None, last_modified_func=None):
"""
Decorator to support conditional retrieval (or change) for a view
function.
The parameters are callables to compute the ETag and last modified time for
the requested resource, respectively. The callables are passed the same
parameters as the view itself. The ETag function should return a string (or
None if the resource doesn't exist), while the last_modified function
should return a datetime object (or None if the resource doesn't exist).
The ETag function should return a complete ETag, including quotes (e.g.
'"etag"'), since that's the only way to distinguish between weak and strong
ETags. If an unquoted ETag is returned (e.g. 'etag'), it will be converted
to a strong ETag by adding quotes.
This decorator will either pass control to the wrapped view function or
return an HTTP 304 response (unmodified) or 412 response (precondition
failed), depending upon the request method. In either case, the decorator
will add the generated ETag and Last-Modified headers to the response if
the headers aren't already set and if the request's method is safe.
"""
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
# Compute values (if any) for the requested resource.
def get_last_modified():
if last_modified_func:
dt = last_modified_func(request, *args, **kwargs)
if dt:
return timegm(dt.utctimetuple())
# The value from etag_func() could be quoted or unquoted.
res_etag = etag_func(request, *args, **kwargs) if etag_func else None
res_etag = quote_etag(res_etag) if res_etag is not None else None
res_last_modified = get_last_modified()
response = get_conditional_response(
request,
etag=res_etag,
last_modified=res_last_modified,
)
if response is None:
response = func(request, *args, **kwargs)
# Set relevant headers on the response if they don't already exist
# and if the request method is safe.
if request.method in ('GET', 'HEAD'):
if res_last_modified and not response.has_header('Last-Modified'):
response.headers['Last-Modified'] = http_date(res_last_modified)
if res_etag:
response.headers.setdefault('ETag', res_etag)
return response
return inner
return decorator | [
"def",
"condition",
"(",
"etag_func",
"=",
"None",
",",
"last_modified_func",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Compute values (if any) for the requested resource.",
"def",
"get_last_modified",
"(",
")",
":",
"if",
"last_modified_func",
":",
"dt",
"=",
"last_modified_func",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"dt",
":",
"return",
"timegm",
"(",
"dt",
".",
"utctimetuple",
"(",
")",
")",
"# The value from etag_func() could be quoted or unquoted.",
"res_etag",
"=",
"etag_func",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"etag_func",
"else",
"None",
"res_etag",
"=",
"quote_etag",
"(",
"res_etag",
")",
"if",
"res_etag",
"is",
"not",
"None",
"else",
"None",
"res_last_modified",
"=",
"get_last_modified",
"(",
")",
"response",
"=",
"get_conditional_response",
"(",
"request",
",",
"etag",
"=",
"res_etag",
",",
"last_modified",
"=",
"res_last_modified",
",",
")",
"if",
"response",
"is",
"None",
":",
"response",
"=",
"func",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Set relevant headers on the response if they don't already exist",
"# and if the request method is safe.",
"if",
"request",
".",
"method",
"in",
"(",
"'GET'",
",",
"'HEAD'",
")",
":",
"if",
"res_last_modified",
"and",
"not",
"response",
".",
"has_header",
"(",
"'Last-Modified'",
")",
":",
"response",
".",
"headers",
"[",
"'Last-Modified'",
"]",
"=",
"http_date",
"(",
"res_last_modified",
")",
"if",
"res_etag",
":",
"response",
".",
"headers",
".",
"setdefault",
"(",
"'ETag'",
",",
"res_etag",
")",
"return",
"response",
"return",
"inner",
"return",
"decorator"
] | [
54,
0
] | [
111,
20
] | python | en | ['en', 'error', 'th'] | False |
with_metaclass | (meta, *bases) |
Create a base class with a metaclass.
This requires a bit of explanation: the basic idea is to make a dummy
metaclass for one level of class instantiation that replaces itself with
the actual metaclass.
Taken from six - https://pythonhosted.org/six/
|
Create a base class with a metaclass. | def with_metaclass(meta, *bases):
"""
Create a base class with a metaclass.
This requires a bit of explanation: the basic idea is to make a dummy
metaclass for one level of class instantiation that replaces itself with
the actual metaclass.
Taken from six - https://pythonhosted.org/six/
"""
class metaclass(meta):
def __new__(cls, name, this_bases, d):
return meta(name, bases, d)
return type.__new__(metaclass, 'temporary_class', (), {}) | [
"def",
"with_metaclass",
"(",
"meta",
",",
"*",
"bases",
")",
":",
"class",
"metaclass",
"(",
"meta",
")",
":",
"def",
"__new__",
"(",
"cls",
",",
"name",
",",
"this_bases",
",",
"d",
")",
":",
"return",
"meta",
"(",
"name",
",",
"bases",
",",
"d",
")",
"return",
"type",
".",
"__new__",
"(",
"metaclass",
",",
"'temporary_class'",
",",
"(",
")",
",",
"{",
"}",
")"
] | [
22,
0
] | [
35,
61
] | python | en | ['en', 'error', 'th'] | False |
CloudinaryField.value_to_string | (self, obj) |
We need to support both legacy `_get_val_from_obj` and new `value_from_object` models.Field methods.
It would be better to wrap it with try -> except AttributeError -> fallback to legacy.
Unfortunately, we can catch AttributeError exception from `value_from_object` function itself.
Parsing exception string is an overkill here, that's why we check for attribute existence
:param obj: Value to serialize
:return: Serialized value
|
We need to support both legacy `_get_val_from_obj` and new `value_from_object` models.Field methods.
It would be better to wrap it with try -> except AttributeError -> fallback to legacy.
Unfortunately, we can catch AttributeError exception from `value_from_object` function itself.
Parsing exception string is an overkill here, that's why we check for attribute existence | def value_to_string(self, obj):
"""
We need to support both legacy `_get_val_from_obj` and new `value_from_object` models.Field methods.
It would be better to wrap it with try -> except AttributeError -> fallback to legacy.
Unfortunately, we can catch AttributeError exception from `value_from_object` function itself.
Parsing exception string is an overkill here, that's why we check for attribute existence
:param obj: Value to serialize
:return: Serialized value
"""
if hasattr(self, 'value_from_object'):
value = self.value_from_object(obj)
else: # fallback for legacy django versions
value = self._get_val_from_obj(obj)
return self.get_prep_value(value) | [
"def",
"value_to_string",
"(",
"self",
",",
"obj",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'value_from_object'",
")",
":",
"value",
"=",
"self",
".",
"value_from_object",
"(",
"obj",
")",
"else",
":",
"# fallback for legacy django versions",
"value",
"=",
"self",
".",
"_get_val_from_obj",
"(",
"obj",
")",
"return",
"self",
".",
"get_prep_value",
"(",
"value",
")"
] | [
57,
4
] | [
74,
41
] | python | en | ['en', 'error', 'th'] | False |
PyAccess.__setitem__ | (self, xy, color) |
Modifies the pixel at x,y. The color is given as a single
numerical value for single band images, and a tuple for
multi-band images
:param xy: The pixel coordinate, given as (x, y). See
:ref:`coordinate-system`.
:param color: The pixel value.
|
Modifies the pixel at x,y. The color is given as a single
numerical value for single band images, and a tuple for
multi-band images | def __setitem__(self, xy, color):
"""
Modifies the pixel at x,y. The color is given as a single
numerical value for single band images, and a tuple for
multi-band images
:param xy: The pixel coordinate, given as (x, y). See
:ref:`coordinate-system`.
:param color: The pixel value.
"""
if self.readonly:
raise ValueError("Attempt to putpixel a read only image")
(x, y) = xy
if x < 0:
x = self.xsize + x
if y < 0:
y = self.ysize + y
(x, y) = self.check_xy((x, y))
if (
self._im.mode == "P"
and isinstance(color, (list, tuple))
and len(color) in [3, 4]
):
# RGB or RGBA value for a P image
color = self._palette.getcolor(color, self._img)
return self.set_pixel(x, y, color) | [
"def",
"__setitem__",
"(",
"self",
",",
"xy",
",",
"color",
")",
":",
"if",
"self",
".",
"readonly",
":",
"raise",
"ValueError",
"(",
"\"Attempt to putpixel a read only image\"",
")",
"(",
"x",
",",
"y",
")",
"=",
"xy",
"if",
"x",
"<",
"0",
":",
"x",
"=",
"self",
".",
"xsize",
"+",
"x",
"if",
"y",
"<",
"0",
":",
"y",
"=",
"self",
".",
"ysize",
"+",
"y",
"(",
"x",
",",
"y",
")",
"=",
"self",
".",
"check_xy",
"(",
"(",
"x",
",",
"y",
")",
")",
"if",
"(",
"self",
".",
"_im",
".",
"mode",
"==",
"\"P\"",
"and",
"isinstance",
"(",
"color",
",",
"(",
"list",
",",
"tuple",
")",
")",
"and",
"len",
"(",
"color",
")",
"in",
"[",
"3",
",",
"4",
"]",
")",
":",
"# RGB or RGBA value for a P image",
"color",
"=",
"self",
".",
"_palette",
".",
"getcolor",
"(",
"color",
",",
"self",
".",
"_img",
")",
"return",
"self",
".",
"set_pixel",
"(",
"x",
",",
"y",
",",
"color",
")"
] | [
71,
4
] | [
98,
42
] | python | en | ['en', 'error', 'th'] | False |
PyAccess.__getitem__ | (self, xy) |
Returns the pixel at x,y. The pixel is returned as a single
value for single band images or a tuple for multiple band
images
:param xy: The pixel coordinate, given as (x, y). See
:ref:`coordinate-system`.
:returns: a pixel value for single band images, a tuple of
pixel values for multiband images.
|
Returns the pixel at x,y. The pixel is returned as a single
value for single band images or a tuple for multiple band
images | def __getitem__(self, xy):
"""
Returns the pixel at x,y. The pixel is returned as a single
value for single band images or a tuple for multiple band
images
:param xy: The pixel coordinate, given as (x, y). See
:ref:`coordinate-system`.
:returns: a pixel value for single band images, a tuple of
pixel values for multiband images.
"""
(x, y) = xy
if x < 0:
x = self.xsize + x
if y < 0:
y = self.ysize + y
(x, y) = self.check_xy((x, y))
return self.get_pixel(x, y) | [
"def",
"__getitem__",
"(",
"self",
",",
"xy",
")",
":",
"(",
"x",
",",
"y",
")",
"=",
"xy",
"if",
"x",
"<",
"0",
":",
"x",
"=",
"self",
".",
"xsize",
"+",
"x",
"if",
"y",
"<",
"0",
":",
"y",
"=",
"self",
".",
"ysize",
"+",
"y",
"(",
"x",
",",
"y",
")",
"=",
"self",
".",
"check_xy",
"(",
"(",
"x",
",",
"y",
")",
")",
"return",
"self",
".",
"get_pixel",
"(",
"x",
",",
"y",
")"
] | [
100,
4
] | [
117,
35
] | python | en | ['en', 'error', 'th'] | False |
setdefaultproxy | (
proxytype=None, addr=None, port=None, rdns=True, username=None, password=None
) | setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
Sets a default proxy which all further socksocket objects will use,
unless explicitly changed.
| setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
Sets a default proxy which all further socksocket objects will use,
unless explicitly changed.
| def setdefaultproxy(
proxytype=None, addr=None, port=None, rdns=True, username=None, password=None
):
"""setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
Sets a default proxy which all further socksocket objects will use,
unless explicitly changed.
"""
global _defaultproxy
_defaultproxy = (proxytype, addr, port, rdns, username, password) | [
"def",
"setdefaultproxy",
"(",
"proxytype",
"=",
"None",
",",
"addr",
"=",
"None",
",",
"port",
"=",
"None",
",",
"rdns",
"=",
"True",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"global",
"_defaultproxy",
"_defaultproxy",
"=",
"(",
"proxytype",
",",
"addr",
",",
"port",
",",
"rdns",
",",
"username",
",",
"password",
")"
] | [
118,
0
] | [
126,
69
] | python | en | ['es', 'hu', 'en'] | False |
wrapmodule | (module) | wrapmodule(module)
Attempts to replace a module's socket library with a SOCKS socket. Must set
a default proxy using setdefaultproxy(...) first.
This will only work on modules that import socket directly into the
namespace;
most of the Python Standard Library falls into this category.
| wrapmodule(module) | def wrapmodule(module):
"""wrapmodule(module)
Attempts to replace a module's socket library with a SOCKS socket. Must set
a default proxy using setdefaultproxy(...) first.
This will only work on modules that import socket directly into the
namespace;
most of the Python Standard Library falls into this category.
"""
if _defaultproxy != None:
module.socket.socket = socksocket
else:
raise GeneralProxyError((4, "no proxy specified")) | [
"def",
"wrapmodule",
"(",
"module",
")",
":",
"if",
"_defaultproxy",
"!=",
"None",
":",
"module",
".",
"socket",
".",
"socket",
"=",
"socksocket",
"else",
":",
"raise",
"GeneralProxyError",
"(",
"(",
"4",
",",
"\"no proxy specified\"",
")",
")"
] | [
129,
0
] | [
141,
58
] | python | en | ['en', 'yo', 'en'] | False |
socksocket.__recvall | (self, count) | __recvall(count) -> data
Receive EXACTLY the number of bytes requested from the socket.
Blocks until the required number of bytes have been received.
| __recvall(count) -> data
Receive EXACTLY the number of bytes requested from the socket.
Blocks until the required number of bytes have been received.
| def __recvall(self, count):
"""__recvall(count) -> data
Receive EXACTLY the number of bytes requested from the socket.
Blocks until the required number of bytes have been received.
"""
data = self.recv(count)
while len(data) < count:
d = self.recv(count - len(data))
if not d:
raise GeneralProxyError((0, "connection closed unexpectedly"))
data = data + d
return data | [
"def",
"__recvall",
"(",
"self",
",",
"count",
")",
":",
"data",
"=",
"self",
".",
"recv",
"(",
"count",
")",
"while",
"len",
"(",
"data",
")",
"<",
"count",
":",
"d",
"=",
"self",
".",
"recv",
"(",
"count",
"-",
"len",
"(",
"data",
")",
")",
"if",
"not",
"d",
":",
"raise",
"GeneralProxyError",
"(",
"(",
"0",
",",
"\"connection closed unexpectedly\"",
")",
")",
"data",
"=",
"data",
"+",
"d",
"return",
"data"
] | [
163,
4
] | [
174,
19
] | python | en | ['en', 'en', 'hi'] | True |
socksocket.sendall | (self, content, *args) | override socket.socket.sendall method to rewrite the header
for non-tunneling proxies if needed
| override socket.socket.sendall method to rewrite the header
for non-tunneling proxies if needed
| def sendall(self, content, *args):
""" override socket.socket.sendall method to rewrite the header
for non-tunneling proxies if needed
"""
if not self.__httptunnel:
content = self.__rewriteproxy(content)
return super(socksocket, self).sendall(content, *args) | [
"def",
"sendall",
"(",
"self",
",",
"content",
",",
"*",
"args",
")",
":",
"if",
"not",
"self",
".",
"__httptunnel",
":",
"content",
"=",
"self",
".",
"__rewriteproxy",
"(",
"content",
")",
"return",
"super",
"(",
"socksocket",
",",
"self",
")",
".",
"sendall",
"(",
"content",
",",
"*",
"args",
")"
] | [
176,
4
] | [
182,
62
] | python | en | ['en', 'no', 'en'] | True |
socksocket.__rewriteproxy | (self, header) | rewrite HTTP request headers to support non-tunneling proxies
(i.e. those which do not support the CONNECT method).
This only works for HTTP (not HTTPS) since HTTPS requires tunneling.
| rewrite HTTP request headers to support non-tunneling proxies
(i.e. those which do not support the CONNECT method).
This only works for HTTP (not HTTPS) since HTTPS requires tunneling.
| def __rewriteproxy(self, header):
""" rewrite HTTP request headers to support non-tunneling proxies
(i.e. those which do not support the CONNECT method).
This only works for HTTP (not HTTPS) since HTTPS requires tunneling.
"""
host, endpt = None, None
hdrs = header.split("\r\n")
for hdr in hdrs:
if hdr.lower().startswith("host:"):
host = hdr
elif hdr.lower().startswith("get") or hdr.lower().startswith("post"):
endpt = hdr
if host and endpt:
hdrs.remove(host)
hdrs.remove(endpt)
host = host.split(" ")[1]
endpt = endpt.split(" ")
if self.__proxy[4] != None and self.__proxy[5] != None:
hdrs.insert(0, self.__getauthheader())
hdrs.insert(0, "Host: %s" % host)
hdrs.insert(0, "%s http://%s%s %s" % (endpt[0], host, endpt[1], endpt[2]))
return "\r\n".join(hdrs) | [
"def",
"__rewriteproxy",
"(",
"self",
",",
"header",
")",
":",
"host",
",",
"endpt",
"=",
"None",
",",
"None",
"hdrs",
"=",
"header",
".",
"split",
"(",
"\"\\r\\n\"",
")",
"for",
"hdr",
"in",
"hdrs",
":",
"if",
"hdr",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"\"host:\"",
")",
":",
"host",
"=",
"hdr",
"elif",
"hdr",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"\"get\"",
")",
"or",
"hdr",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"\"post\"",
")",
":",
"endpt",
"=",
"hdr",
"if",
"host",
"and",
"endpt",
":",
"hdrs",
".",
"remove",
"(",
"host",
")",
"hdrs",
".",
"remove",
"(",
"endpt",
")",
"host",
"=",
"host",
".",
"split",
"(",
"\" \"",
")",
"[",
"1",
"]",
"endpt",
"=",
"endpt",
".",
"split",
"(",
"\" \"",
")",
"if",
"self",
".",
"__proxy",
"[",
"4",
"]",
"!=",
"None",
"and",
"self",
".",
"__proxy",
"[",
"5",
"]",
"!=",
"None",
":",
"hdrs",
".",
"insert",
"(",
"0",
",",
"self",
".",
"__getauthheader",
"(",
")",
")",
"hdrs",
".",
"insert",
"(",
"0",
",",
"\"Host: %s\"",
"%",
"host",
")",
"hdrs",
".",
"insert",
"(",
"0",
",",
"\"%s http://%s%s %s\"",
"%",
"(",
"endpt",
"[",
"0",
"]",
",",
"host",
",",
"endpt",
"[",
"1",
"]",
",",
"endpt",
"[",
"2",
"]",
")",
")",
"return",
"\"\\r\\n\"",
".",
"join",
"(",
"hdrs",
")"
] | [
184,
4
] | [
205,
32
] | python | en | ['en', 'en', 'en'] | True |
socksocket.setproxy | (
self,
proxytype=None,
addr=None,
port=None,
rdns=True,
username=None,
password=None,
headers=None,
) | setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
Sets the proxy to be used.
proxytype - The type of the proxy to be used. Three types
are supported: PROXY_TYPE_SOCKS4 (including socks4a),
PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
addr - The address of the server (IP or DNS).
port - The port of the server. Defaults to 1080 for SOCKS
servers and 8080 for HTTP proxy servers.
rdns - Should DNS queries be preformed on the remote side
(rather than the local side). The default is True.
Note: This has no effect with SOCKS4 servers.
username - Username to authenticate with to the server.
The default is no authentication.
password - Password to authenticate with to the server.
Only relevant when username is also provided.
headers - Additional or modified headers for the proxy connect
request.
| setproxy(proxytype, addr[, port[, rdns[, username[, password]]]]) | def setproxy(
self,
proxytype=None,
addr=None,
port=None,
rdns=True,
username=None,
password=None,
headers=None,
):
"""setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
Sets the proxy to be used.
proxytype - The type of the proxy to be used. Three types
are supported: PROXY_TYPE_SOCKS4 (including socks4a),
PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
addr - The address of the server (IP or DNS).
port - The port of the server. Defaults to 1080 for SOCKS
servers and 8080 for HTTP proxy servers.
rdns - Should DNS queries be preformed on the remote side
(rather than the local side). The default is True.
Note: This has no effect with SOCKS4 servers.
username - Username to authenticate with to the server.
The default is no authentication.
password - Password to authenticate with to the server.
Only relevant when username is also provided.
headers - Additional or modified headers for the proxy connect
request.
"""
self.__proxy = (proxytype, addr, port, rdns, username, password, headers) | [
"def",
"setproxy",
"(",
"self",
",",
"proxytype",
"=",
"None",
",",
"addr",
"=",
"None",
",",
"port",
"=",
"None",
",",
"rdns",
"=",
"True",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"headers",
"=",
"None",
",",
")",
":",
"self",
".",
"__proxy",
"=",
"(",
"proxytype",
",",
"addr",
",",
"port",
",",
"rdns",
",",
"username",
",",
"password",
",",
"headers",
")"
] | [
211,
4
] | [
240,
81
] | python | en | ['es', 'hu', 'en'] | False |
socksocket.__negotiatesocks5 | (self, destaddr, destport) | __negotiatesocks5(self,destaddr,destport)
Negotiates a connection through a SOCKS5 server.
| __negotiatesocks5(self,destaddr,destport)
Negotiates a connection through a SOCKS5 server.
| def __negotiatesocks5(self, destaddr, destport):
"""__negotiatesocks5(self,destaddr,destport)
Negotiates a connection through a SOCKS5 server.
"""
# First we'll send the authentication packages we support.
if (self.__proxy[4] != None) and (self.__proxy[5] != None):
# The username/password details were supplied to the
# setproxy method so we support the USERNAME/PASSWORD
# authentication (in addition to the standard none).
self.sendall(struct.pack("BBBB", 0x05, 0x02, 0x00, 0x02))
else:
# No username/password were entered, therefore we
# only support connections with no authentication.
self.sendall(struct.pack("BBB", 0x05, 0x01, 0x00))
# We'll receive the server's response to determine which
# method was selected
chosenauth = self.__recvall(2)
if chosenauth[0:1] != chr(0x05).encode():
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
# Check the chosen authentication method
if chosenauth[1:2] == chr(0x00).encode():
# No authentication is required
pass
elif chosenauth[1:2] == chr(0x02).encode():
# Okay, we need to perform a basic username/password
# authentication.
self.sendall(
chr(0x01).encode()
+ chr(len(self.__proxy[4]))
+ self.__proxy[4]
+ chr(len(self.__proxy[5]))
+ self.__proxy[5]
)
authstat = self.__recvall(2)
if authstat[0:1] != chr(0x01).encode():
# Bad response
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
if authstat[1:2] != chr(0x00).encode():
# Authentication failed
self.close()
raise Socks5AuthError((3, _socks5autherrors[3]))
# Authentication succeeded
else:
# Reaching here is always bad
self.close()
if chosenauth[1] == chr(0xFF).encode():
raise Socks5AuthError((2, _socks5autherrors[2]))
else:
raise GeneralProxyError((1, _generalerrors[1]))
# Now we can request the actual connection
req = struct.pack("BBB", 0x05, 0x01, 0x00)
# If the given destination address is an IP address, we'll
# use the IPv4 address request even if remote resolving was specified.
try:
ipaddr = socket.inet_aton(destaddr)
req = req + chr(0x01).encode() + ipaddr
except socket.error:
# Well it's not an IP number, so it's probably a DNS name.
if self.__proxy[3]:
# Resolve remotely
ipaddr = None
req = (
req
+ chr(0x03).encode()
+ chr(len(destaddr)).encode()
+ destaddr.encode()
)
else:
# Resolve locally
ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
req = req + chr(0x01).encode() + ipaddr
req = req + struct.pack(">H", destport)
self.sendall(req)
# Get the response
resp = self.__recvall(4)
if resp[0:1] != chr(0x05).encode():
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
elif resp[1:2] != chr(0x00).encode():
# Connection failed
self.close()
if ord(resp[1:2]) <= 8:
raise Socks5Error((ord(resp[1:2]), _socks5errors[ord(resp[1:2])]))
else:
raise Socks5Error((9, _socks5errors[9]))
# Get the bound address/port
elif resp[3:4] == chr(0x01).encode():
boundaddr = self.__recvall(4)
elif resp[3:4] == chr(0x03).encode():
resp = resp + self.recv(1)
boundaddr = self.__recvall(ord(resp[4:5]))
else:
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
boundport = struct.unpack(">H", self.__recvall(2))[0]
self.__proxysockname = (boundaddr, boundport)
if ipaddr != None:
self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
else:
self.__proxypeername = (destaddr, destport) | [
"def",
"__negotiatesocks5",
"(",
"self",
",",
"destaddr",
",",
"destport",
")",
":",
"# First we'll send the authentication packages we support.",
"if",
"(",
"self",
".",
"__proxy",
"[",
"4",
"]",
"!=",
"None",
")",
"and",
"(",
"self",
".",
"__proxy",
"[",
"5",
"]",
"!=",
"None",
")",
":",
"# The username/password details were supplied to the",
"# setproxy method so we support the USERNAME/PASSWORD",
"# authentication (in addition to the standard none).",
"self",
".",
"sendall",
"(",
"struct",
".",
"pack",
"(",
"\"BBBB\"",
",",
"0x05",
",",
"0x02",
",",
"0x00",
",",
"0x02",
")",
")",
"else",
":",
"# No username/password were entered, therefore we",
"# only support connections with no authentication.",
"self",
".",
"sendall",
"(",
"struct",
".",
"pack",
"(",
"\"BBB\"",
",",
"0x05",
",",
"0x01",
",",
"0x00",
")",
")",
"# We'll receive the server's response to determine which",
"# method was selected",
"chosenauth",
"=",
"self",
".",
"__recvall",
"(",
"2",
")",
"if",
"chosenauth",
"[",
"0",
":",
"1",
"]",
"!=",
"chr",
"(",
"0x05",
")",
".",
"encode",
"(",
")",
":",
"self",
".",
"close",
"(",
")",
"raise",
"GeneralProxyError",
"(",
"(",
"1",
",",
"_generalerrors",
"[",
"1",
"]",
")",
")",
"# Check the chosen authentication method",
"if",
"chosenauth",
"[",
"1",
":",
"2",
"]",
"==",
"chr",
"(",
"0x00",
")",
".",
"encode",
"(",
")",
":",
"# No authentication is required",
"pass",
"elif",
"chosenauth",
"[",
"1",
":",
"2",
"]",
"==",
"chr",
"(",
"0x02",
")",
".",
"encode",
"(",
")",
":",
"# Okay, we need to perform a basic username/password",
"# authentication.",
"self",
".",
"sendall",
"(",
"chr",
"(",
"0x01",
")",
".",
"encode",
"(",
")",
"+",
"chr",
"(",
"len",
"(",
"self",
".",
"__proxy",
"[",
"4",
"]",
")",
")",
"+",
"self",
".",
"__proxy",
"[",
"4",
"]",
"+",
"chr",
"(",
"len",
"(",
"self",
".",
"__proxy",
"[",
"5",
"]",
")",
")",
"+",
"self",
".",
"__proxy",
"[",
"5",
"]",
")",
"authstat",
"=",
"self",
".",
"__recvall",
"(",
"2",
")",
"if",
"authstat",
"[",
"0",
":",
"1",
"]",
"!=",
"chr",
"(",
"0x01",
")",
".",
"encode",
"(",
")",
":",
"# Bad response",
"self",
".",
"close",
"(",
")",
"raise",
"GeneralProxyError",
"(",
"(",
"1",
",",
"_generalerrors",
"[",
"1",
"]",
")",
")",
"if",
"authstat",
"[",
"1",
":",
"2",
"]",
"!=",
"chr",
"(",
"0x00",
")",
".",
"encode",
"(",
")",
":",
"# Authentication failed",
"self",
".",
"close",
"(",
")",
"raise",
"Socks5AuthError",
"(",
"(",
"3",
",",
"_socks5autherrors",
"[",
"3",
"]",
")",
")",
"# Authentication succeeded",
"else",
":",
"# Reaching here is always bad",
"self",
".",
"close",
"(",
")",
"if",
"chosenauth",
"[",
"1",
"]",
"==",
"chr",
"(",
"0xFF",
")",
".",
"encode",
"(",
")",
":",
"raise",
"Socks5AuthError",
"(",
"(",
"2",
",",
"_socks5autherrors",
"[",
"2",
"]",
")",
")",
"else",
":",
"raise",
"GeneralProxyError",
"(",
"(",
"1",
",",
"_generalerrors",
"[",
"1",
"]",
")",
")",
"# Now we can request the actual connection",
"req",
"=",
"struct",
".",
"pack",
"(",
"\"BBB\"",
",",
"0x05",
",",
"0x01",
",",
"0x00",
")",
"# If the given destination address is an IP address, we'll",
"# use the IPv4 address request even if remote resolving was specified.",
"try",
":",
"ipaddr",
"=",
"socket",
".",
"inet_aton",
"(",
"destaddr",
")",
"req",
"=",
"req",
"+",
"chr",
"(",
"0x01",
")",
".",
"encode",
"(",
")",
"+",
"ipaddr",
"except",
"socket",
".",
"error",
":",
"# Well it's not an IP number, so it's probably a DNS name.",
"if",
"self",
".",
"__proxy",
"[",
"3",
"]",
":",
"# Resolve remotely",
"ipaddr",
"=",
"None",
"req",
"=",
"(",
"req",
"+",
"chr",
"(",
"0x03",
")",
".",
"encode",
"(",
")",
"+",
"chr",
"(",
"len",
"(",
"destaddr",
")",
")",
".",
"encode",
"(",
")",
"+",
"destaddr",
".",
"encode",
"(",
")",
")",
"else",
":",
"# Resolve locally",
"ipaddr",
"=",
"socket",
".",
"inet_aton",
"(",
"socket",
".",
"gethostbyname",
"(",
"destaddr",
")",
")",
"req",
"=",
"req",
"+",
"chr",
"(",
"0x01",
")",
".",
"encode",
"(",
")",
"+",
"ipaddr",
"req",
"=",
"req",
"+",
"struct",
".",
"pack",
"(",
"\">H\"",
",",
"destport",
")",
"self",
".",
"sendall",
"(",
"req",
")",
"# Get the response",
"resp",
"=",
"self",
".",
"__recvall",
"(",
"4",
")",
"if",
"resp",
"[",
"0",
":",
"1",
"]",
"!=",
"chr",
"(",
"0x05",
")",
".",
"encode",
"(",
")",
":",
"self",
".",
"close",
"(",
")",
"raise",
"GeneralProxyError",
"(",
"(",
"1",
",",
"_generalerrors",
"[",
"1",
"]",
")",
")",
"elif",
"resp",
"[",
"1",
":",
"2",
"]",
"!=",
"chr",
"(",
"0x00",
")",
".",
"encode",
"(",
")",
":",
"# Connection failed",
"self",
".",
"close",
"(",
")",
"if",
"ord",
"(",
"resp",
"[",
"1",
":",
"2",
"]",
")",
"<=",
"8",
":",
"raise",
"Socks5Error",
"(",
"(",
"ord",
"(",
"resp",
"[",
"1",
":",
"2",
"]",
")",
",",
"_socks5errors",
"[",
"ord",
"(",
"resp",
"[",
"1",
":",
"2",
"]",
")",
"]",
")",
")",
"else",
":",
"raise",
"Socks5Error",
"(",
"(",
"9",
",",
"_socks5errors",
"[",
"9",
"]",
")",
")",
"# Get the bound address/port",
"elif",
"resp",
"[",
"3",
":",
"4",
"]",
"==",
"chr",
"(",
"0x01",
")",
".",
"encode",
"(",
")",
":",
"boundaddr",
"=",
"self",
".",
"__recvall",
"(",
"4",
")",
"elif",
"resp",
"[",
"3",
":",
"4",
"]",
"==",
"chr",
"(",
"0x03",
")",
".",
"encode",
"(",
")",
":",
"resp",
"=",
"resp",
"+",
"self",
".",
"recv",
"(",
"1",
")",
"boundaddr",
"=",
"self",
".",
"__recvall",
"(",
"ord",
"(",
"resp",
"[",
"4",
":",
"5",
"]",
")",
")",
"else",
":",
"self",
".",
"close",
"(",
")",
"raise",
"GeneralProxyError",
"(",
"(",
"1",
",",
"_generalerrors",
"[",
"1",
"]",
")",
")",
"boundport",
"=",
"struct",
".",
"unpack",
"(",
"\">H\"",
",",
"self",
".",
"__recvall",
"(",
"2",
")",
")",
"[",
"0",
"]",
"self",
".",
"__proxysockname",
"=",
"(",
"boundaddr",
",",
"boundport",
")",
"if",
"ipaddr",
"!=",
"None",
":",
"self",
".",
"__proxypeername",
"=",
"(",
"socket",
".",
"inet_ntoa",
"(",
"ipaddr",
")",
",",
"destport",
")",
"else",
":",
"self",
".",
"__proxypeername",
"=",
"(",
"destaddr",
",",
"destport",
")"
] | [
242,
4
] | [
343,
55
] | python | pl | ['pl', 'sv', 'sw'] | False |
socksocket.getproxysockname | (self) | getsockname() -> address info
Returns the bound IP address and port number at the proxy.
| getsockname() -> address info
Returns the bound IP address and port number at the proxy.
| def getproxysockname(self):
"""getsockname() -> address info
Returns the bound IP address and port number at the proxy.
"""
return self.__proxysockname | [
"def",
"getproxysockname",
"(",
"self",
")",
":",
"return",
"self",
".",
"__proxysockname"
] | [
345,
4
] | [
349,
35
] | python | en | ['en', 'no', 'en'] | True |
socksocket.getproxypeername | (self) | getproxypeername() -> address info
Returns the IP and port number of the proxy.
| getproxypeername() -> address info
Returns the IP and port number of the proxy.
| def getproxypeername(self):
"""getproxypeername() -> address info
Returns the IP and port number of the proxy.
"""
return _orgsocket.getpeername(self) | [
"def",
"getproxypeername",
"(",
"self",
")",
":",
"return",
"_orgsocket",
".",
"getpeername",
"(",
"self",
")"
] | [
351,
4
] | [
355,
43
] | python | en | ['en', 'nl', 'en'] | True |
socksocket.getpeername | (self) | getpeername() -> address info
Returns the IP address and port number of the destination
machine (note: getproxypeername returns the proxy)
| getpeername() -> address info
Returns the IP address and port number of the destination
machine (note: getproxypeername returns the proxy)
| def getpeername(self):
"""getpeername() -> address info
Returns the IP address and port number of the destination
machine (note: getproxypeername returns the proxy)
"""
return self.__proxypeername | [
"def",
"getpeername",
"(",
"self",
")",
":",
"return",
"self",
".",
"__proxypeername"
] | [
357,
4
] | [
362,
35
] | python | en | ['en', 'ko', 'en'] | True |
socksocket.__negotiatesocks4 | (self, destaddr, destport) | __negotiatesocks4(self,destaddr,destport)
Negotiates a connection through a SOCKS4 server.
| __negotiatesocks4(self,destaddr,destport)
Negotiates a connection through a SOCKS4 server.
| def __negotiatesocks4(self, destaddr, destport):
"""__negotiatesocks4(self,destaddr,destport)
Negotiates a connection through a SOCKS4 server.
"""
# Check if the destination address provided is an IP address
rmtrslv = False
try:
ipaddr = socket.inet_aton(destaddr)
except socket.error:
# It's a DNS name. Check where it should be resolved.
if self.__proxy[3]:
ipaddr = struct.pack("BBBB", 0x00, 0x00, 0x00, 0x01)
rmtrslv = True
else:
ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
# Construct the request packet
req = struct.pack(">BBH", 0x04, 0x01, destport) + ipaddr
# The username parameter is considered userid for SOCKS4
if self.__proxy[4] != None:
req = req + self.__proxy[4]
req = req + chr(0x00).encode()
# DNS name if remote resolving is required
# NOTE: This is actually an extension to the SOCKS4 protocol
# called SOCKS4A and may not be supported in all cases.
if rmtrslv:
req = req + destaddr + chr(0x00).encode()
self.sendall(req)
# Get the response from the server
resp = self.__recvall(8)
if resp[0:1] != chr(0x00).encode():
# Bad data
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
if resp[1:2] != chr(0x5A).encode():
# Server returned an error
self.close()
if ord(resp[1:2]) in (91, 92, 93):
self.close()
raise Socks4Error((ord(resp[1:2]), _socks4errors[ord(resp[1:2]) - 90]))
else:
raise Socks4Error((94, _socks4errors[4]))
# Get the bound address/port
self.__proxysockname = (
socket.inet_ntoa(resp[4:]),
struct.unpack(">H", resp[2:4])[0],
)
if rmtrslv != None:
self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
else:
self.__proxypeername = (destaddr, destport) | [
"def",
"__negotiatesocks4",
"(",
"self",
",",
"destaddr",
",",
"destport",
")",
":",
"# Check if the destination address provided is an IP address",
"rmtrslv",
"=",
"False",
"try",
":",
"ipaddr",
"=",
"socket",
".",
"inet_aton",
"(",
"destaddr",
")",
"except",
"socket",
".",
"error",
":",
"# It's a DNS name. Check where it should be resolved.",
"if",
"self",
".",
"__proxy",
"[",
"3",
"]",
":",
"ipaddr",
"=",
"struct",
".",
"pack",
"(",
"\"BBBB\"",
",",
"0x00",
",",
"0x00",
",",
"0x00",
",",
"0x01",
")",
"rmtrslv",
"=",
"True",
"else",
":",
"ipaddr",
"=",
"socket",
".",
"inet_aton",
"(",
"socket",
".",
"gethostbyname",
"(",
"destaddr",
")",
")",
"# Construct the request packet",
"req",
"=",
"struct",
".",
"pack",
"(",
"\">BBH\"",
",",
"0x04",
",",
"0x01",
",",
"destport",
")",
"+",
"ipaddr",
"# The username parameter is considered userid for SOCKS4",
"if",
"self",
".",
"__proxy",
"[",
"4",
"]",
"!=",
"None",
":",
"req",
"=",
"req",
"+",
"self",
".",
"__proxy",
"[",
"4",
"]",
"req",
"=",
"req",
"+",
"chr",
"(",
"0x00",
")",
".",
"encode",
"(",
")",
"# DNS name if remote resolving is required",
"# NOTE: This is actually an extension to the SOCKS4 protocol",
"# called SOCKS4A and may not be supported in all cases.",
"if",
"rmtrslv",
":",
"req",
"=",
"req",
"+",
"destaddr",
"+",
"chr",
"(",
"0x00",
")",
".",
"encode",
"(",
")",
"self",
".",
"sendall",
"(",
"req",
")",
"# Get the response from the server",
"resp",
"=",
"self",
".",
"__recvall",
"(",
"8",
")",
"if",
"resp",
"[",
"0",
":",
"1",
"]",
"!=",
"chr",
"(",
"0x00",
")",
".",
"encode",
"(",
")",
":",
"# Bad data",
"self",
".",
"close",
"(",
")",
"raise",
"GeneralProxyError",
"(",
"(",
"1",
",",
"_generalerrors",
"[",
"1",
"]",
")",
")",
"if",
"resp",
"[",
"1",
":",
"2",
"]",
"!=",
"chr",
"(",
"0x5A",
")",
".",
"encode",
"(",
")",
":",
"# Server returned an error",
"self",
".",
"close",
"(",
")",
"if",
"ord",
"(",
"resp",
"[",
"1",
":",
"2",
"]",
")",
"in",
"(",
"91",
",",
"92",
",",
"93",
")",
":",
"self",
".",
"close",
"(",
")",
"raise",
"Socks4Error",
"(",
"(",
"ord",
"(",
"resp",
"[",
"1",
":",
"2",
"]",
")",
",",
"_socks4errors",
"[",
"ord",
"(",
"resp",
"[",
"1",
":",
"2",
"]",
")",
"-",
"90",
"]",
")",
")",
"else",
":",
"raise",
"Socks4Error",
"(",
"(",
"94",
",",
"_socks4errors",
"[",
"4",
"]",
")",
")",
"# Get the bound address/port",
"self",
".",
"__proxysockname",
"=",
"(",
"socket",
".",
"inet_ntoa",
"(",
"resp",
"[",
"4",
":",
"]",
")",
",",
"struct",
".",
"unpack",
"(",
"\">H\"",
",",
"resp",
"[",
"2",
":",
"4",
"]",
")",
"[",
"0",
"]",
",",
")",
"if",
"rmtrslv",
"!=",
"None",
":",
"self",
".",
"__proxypeername",
"=",
"(",
"socket",
".",
"inet_ntoa",
"(",
"ipaddr",
")",
",",
"destport",
")",
"else",
":",
"self",
".",
"__proxypeername",
"=",
"(",
"destaddr",
",",
"destport",
")"
] | [
364,
4
] | [
413,
55
] | python | hi | ['pl', 'sv', 'hi'] | False |
socksocket.__negotiatehttp | (self, destaddr, destport) | __negotiatehttp(self,destaddr,destport)
Negotiates a connection through an HTTP server.
| __negotiatehttp(self,destaddr,destport)
Negotiates a connection through an HTTP server.
| def __negotiatehttp(self, destaddr, destport):
"""__negotiatehttp(self,destaddr,destport)
Negotiates a connection through an HTTP server.
"""
# If we need to resolve locally, we do this now
if not self.__proxy[3]:
addr = socket.gethostbyname(destaddr)
else:
addr = destaddr
headers = ["CONNECT ", addr, ":", str(destport), " HTTP/1.1\r\n"]
wrote_host_header = False
wrote_auth_header = False
if self.__proxy[6] != None:
for key, val in self.__proxy[6].iteritems():
headers += [key, ": ", val, "\r\n"]
wrote_host_header = key.lower() == "host"
wrote_auth_header = key.lower() == "proxy-authorization"
if not wrote_host_header:
headers += ["Host: ", destaddr, "\r\n"]
if not wrote_auth_header:
if self.__proxy[4] != None and self.__proxy[5] != None:
headers += [self.__getauthheader(), "\r\n"]
headers.append("\r\n")
self.sendall("".join(headers).encode())
# We read the response until we get the string "\r\n\r\n"
resp = self.recv(1)
while resp.find("\r\n\r\n".encode()) == -1:
resp = resp + self.recv(1)
# We just need the first line to check if the connection
# was successful
statusline = resp.splitlines()[0].split(" ".encode(), 2)
if statusline[0] not in ("HTTP/1.0".encode(), "HTTP/1.1".encode()):
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
try:
statuscode = int(statusline[1])
except ValueError:
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
if statuscode != 200:
self.close()
raise HTTPError((statuscode, statusline[2]))
self.__proxysockname = ("0.0.0.0", 0)
self.__proxypeername = (addr, destport) | [
"def",
"__negotiatehttp",
"(",
"self",
",",
"destaddr",
",",
"destport",
")",
":",
"# If we need to resolve locally, we do this now",
"if",
"not",
"self",
".",
"__proxy",
"[",
"3",
"]",
":",
"addr",
"=",
"socket",
".",
"gethostbyname",
"(",
"destaddr",
")",
"else",
":",
"addr",
"=",
"destaddr",
"headers",
"=",
"[",
"\"CONNECT \"",
",",
"addr",
",",
"\":\"",
",",
"str",
"(",
"destport",
")",
",",
"\" HTTP/1.1\\r\\n\"",
"]",
"wrote_host_header",
"=",
"False",
"wrote_auth_header",
"=",
"False",
"if",
"self",
".",
"__proxy",
"[",
"6",
"]",
"!=",
"None",
":",
"for",
"key",
",",
"val",
"in",
"self",
".",
"__proxy",
"[",
"6",
"]",
".",
"iteritems",
"(",
")",
":",
"headers",
"+=",
"[",
"key",
",",
"\": \"",
",",
"val",
",",
"\"\\r\\n\"",
"]",
"wrote_host_header",
"=",
"key",
".",
"lower",
"(",
")",
"==",
"\"host\"",
"wrote_auth_header",
"=",
"key",
".",
"lower",
"(",
")",
"==",
"\"proxy-authorization\"",
"if",
"not",
"wrote_host_header",
":",
"headers",
"+=",
"[",
"\"Host: \"",
",",
"destaddr",
",",
"\"\\r\\n\"",
"]",
"if",
"not",
"wrote_auth_header",
":",
"if",
"self",
".",
"__proxy",
"[",
"4",
"]",
"!=",
"None",
"and",
"self",
".",
"__proxy",
"[",
"5",
"]",
"!=",
"None",
":",
"headers",
"+=",
"[",
"self",
".",
"__getauthheader",
"(",
")",
",",
"\"\\r\\n\"",
"]",
"headers",
".",
"append",
"(",
"\"\\r\\n\"",
")",
"self",
".",
"sendall",
"(",
"\"\"",
".",
"join",
"(",
"headers",
")",
".",
"encode",
"(",
")",
")",
"# We read the response until we get the string \"\\r\\n\\r\\n\"",
"resp",
"=",
"self",
".",
"recv",
"(",
"1",
")",
"while",
"resp",
".",
"find",
"(",
"\"\\r\\n\\r\\n\"",
".",
"encode",
"(",
")",
")",
"==",
"-",
"1",
":",
"resp",
"=",
"resp",
"+",
"self",
".",
"recv",
"(",
"1",
")",
"# We just need the first line to check if the connection",
"# was successful",
"statusline",
"=",
"resp",
".",
"splitlines",
"(",
")",
"[",
"0",
"]",
".",
"split",
"(",
"\" \"",
".",
"encode",
"(",
")",
",",
"2",
")",
"if",
"statusline",
"[",
"0",
"]",
"not",
"in",
"(",
"\"HTTP/1.0\"",
".",
"encode",
"(",
")",
",",
"\"HTTP/1.1\"",
".",
"encode",
"(",
")",
")",
":",
"self",
".",
"close",
"(",
")",
"raise",
"GeneralProxyError",
"(",
"(",
"1",
",",
"_generalerrors",
"[",
"1",
"]",
")",
")",
"try",
":",
"statuscode",
"=",
"int",
"(",
"statusline",
"[",
"1",
"]",
")",
"except",
"ValueError",
":",
"self",
".",
"close",
"(",
")",
"raise",
"GeneralProxyError",
"(",
"(",
"1",
",",
"_generalerrors",
"[",
"1",
"]",
")",
")",
"if",
"statuscode",
"!=",
"200",
":",
"self",
".",
"close",
"(",
")",
"raise",
"HTTPError",
"(",
"(",
"statuscode",
",",
"statusline",
"[",
"2",
"]",
")",
")",
"self",
".",
"__proxysockname",
"=",
"(",
"\"0.0.0.0\"",
",",
"0",
")",
"self",
".",
"__proxypeername",
"=",
"(",
"addr",
",",
"destport",
")"
] | [
415,
4
] | [
458,
47
] | python | et | ['et', 'lb', 'hi'] | False |
socksocket.connect | (self, destpair) | connect(self, despair)
Connects to the specified destination through a proxy.
destpar - A tuple of the IP/DNS address and the port number.
(identical to socket's connect).
To select the proxy server use setproxy().
| connect(self, despair)
Connects to the specified destination through a proxy.
destpar - A tuple of the IP/DNS address and the port number.
(identical to socket's connect).
To select the proxy server use setproxy().
| def connect(self, destpair):
"""connect(self, despair)
Connects to the specified destination through a proxy.
destpar - A tuple of the IP/DNS address and the port number.
(identical to socket's connect).
To select the proxy server use setproxy().
"""
# Do a minimal input check first
if (
(not type(destpair) in (list, tuple))
or (len(destpair) < 2)
or (not isinstance(destpair[0], basestring))
or (type(destpair[1]) != int)
):
raise GeneralProxyError((5, _generalerrors[5]))
if self.__proxy[0] == PROXY_TYPE_SOCKS5:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 1080
_orgsocket.connect(self, (self.__proxy[1], portnum))
self.__negotiatesocks5(destpair[0], destpair[1])
elif self.__proxy[0] == PROXY_TYPE_SOCKS4:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 1080
_orgsocket.connect(self, (self.__proxy[1], portnum))
self.__negotiatesocks4(destpair[0], destpair[1])
elif self.__proxy[0] == PROXY_TYPE_HTTP:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 8080
_orgsocket.connect(self, (self.__proxy[1], portnum))
self.__negotiatehttp(destpair[0], destpair[1])
elif self.__proxy[0] == PROXY_TYPE_HTTP_NO_TUNNEL:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 8080
_orgsocket.connect(self, (self.__proxy[1], portnum))
if destpair[1] == 443:
self.__negotiatehttp(destpair[0], destpair[1])
else:
self.__httptunnel = False
elif self.__proxy[0] == None:
_orgsocket.connect(self, (destpair[0], destpair[1]))
else:
raise GeneralProxyError((4, _generalerrors[4])) | [
"def",
"connect",
"(",
"self",
",",
"destpair",
")",
":",
"# Do a minimal input check first",
"if",
"(",
"(",
"not",
"type",
"(",
"destpair",
")",
"in",
"(",
"list",
",",
"tuple",
")",
")",
"or",
"(",
"len",
"(",
"destpair",
")",
"<",
"2",
")",
"or",
"(",
"not",
"isinstance",
"(",
"destpair",
"[",
"0",
"]",
",",
"basestring",
")",
")",
"or",
"(",
"type",
"(",
"destpair",
"[",
"1",
"]",
")",
"!=",
"int",
")",
")",
":",
"raise",
"GeneralProxyError",
"(",
"(",
"5",
",",
"_generalerrors",
"[",
"5",
"]",
")",
")",
"if",
"self",
".",
"__proxy",
"[",
"0",
"]",
"==",
"PROXY_TYPE_SOCKS5",
":",
"if",
"self",
".",
"__proxy",
"[",
"2",
"]",
"!=",
"None",
":",
"portnum",
"=",
"self",
".",
"__proxy",
"[",
"2",
"]",
"else",
":",
"portnum",
"=",
"1080",
"_orgsocket",
".",
"connect",
"(",
"self",
",",
"(",
"self",
".",
"__proxy",
"[",
"1",
"]",
",",
"portnum",
")",
")",
"self",
".",
"__negotiatesocks5",
"(",
"destpair",
"[",
"0",
"]",
",",
"destpair",
"[",
"1",
"]",
")",
"elif",
"self",
".",
"__proxy",
"[",
"0",
"]",
"==",
"PROXY_TYPE_SOCKS4",
":",
"if",
"self",
".",
"__proxy",
"[",
"2",
"]",
"!=",
"None",
":",
"portnum",
"=",
"self",
".",
"__proxy",
"[",
"2",
"]",
"else",
":",
"portnum",
"=",
"1080",
"_orgsocket",
".",
"connect",
"(",
"self",
",",
"(",
"self",
".",
"__proxy",
"[",
"1",
"]",
",",
"portnum",
")",
")",
"self",
".",
"__negotiatesocks4",
"(",
"destpair",
"[",
"0",
"]",
",",
"destpair",
"[",
"1",
"]",
")",
"elif",
"self",
".",
"__proxy",
"[",
"0",
"]",
"==",
"PROXY_TYPE_HTTP",
":",
"if",
"self",
".",
"__proxy",
"[",
"2",
"]",
"!=",
"None",
":",
"portnum",
"=",
"self",
".",
"__proxy",
"[",
"2",
"]",
"else",
":",
"portnum",
"=",
"8080",
"_orgsocket",
".",
"connect",
"(",
"self",
",",
"(",
"self",
".",
"__proxy",
"[",
"1",
"]",
",",
"portnum",
")",
")",
"self",
".",
"__negotiatehttp",
"(",
"destpair",
"[",
"0",
"]",
",",
"destpair",
"[",
"1",
"]",
")",
"elif",
"self",
".",
"__proxy",
"[",
"0",
"]",
"==",
"PROXY_TYPE_HTTP_NO_TUNNEL",
":",
"if",
"self",
".",
"__proxy",
"[",
"2",
"]",
"!=",
"None",
":",
"portnum",
"=",
"self",
".",
"__proxy",
"[",
"2",
"]",
"else",
":",
"portnum",
"=",
"8080",
"_orgsocket",
".",
"connect",
"(",
"self",
",",
"(",
"self",
".",
"__proxy",
"[",
"1",
"]",
",",
"portnum",
")",
")",
"if",
"destpair",
"[",
"1",
"]",
"==",
"443",
":",
"self",
".",
"__negotiatehttp",
"(",
"destpair",
"[",
"0",
"]",
",",
"destpair",
"[",
"1",
"]",
")",
"else",
":",
"self",
".",
"__httptunnel",
"=",
"False",
"elif",
"self",
".",
"__proxy",
"[",
"0",
"]",
"==",
"None",
":",
"_orgsocket",
".",
"connect",
"(",
"self",
",",
"(",
"destpair",
"[",
"0",
"]",
",",
"destpair",
"[",
"1",
"]",
")",
")",
"else",
":",
"raise",
"GeneralProxyError",
"(",
"(",
"4",
",",
"_generalerrors",
"[",
"4",
"]",
")",
")"
] | [
460,
4
] | [
509,
59
] | python | es | ['es', 'gd', 'fr'] | False |
srs_double | (f) |
Create a function prototype for the OSR routines that take
the OSRSpatialReference object and return a double value.
|
Create a function prototype for the OSR routines that take
the OSRSpatialReference object and return a double value.
| def srs_double(f):
"""
Create a function prototype for the OSR routines that take
the OSRSpatialReference object and return a double value.
"""
return double_output(f, [c_void_p, POINTER(c_int)], errcheck=True) | [
"def",
"srs_double",
"(",
"f",
")",
":",
"return",
"double_output",
"(",
"f",
",",
"[",
"c_void_p",
",",
"POINTER",
"(",
"c_int",
")",
"]",
",",
"errcheck",
"=",
"True",
")"
] | [
10,
0
] | [
15,
70
] | python | en | ['en', 'error', 'th'] | False |
units_func | (f) |
Create a ctypes function prototype for OSR units functions, e.g.,
OSRGetAngularUnits, OSRGetLinearUnits.
|
Create a ctypes function prototype for OSR units functions, e.g.,
OSRGetAngularUnits, OSRGetLinearUnits.
| def units_func(f):
"""
Create a ctypes function prototype for OSR units functions, e.g.,
OSRGetAngularUnits, OSRGetLinearUnits.
"""
return double_output(f, [c_void_p, POINTER(c_char_p)], strarg=True) | [
"def",
"units_func",
"(",
"f",
")",
":",
"return",
"double_output",
"(",
"f",
",",
"[",
"c_void_p",
",",
"POINTER",
"(",
"c_char_p",
")",
"]",
",",
"strarg",
"=",
"True",
")"
] | [
18,
0
] | [
23,
71
] | python | en | ['en', 'error', 'th'] | False |
run | (argv=None) | Build and run the pipeline. | Build and run the pipeline. | def run(argv=None):
"""Build and run the pipeline."""
parser = argparse.ArgumentParser()
parser.add_argument(
'--project',
help=('Google Cloud Project ID'),
required=True)
parser.add_argument(
'--input_topic',
help=('Google Cloud PubSub topic name '),
required=True)
known_args, pipeline_args = parser.parse_known_args(argv)
pipeline_options = PipelineOptions(
pipeline_args.append('--project={}'.format(known_args.project)))
pipeline_options.view_as(SetupOptions).save_main_session = True
pipeline_options.view_as(StandardOptions).streaming = True
p = beam.Pipeline(options=pipeline_options)
TOPIC = 'projects/{}/topics/{}'.format(known_args.project,
known_args.input_topic)
# this table needs to exist
table_spec = '{}:taxifare.traffic_realtime'.format(known_args.project)
def to_bq_format(count):
"""BigQuery writer requires rows to be stored as python dictionary"""
return {'trips_last_5min': count,
'time': datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
pipeline = (p
| 'read_from_pubsub' >> beam.io.ReadFromPubSub(topic=TOPIC).with_output_types(bytes)
| 'window' >> beam.WindowInto(window.SlidingWindows(
size=300,
period=15))
| 'count' >> beam.CombineGlobally(CountFn()).without_defaults()
| 'format_for_bq' >> beam.Map(to_bq_format)
| 'write_to_bq' >> beam.io.WriteToBigQuery(
table_spec,
# WRITE_TRUNCATE not supported for streaming
write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,
create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER)
)
result = p.run() | [
"def",
"run",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'--project'",
",",
"help",
"=",
"(",
"'Google Cloud Project ID'",
")",
",",
"required",
"=",
"True",
")",
"parser",
".",
"add_argument",
"(",
"'--input_topic'",
",",
"help",
"=",
"(",
"'Google Cloud PubSub topic name '",
")",
",",
"required",
"=",
"True",
")",
"known_args",
",",
"pipeline_args",
"=",
"parser",
".",
"parse_known_args",
"(",
"argv",
")",
"pipeline_options",
"=",
"PipelineOptions",
"(",
"pipeline_args",
".",
"append",
"(",
"'--project={}'",
".",
"format",
"(",
"known_args",
".",
"project",
")",
")",
")",
"pipeline_options",
".",
"view_as",
"(",
"SetupOptions",
")",
".",
"save_main_session",
"=",
"True",
"pipeline_options",
".",
"view_as",
"(",
"StandardOptions",
")",
".",
"streaming",
"=",
"True",
"p",
"=",
"beam",
".",
"Pipeline",
"(",
"options",
"=",
"pipeline_options",
")",
"TOPIC",
"=",
"'projects/{}/topics/{}'",
".",
"format",
"(",
"known_args",
".",
"project",
",",
"known_args",
".",
"input_topic",
")",
"# this table needs to exist",
"table_spec",
"=",
"'{}:taxifare.traffic_realtime'",
".",
"format",
"(",
"known_args",
".",
"project",
")",
"def",
"to_bq_format",
"(",
"count",
")",
":",
"\"\"\"BigQuery writer requires rows to be stored as python dictionary\"\"\"",
"return",
"{",
"'trips_last_5min'",
":",
"count",
",",
"'time'",
":",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"\"%Y-%m-%d %H:%M:%S\"",
")",
"}",
"pipeline",
"=",
"(",
"p",
"|",
"'read_from_pubsub'",
">>",
"beam",
".",
"io",
".",
"ReadFromPubSub",
"(",
"topic",
"=",
"TOPIC",
")",
".",
"with_output_types",
"(",
"bytes",
")",
"|",
"'window'",
">>",
"beam",
".",
"WindowInto",
"(",
"window",
".",
"SlidingWindows",
"(",
"size",
"=",
"300",
",",
"period",
"=",
"15",
")",
")",
"|",
"'count'",
">>",
"beam",
".",
"CombineGlobally",
"(",
"CountFn",
"(",
")",
")",
".",
"without_defaults",
"(",
")",
"|",
"'format_for_bq'",
">>",
"beam",
".",
"Map",
"(",
"to_bq_format",
")",
"|",
"'write_to_bq'",
">>",
"beam",
".",
"io",
".",
"WriteToBigQuery",
"(",
"table_spec",
",",
"# WRITE_TRUNCATE not supported for streaming",
"write_disposition",
"=",
"beam",
".",
"io",
".",
"BigQueryDisposition",
".",
"WRITE_APPEND",
",",
"create_disposition",
"=",
"beam",
".",
"io",
".",
"BigQueryDisposition",
".",
"CREATE_NEVER",
")",
")",
"result",
"=",
"p",
".",
"run",
"(",
")"
] | [
34,
0
] | [
80,
20
] | python | en | ['en', 'en', 'en'] | True |
as_base_candidate | (candidate: Candidate) | The runtime version of BaseCandidate. | The runtime version of BaseCandidate. | def as_base_candidate(candidate: Candidate) -> Optional[BaseCandidate]:
"""The runtime version of BaseCandidate."""
base_candidate_classes = (
AlreadyInstalledCandidate,
EditableCandidate,
LinkCandidate,
)
if isinstance(candidate, base_candidate_classes):
return candidate
return None | [
"def",
"as_base_candidate",
"(",
"candidate",
":",
"Candidate",
")",
"->",
"Optional",
"[",
"BaseCandidate",
"]",
":",
"base_candidate_classes",
"=",
"(",
"AlreadyInstalledCandidate",
",",
"EditableCandidate",
",",
"LinkCandidate",
",",
")",
"if",
"isinstance",
"(",
"candidate",
",",
"base_candidate_classes",
")",
":",
"return",
"candidate",
"return",
"None"
] | [
38,
0
] | [
47,
15
] | python | en | ['en', 'en', 'en'] | True |
_InstallRequirementBackedCandidate.project_name | (self) | The normalised name of the project the candidate refers to | The normalised name of the project the candidate refers to | def project_name(self) -> NormalizedName:
"""The normalised name of the project the candidate refers to"""
if self._name is None:
self._name = canonicalize_name(self.dist.project_name)
return self._name | [
"def",
"project_name",
"(",
"self",
")",
"->",
"NormalizedName",
":",
"if",
"self",
".",
"_name",
"is",
"None",
":",
"self",
".",
"_name",
"=",
"canonicalize_name",
"(",
"self",
".",
"dist",
".",
"project_name",
")",
"return",
"self",
".",
"_name"
] | [
179,
4
] | [
183,
25
] | python | en | ['en', 'en', 'en'] | True |
_InstallRequirementBackedCandidate._check_metadata_consistency | (self, dist: Distribution) | Check for consistency of project name and version of dist. | Check for consistency of project name and version of dist. | def _check_metadata_consistency(self, dist: Distribution) -> None:
"""Check for consistency of project name and version of dist."""
canonical_name = canonicalize_name(dist.project_name)
if self._name is not None and self._name != canonical_name:
raise MetadataInconsistent(
self._ireq,
"name",
self._name,
dist.project_name,
)
parsed_version = parse_version(dist.version)
if self._version is not None and self._version != parsed_version:
raise MetadataInconsistent(
self._ireq,
"version",
str(self._version),
dist.version,
) | [
"def",
"_check_metadata_consistency",
"(",
"self",
",",
"dist",
":",
"Distribution",
")",
"->",
"None",
":",
"canonical_name",
"=",
"canonicalize_name",
"(",
"dist",
".",
"project_name",
")",
"if",
"self",
".",
"_name",
"is",
"not",
"None",
"and",
"self",
".",
"_name",
"!=",
"canonical_name",
":",
"raise",
"MetadataInconsistent",
"(",
"self",
".",
"_ireq",
",",
"\"name\"",
",",
"self",
".",
"_name",
",",
"dist",
".",
"project_name",
",",
")",
"parsed_version",
"=",
"parse_version",
"(",
"dist",
".",
"version",
")",
"if",
"self",
".",
"_version",
"is",
"not",
"None",
"and",
"self",
".",
"_version",
"!=",
"parsed_version",
":",
"raise",
"MetadataInconsistent",
"(",
"self",
".",
"_ireq",
",",
"\"version\"",
",",
"str",
"(",
"self",
".",
"_version",
")",
",",
"dist",
".",
"version",
",",
")"
] | [
205,
4
] | [
222,
13
] | python | en | ['en', 'en', 'en'] | True |
ExtrasCandidate.name | (self) | The normalised name of the project the candidate refers to | The normalised name of the project the candidate refers to | def name(self) -> str:
"""The normalised name of the project the candidate refers to"""
return format_name(self.base.project_name, self.extras) | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"format_name",
"(",
"self",
".",
"base",
".",
"project_name",
",",
"self",
".",
"extras",
")"
] | [
457,
4
] | [
459,
63
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceGrpcAsyncIOTransport.create_channel | (
cls,
host: str = "monitoring.googleapis.com",
credentials: credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
**kwargs,
) | Create and return a gRPC AsyncIO channel object.
Args:
address (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is ignored if ``channel`` is provided.
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
kwargs (Optional[dict]): Keyword arguments, which are passed to the
channel creation.
Returns:
aio.Channel: A gRPC AsyncIO channel object.
| Create and return a gRPC AsyncIO channel object.
Args:
address (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is ignored if ``channel`` is provided.
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
kwargs (Optional[dict]): Keyword arguments, which are passed to the
channel creation.
Returns:
aio.Channel: A gRPC AsyncIO channel object.
| def create_channel(
cls,
host: str = "monitoring.googleapis.com",
credentials: credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
**kwargs,
) -> aio.Channel:
"""Create and return a gRPC AsyncIO channel object.
Args:
address (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is ignored if ``channel`` is provided.
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
kwargs (Optional[dict]): Keyword arguments, which are passed to the
channel creation.
Returns:
aio.Channel: A gRPC AsyncIO channel object.
"""
scopes = scopes or cls.AUTH_SCOPES
return grpc_helpers_async.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
scopes=scopes,
quota_project_id=quota_project_id,
**kwargs,
) | [
"def",
"create_channel",
"(",
"cls",
",",
"host",
":",
"str",
"=",
"\"monitoring.googleapis.com\"",
",",
"credentials",
":",
"credentials",
".",
"Credentials",
"=",
"None",
",",
"credentials_file",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"scopes",
":",
"Optional",
"[",
"Sequence",
"[",
"str",
"]",
"]",
"=",
"None",
",",
"quota_project_id",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"*",
"*",
"kwargs",
",",
")",
"->",
"aio",
".",
"Channel",
":",
"scopes",
"=",
"scopes",
"or",
"cls",
".",
"AUTH_SCOPES",
"return",
"grpc_helpers_async",
".",
"create_channel",
"(",
"host",
",",
"credentials",
"=",
"credentials",
",",
"credentials_file",
"=",
"credentials_file",
",",
"scopes",
"=",
"scopes",
",",
"quota_project_id",
"=",
"quota_project_id",
",",
"*",
"*",
"kwargs",
",",
")"
] | [
52,
4
] | [
90,
9
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceGrpcAsyncIOTransport.__init__ | (
self,
*,
host: str = "monitoring.googleapis.com",
credentials: credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: aio.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id=None,
) | Instantiate the transport.
Args:
host (Optional[str]): The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
This argument is ignored if ``channel`` is provided.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is ignored if ``channel`` is provided.
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
channel (Optional[aio.Channel]): A ``Channel`` instance through
which to make calls.
api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If
provided, it overrides the ``host`` argument and tries to create
a mutual TLS channel with client SSL credentials from
``client_cert_source`` or applicatin default SSL credentials.
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A
callback to provide client SSL certificate bytes and private key
bytes, both in PEM format. It is ignored if ``api_mtls_endpoint``
is None.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
Raises:
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
creation failed for any reason.
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
| Instantiate the transport. | def __init__(
self,
*,
host: str = "monitoring.googleapis.com",
credentials: credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: aio.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id=None,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]): The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
This argument is ignored if ``channel`` is provided.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is ignored if ``channel`` is provided.
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
channel (Optional[aio.Channel]): A ``Channel`` instance through
which to make calls.
api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If
provided, it overrides the ``host`` argument and tries to create
a mutual TLS channel with client SSL credentials from
``client_cert_source`` or applicatin default SSL credentials.
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A
callback to provide client SSL certificate bytes and private key
bytes, both in PEM format. It is ignored if ``api_mtls_endpoint``
is None.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
Raises:
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
creation failed for any reason.
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
if channel:
# Sanity check: Ensure that channel and credentials are not both
# provided.
credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
elif api_mtls_endpoint:
host = (
api_mtls_endpoint
if ":" in api_mtls_endpoint
else api_mtls_endpoint + ":443"
)
# Create SSL credentials with client_cert_source or application
# default SSL credentials.
if client_cert_source:
cert, key = client_cert_source()
ssl_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
else:
ssl_credentials = SslCredentials().ssl_credentials
# create a new channel. The provided one is ignored.
self._grpc_channel = type(self).create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
ssl_credentials=ssl_credentials,
scopes=scopes or self.AUTH_SCOPES,
quota_project_id=quota_project_id,
)
# Run the base constructor.
super().__init__(
host=host,
credentials=credentials,
credentials_file=credentials_file,
scopes=scopes or self.AUTH_SCOPES,
quota_project_id=quota_project_id,
)
self._stubs = {} | [
"def",
"__init__",
"(",
"self",
",",
"*",
",",
"host",
":",
"str",
"=",
"\"monitoring.googleapis.com\"",
",",
"credentials",
":",
"credentials",
".",
"Credentials",
"=",
"None",
",",
"credentials_file",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"scopes",
":",
"Optional",
"[",
"Sequence",
"[",
"str",
"]",
"]",
"=",
"None",
",",
"channel",
":",
"aio",
".",
"Channel",
"=",
"None",
",",
"api_mtls_endpoint",
":",
"str",
"=",
"None",
",",
"client_cert_source",
":",
"Callable",
"[",
"[",
"]",
",",
"Tuple",
"[",
"bytes",
",",
"bytes",
"]",
"]",
"=",
"None",
",",
"quota_project_id",
"=",
"None",
",",
")",
"->",
"None",
":",
"if",
"channel",
":",
"# Sanity check: Ensure that channel and credentials are not both",
"# provided.",
"credentials",
"=",
"False",
"# If a channel was explicitly provided, set it.",
"self",
".",
"_grpc_channel",
"=",
"channel",
"elif",
"api_mtls_endpoint",
":",
"host",
"=",
"(",
"api_mtls_endpoint",
"if",
"\":\"",
"in",
"api_mtls_endpoint",
"else",
"api_mtls_endpoint",
"+",
"\":443\"",
")",
"# Create SSL credentials with client_cert_source or application",
"# default SSL credentials.",
"if",
"client_cert_source",
":",
"cert",
",",
"key",
"=",
"client_cert_source",
"(",
")",
"ssl_credentials",
"=",
"grpc",
".",
"ssl_channel_credentials",
"(",
"certificate_chain",
"=",
"cert",
",",
"private_key",
"=",
"key",
")",
"else",
":",
"ssl_credentials",
"=",
"SslCredentials",
"(",
")",
".",
"ssl_credentials",
"# create a new channel. The provided one is ignored.",
"self",
".",
"_grpc_channel",
"=",
"type",
"(",
"self",
")",
".",
"create_channel",
"(",
"host",
",",
"credentials",
"=",
"credentials",
",",
"credentials_file",
"=",
"credentials_file",
",",
"ssl_credentials",
"=",
"ssl_credentials",
",",
"scopes",
"=",
"scopes",
"or",
"self",
".",
"AUTH_SCOPES",
",",
"quota_project_id",
"=",
"quota_project_id",
",",
")",
"# Run the base constructor.",
"super",
"(",
")",
".",
"__init__",
"(",
"host",
"=",
"host",
",",
"credentials",
"=",
"credentials",
",",
"credentials_file",
"=",
"credentials_file",
",",
"scopes",
"=",
"scopes",
"or",
"self",
".",
"AUTH_SCOPES",
",",
"quota_project_id",
"=",
"quota_project_id",
",",
")",
"self",
".",
"_stubs",
"=",
"{",
"}"
] | [
92,
4
] | [
182,
24
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceGrpcAsyncIOTransport.grpc_channel | (self) | Create the channel designed to connect to this service.
This property caches on the instance; repeated calls return
the same channel.
| Create the channel designed to connect to this service. | def grpc_channel(self) -> aio.Channel:
"""Create the channel designed to connect to this service.
This property caches on the instance; repeated calls return
the same channel.
"""
# Sanity check: Only create a new channel if we do not already
# have one.
if not hasattr(self, "_grpc_channel"):
self._grpc_channel = self.create_channel(
self._host, credentials=self._credentials,
)
# Return the channel from cache.
return self._grpc_channel | [
"def",
"grpc_channel",
"(",
"self",
")",
"->",
"aio",
".",
"Channel",
":",
"# Sanity check: Only create a new channel if we do not already",
"# have one.",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_grpc_channel\"",
")",
":",
"self",
".",
"_grpc_channel",
"=",
"self",
".",
"create_channel",
"(",
"self",
".",
"_host",
",",
"credentials",
"=",
"self",
".",
"_credentials",
",",
")",
"# Return the channel from cache.",
"return",
"self",
".",
"_grpc_channel"
] | [
185,
4
] | [
199,
33
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceGrpcAsyncIOTransport.create_dashboard | (
self,
) | r"""Return a callable for the create dashboard method over gRPC.
Creates a new custom dashboard.
This method requires the ``monitoring.dashboards.create``
permission on the specified project. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Returns:
Callable[[~.CreateDashboardRequest],
Awaitable[~.Dashboard]]:
A function that, when called, will call the underlying RPC
on the server.
| r"""Return a callable for the create dashboard method over gRPC. | def create_dashboard(
self,
) -> Callable[
[dashboards_service.CreateDashboardRequest], Awaitable[dashboard.Dashboard]
]:
r"""Return a callable for the create dashboard method over gRPC.
Creates a new custom dashboard.
This method requires the ``monitoring.dashboards.create``
permission on the specified project. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Returns:
Callable[[~.CreateDashboardRequest],
Awaitable[~.Dashboard]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "create_dashboard" not in self._stubs:
self._stubs["create_dashboard"] = self.grpc_channel.unary_unary(
"/google.monitoring.dashboard.v1.DashboardsService/CreateDashboard",
request_serializer=dashboards_service.CreateDashboardRequest.serialize,
response_deserializer=dashboard.Dashboard.deserialize,
)
return self._stubs["create_dashboard"] | [
"def",
"create_dashboard",
"(",
"self",
",",
")",
"->",
"Callable",
"[",
"[",
"dashboards_service",
".",
"CreateDashboardRequest",
"]",
",",
"Awaitable",
"[",
"dashboard",
".",
"Dashboard",
"]",
"]",
":",
"# Generate a \"stub function\" on-the-fly which will actually make",
"# the request.",
"# gRPC handles serialization and deserialization, so we just need",
"# to pass in the functions for each.",
"if",
"\"create_dashboard\"",
"not",
"in",
"self",
".",
"_stubs",
":",
"self",
".",
"_stubs",
"[",
"\"create_dashboard\"",
"]",
"=",
"self",
".",
"grpc_channel",
".",
"unary_unary",
"(",
"\"/google.monitoring.dashboard.v1.DashboardsService/CreateDashboard\"",
",",
"request_serializer",
"=",
"dashboards_service",
".",
"CreateDashboardRequest",
".",
"serialize",
",",
"response_deserializer",
"=",
"dashboard",
".",
"Dashboard",
".",
"deserialize",
",",
")",
"return",
"self",
".",
"_stubs",
"[",
"\"create_dashboard\"",
"]"
] | [
202,
4
] | [
231,
46
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceGrpcAsyncIOTransport.list_dashboards | (
self,
) | r"""Return a callable for the list dashboards method over gRPC.
Lists the existing dashboards.
This method requires the ``monitoring.dashboards.list``
permission on the specified project. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Returns:
Callable[[~.ListDashboardsRequest],
Awaitable[~.ListDashboardsResponse]]:
A function that, when called, will call the underlying RPC
on the server.
| r"""Return a callable for the list dashboards method over gRPC. | def list_dashboards(
self,
) -> Callable[
[dashboards_service.ListDashboardsRequest],
Awaitable[dashboards_service.ListDashboardsResponse],
]:
r"""Return a callable for the list dashboards method over gRPC.
Lists the existing dashboards.
This method requires the ``monitoring.dashboards.list``
permission on the specified project. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Returns:
Callable[[~.ListDashboardsRequest],
Awaitable[~.ListDashboardsResponse]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "list_dashboards" not in self._stubs:
self._stubs["list_dashboards"] = self.grpc_channel.unary_unary(
"/google.monitoring.dashboard.v1.DashboardsService/ListDashboards",
request_serializer=dashboards_service.ListDashboardsRequest.serialize,
response_deserializer=dashboards_service.ListDashboardsResponse.deserialize,
)
return self._stubs["list_dashboards"] | [
"def",
"list_dashboards",
"(",
"self",
",",
")",
"->",
"Callable",
"[",
"[",
"dashboards_service",
".",
"ListDashboardsRequest",
"]",
",",
"Awaitable",
"[",
"dashboards_service",
".",
"ListDashboardsResponse",
"]",
",",
"]",
":",
"# Generate a \"stub function\" on-the-fly which will actually make",
"# the request.",
"# gRPC handles serialization and deserialization, so we just need",
"# to pass in the functions for each.",
"if",
"\"list_dashboards\"",
"not",
"in",
"self",
".",
"_stubs",
":",
"self",
".",
"_stubs",
"[",
"\"list_dashboards\"",
"]",
"=",
"self",
".",
"grpc_channel",
".",
"unary_unary",
"(",
"\"/google.monitoring.dashboard.v1.DashboardsService/ListDashboards\"",
",",
"request_serializer",
"=",
"dashboards_service",
".",
"ListDashboardsRequest",
".",
"serialize",
",",
"response_deserializer",
"=",
"dashboards_service",
".",
"ListDashboardsResponse",
".",
"deserialize",
",",
")",
"return",
"self",
".",
"_stubs",
"[",
"\"list_dashboards\"",
"]"
] | [
234,
4
] | [
264,
45
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceGrpcAsyncIOTransport.get_dashboard | (
self,
) | r"""Return a callable for the get dashboard method over gRPC.
Fetches a specific dashboard.
This method requires the ``monitoring.dashboards.get``
permission on the specified dashboard. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Returns:
Callable[[~.GetDashboardRequest],
Awaitable[~.Dashboard]]:
A function that, when called, will call the underlying RPC
on the server.
| r"""Return a callable for the get dashboard method over gRPC. | def get_dashboard(
self,
) -> Callable[
[dashboards_service.GetDashboardRequest], Awaitable[dashboard.Dashboard]
]:
r"""Return a callable for the get dashboard method over gRPC.
Fetches a specific dashboard.
This method requires the ``monitoring.dashboards.get``
permission on the specified dashboard. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Returns:
Callable[[~.GetDashboardRequest],
Awaitable[~.Dashboard]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_dashboard" not in self._stubs:
self._stubs["get_dashboard"] = self.grpc_channel.unary_unary(
"/google.monitoring.dashboard.v1.DashboardsService/GetDashboard",
request_serializer=dashboards_service.GetDashboardRequest.serialize,
response_deserializer=dashboard.Dashboard.deserialize,
)
return self._stubs["get_dashboard"] | [
"def",
"get_dashboard",
"(",
"self",
",",
")",
"->",
"Callable",
"[",
"[",
"dashboards_service",
".",
"GetDashboardRequest",
"]",
",",
"Awaitable",
"[",
"dashboard",
".",
"Dashboard",
"]",
"]",
":",
"# Generate a \"stub function\" on-the-fly which will actually make",
"# the request.",
"# gRPC handles serialization and deserialization, so we just need",
"# to pass in the functions for each.",
"if",
"\"get_dashboard\"",
"not",
"in",
"self",
".",
"_stubs",
":",
"self",
".",
"_stubs",
"[",
"\"get_dashboard\"",
"]",
"=",
"self",
".",
"grpc_channel",
".",
"unary_unary",
"(",
"\"/google.monitoring.dashboard.v1.DashboardsService/GetDashboard\"",
",",
"request_serializer",
"=",
"dashboards_service",
".",
"GetDashboardRequest",
".",
"serialize",
",",
"response_deserializer",
"=",
"dashboard",
".",
"Dashboard",
".",
"deserialize",
",",
")",
"return",
"self",
".",
"_stubs",
"[",
"\"get_dashboard\"",
"]"
] | [
267,
4
] | [
296,
43
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceGrpcAsyncIOTransport.delete_dashboard | (
self,
) | r"""Return a callable for the delete dashboard method over gRPC.
Deletes an existing custom dashboard.
This method requires the ``monitoring.dashboards.delete``
permission on the specified dashboard. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Returns:
Callable[[~.DeleteDashboardRequest],
Awaitable[~.Empty]]:
A function that, when called, will call the underlying RPC
on the server.
| r"""Return a callable for the delete dashboard method over gRPC. | def delete_dashboard(
self,
) -> Callable[[dashboards_service.DeleteDashboardRequest], Awaitable[empty.Empty]]:
r"""Return a callable for the delete dashboard method over gRPC.
Deletes an existing custom dashboard.
This method requires the ``monitoring.dashboards.delete``
permission on the specified dashboard. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Returns:
Callable[[~.DeleteDashboardRequest],
Awaitable[~.Empty]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "delete_dashboard" not in self._stubs:
self._stubs["delete_dashboard"] = self.grpc_channel.unary_unary(
"/google.monitoring.dashboard.v1.DashboardsService/DeleteDashboard",
request_serializer=dashboards_service.DeleteDashboardRequest.serialize,
response_deserializer=empty.Empty.FromString,
)
return self._stubs["delete_dashboard"] | [
"def",
"delete_dashboard",
"(",
"self",
",",
")",
"->",
"Callable",
"[",
"[",
"dashboards_service",
".",
"DeleteDashboardRequest",
"]",
",",
"Awaitable",
"[",
"empty",
".",
"Empty",
"]",
"]",
":",
"# Generate a \"stub function\" on-the-fly which will actually make",
"# the request.",
"# gRPC handles serialization and deserialization, so we just need",
"# to pass in the functions for each.",
"if",
"\"delete_dashboard\"",
"not",
"in",
"self",
".",
"_stubs",
":",
"self",
".",
"_stubs",
"[",
"\"delete_dashboard\"",
"]",
"=",
"self",
".",
"grpc_channel",
".",
"unary_unary",
"(",
"\"/google.monitoring.dashboard.v1.DashboardsService/DeleteDashboard\"",
",",
"request_serializer",
"=",
"dashboards_service",
".",
"DeleteDashboardRequest",
".",
"serialize",
",",
"response_deserializer",
"=",
"empty",
".",
"Empty",
".",
"FromString",
",",
")",
"return",
"self",
".",
"_stubs",
"[",
"\"delete_dashboard\"",
"]"
] | [
299,
4
] | [
326,
46
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceGrpcAsyncIOTransport.update_dashboard | (
self,
) | r"""Return a callable for the update dashboard method over gRPC.
Replaces an existing custom dashboard with a new definition.
This method requires the ``monitoring.dashboards.update``
permission on the specified dashboard. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Returns:
Callable[[~.UpdateDashboardRequest],
Awaitable[~.Dashboard]]:
A function that, when called, will call the underlying RPC
on the server.
| r"""Return a callable for the update dashboard method over gRPC. | def update_dashboard(
self,
) -> Callable[
[dashboards_service.UpdateDashboardRequest], Awaitable[dashboard.Dashboard]
]:
r"""Return a callable for the update dashboard method over gRPC.
Replaces an existing custom dashboard with a new definition.
This method requires the ``monitoring.dashboards.update``
permission on the specified dashboard. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Returns:
Callable[[~.UpdateDashboardRequest],
Awaitable[~.Dashboard]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "update_dashboard" not in self._stubs:
self._stubs["update_dashboard"] = self.grpc_channel.unary_unary(
"/google.monitoring.dashboard.v1.DashboardsService/UpdateDashboard",
request_serializer=dashboards_service.UpdateDashboardRequest.serialize,
response_deserializer=dashboard.Dashboard.deserialize,
)
return self._stubs["update_dashboard"] | [
"def",
"update_dashboard",
"(",
"self",
",",
")",
"->",
"Callable",
"[",
"[",
"dashboards_service",
".",
"UpdateDashboardRequest",
"]",
",",
"Awaitable",
"[",
"dashboard",
".",
"Dashboard",
"]",
"]",
":",
"# Generate a \"stub function\" on-the-fly which will actually make",
"# the request.",
"# gRPC handles serialization and deserialization, so we just need",
"# to pass in the functions for each.",
"if",
"\"update_dashboard\"",
"not",
"in",
"self",
".",
"_stubs",
":",
"self",
".",
"_stubs",
"[",
"\"update_dashboard\"",
"]",
"=",
"self",
".",
"grpc_channel",
".",
"unary_unary",
"(",
"\"/google.monitoring.dashboard.v1.DashboardsService/UpdateDashboard\"",
",",
"request_serializer",
"=",
"dashboards_service",
".",
"UpdateDashboardRequest",
".",
"serialize",
",",
"response_deserializer",
"=",
"dashboard",
".",
"Dashboard",
".",
"deserialize",
",",
")",
"return",
"self",
".",
"_stubs",
"[",
"\"update_dashboard\"",
"]"
] | [
329,
4
] | [
358,
46
] | python | en | ['en', 'en', 'en'] | True |
command_urls | (bot, user, channel, args) | Prints the titles of URLs linked in the channel. Usage: urls [on|off] | Prints the titles of URLs linked in the channel. Usage: urls [on|off] | def command_urls(bot, user, channel, args):
"Prints the titles of URLs linked in the channel. Usage: urls [on|off]"
if permissions(user) < 10: # 10 == admin, 20 == superadmin
return bot.say(channel,
"{}, your permission level is not high enough.".format(
get_nick(user)))
if args == "off" and bot.factory.urltitles_enabled:
bot.factory.urltitles_enabled = False
log.debug("URL title display disabled.")
return bot.say(channel, "URL title display is now disabled.")
elif args == "on" and not bot.factory.urltitles_enabled:
bot.factory.urltitles_enabled = True
log.debug("URL title display enabled.")
return bot.say(channel, "URL title display is now enabled.")
else:
if bot.factory.urltitles_enabled:
return bot.say(channel,
"URL title display is enabled. Use {}urls off to disable."
.format(bot.lead))
else:
return bot.say(channel,
"URL title display is disabled. Use {}urls on to enable."
.format(bot.lead)) | [
"def",
"command_urls",
"(",
"bot",
",",
"user",
",",
"channel",
",",
"args",
")",
":",
"if",
"permissions",
"(",
"user",
")",
"<",
"10",
":",
"# 10 == admin, 20 == superadmin",
"return",
"bot",
".",
"say",
"(",
"channel",
",",
"\"{}, your permission level is not high enough.\"",
".",
"format",
"(",
"get_nick",
"(",
"user",
")",
")",
")",
"if",
"args",
"==",
"\"off\"",
"and",
"bot",
".",
"factory",
".",
"urltitles_enabled",
":",
"bot",
".",
"factory",
".",
"urltitles_enabled",
"=",
"False",
"log",
".",
"debug",
"(",
"\"URL title display disabled.\"",
")",
"return",
"bot",
".",
"say",
"(",
"channel",
",",
"\"URL title display is now disabled.\"",
")",
"elif",
"args",
"==",
"\"on\"",
"and",
"not",
"bot",
".",
"factory",
".",
"urltitles_enabled",
":",
"bot",
".",
"factory",
".",
"urltitles_enabled",
"=",
"True",
"log",
".",
"debug",
"(",
"\"URL title display enabled.\"",
")",
"return",
"bot",
".",
"say",
"(",
"channel",
",",
"\"URL title display is now enabled.\"",
")",
"else",
":",
"if",
"bot",
".",
"factory",
".",
"urltitles_enabled",
":",
"return",
"bot",
".",
"say",
"(",
"channel",
",",
"\"URL title display is enabled. Use {}urls off to disable.\"",
".",
"format",
"(",
"bot",
".",
"lead",
")",
")",
"else",
":",
"return",
"bot",
".",
"say",
"(",
"channel",
",",
"\"URL title display is disabled. Use {}urls on to enable.\"",
".",
"format",
"(",
"bot",
".",
"lead",
")",
")"
] | [
6,
0
] | [
29,
34
] | python | en | ['en', 'en', 'en'] | True |
write_pkg_file | (self, file) | Write the PKG-INFO format data to a file object.
| Write the PKG-INFO format data to a file object.
| def write_pkg_file(self, file):
"""Write the PKG-INFO format data to a file object.
"""
version = get_metadata_version(self)
file.write('Metadata-Version: %s\n' % version)
file.write('Name: %s\n' % self.get_name())
file.write('Version: %s\n' % self.get_version())
file.write('Summary: %s\n' % self.get_description())
file.write('Home-page: %s\n' % self.get_url())
if version < StrictVersion('1.2'):
file.write('Author: %s\n' % self.get_contact())
file.write('Author-email: %s\n' % self.get_contact_email())
else:
optional_fields = (
('Author', 'author'),
('Author-email', 'author_email'),
('Maintainer', 'maintainer'),
('Maintainer-email', 'maintainer_email'),
)
for field, attr in optional_fields:
attr_val = getattr(self, attr)
if six.PY2:
attr_val = self._encode_field(attr_val)
if attr_val is not None:
file.write('%s: %s\n' % (field, attr_val))
file.write('License: %s\n' % self.get_license())
if self.download_url:
file.write('Download-URL: %s\n' % self.download_url)
for project_url in self.project_urls.items():
file.write('Project-URL: %s, %s\n' % project_url)
long_desc = rfc822_escape(self.get_long_description())
file.write('Description: %s\n' % long_desc)
keywords = ','.join(self.get_keywords())
if keywords:
file.write('Keywords: %s\n' % keywords)
if version >= StrictVersion('1.2'):
for platform in self.get_platforms():
file.write('Platform: %s\n' % platform)
else:
self._write_list(file, 'Platform', self.get_platforms())
self._write_list(file, 'Classifier', self.get_classifiers())
# PEP 314
self._write_list(file, 'Requires', self.get_requires())
self._write_list(file, 'Provides', self.get_provides())
self._write_list(file, 'Obsoletes', self.get_obsoletes())
# Setuptools specific for PEP 345
if hasattr(self, 'python_requires'):
file.write('Requires-Python: %s\n' % self.python_requires)
# PEP 566
if self.long_description_content_type:
file.write(
'Description-Content-Type: %s\n' %
self.long_description_content_type
)
if self.provides_extras:
for extra in sorted(self.provides_extras):
file.write('Provides-Extra: %s\n' % extra) | [
"def",
"write_pkg_file",
"(",
"self",
",",
"file",
")",
":",
"version",
"=",
"get_metadata_version",
"(",
"self",
")",
"file",
".",
"write",
"(",
"'Metadata-Version: %s\\n'",
"%",
"version",
")",
"file",
".",
"write",
"(",
"'Name: %s\\n'",
"%",
"self",
".",
"get_name",
"(",
")",
")",
"file",
".",
"write",
"(",
"'Version: %s\\n'",
"%",
"self",
".",
"get_version",
"(",
")",
")",
"file",
".",
"write",
"(",
"'Summary: %s\\n'",
"%",
"self",
".",
"get_description",
"(",
")",
")",
"file",
".",
"write",
"(",
"'Home-page: %s\\n'",
"%",
"self",
".",
"get_url",
"(",
")",
")",
"if",
"version",
"<",
"StrictVersion",
"(",
"'1.2'",
")",
":",
"file",
".",
"write",
"(",
"'Author: %s\\n'",
"%",
"self",
".",
"get_contact",
"(",
")",
")",
"file",
".",
"write",
"(",
"'Author-email: %s\\n'",
"%",
"self",
".",
"get_contact_email",
"(",
")",
")",
"else",
":",
"optional_fields",
"=",
"(",
"(",
"'Author'",
",",
"'author'",
")",
",",
"(",
"'Author-email'",
",",
"'author_email'",
")",
",",
"(",
"'Maintainer'",
",",
"'maintainer'",
")",
",",
"(",
"'Maintainer-email'",
",",
"'maintainer_email'",
")",
",",
")",
"for",
"field",
",",
"attr",
"in",
"optional_fields",
":",
"attr_val",
"=",
"getattr",
"(",
"self",
",",
"attr",
")",
"if",
"six",
".",
"PY2",
":",
"attr_val",
"=",
"self",
".",
"_encode_field",
"(",
"attr_val",
")",
"if",
"attr_val",
"is",
"not",
"None",
":",
"file",
".",
"write",
"(",
"'%s: %s\\n'",
"%",
"(",
"field",
",",
"attr_val",
")",
")",
"file",
".",
"write",
"(",
"'License: %s\\n'",
"%",
"self",
".",
"get_license",
"(",
")",
")",
"if",
"self",
".",
"download_url",
":",
"file",
".",
"write",
"(",
"'Download-URL: %s\\n'",
"%",
"self",
".",
"download_url",
")",
"for",
"project_url",
"in",
"self",
".",
"project_urls",
".",
"items",
"(",
")",
":",
"file",
".",
"write",
"(",
"'Project-URL: %s, %s\\n'",
"%",
"project_url",
")",
"long_desc",
"=",
"rfc822_escape",
"(",
"self",
".",
"get_long_description",
"(",
")",
")",
"file",
".",
"write",
"(",
"'Description: %s\\n'",
"%",
"long_desc",
")",
"keywords",
"=",
"','",
".",
"join",
"(",
"self",
".",
"get_keywords",
"(",
")",
")",
"if",
"keywords",
":",
"file",
".",
"write",
"(",
"'Keywords: %s\\n'",
"%",
"keywords",
")",
"if",
"version",
">=",
"StrictVersion",
"(",
"'1.2'",
")",
":",
"for",
"platform",
"in",
"self",
".",
"get_platforms",
"(",
")",
":",
"file",
".",
"write",
"(",
"'Platform: %s\\n'",
"%",
"platform",
")",
"else",
":",
"self",
".",
"_write_list",
"(",
"file",
",",
"'Platform'",
",",
"self",
".",
"get_platforms",
"(",
")",
")",
"self",
".",
"_write_list",
"(",
"file",
",",
"'Classifier'",
",",
"self",
".",
"get_classifiers",
"(",
")",
")",
"# PEP 314",
"self",
".",
"_write_list",
"(",
"file",
",",
"'Requires'",
",",
"self",
".",
"get_requires",
"(",
")",
")",
"self",
".",
"_write_list",
"(",
"file",
",",
"'Provides'",
",",
"self",
".",
"get_provides",
"(",
")",
")",
"self",
".",
"_write_list",
"(",
"file",
",",
"'Obsoletes'",
",",
"self",
".",
"get_obsoletes",
"(",
")",
")",
"# Setuptools specific for PEP 345",
"if",
"hasattr",
"(",
"self",
",",
"'python_requires'",
")",
":",
"file",
".",
"write",
"(",
"'Requires-Python: %s\\n'",
"%",
"self",
".",
"python_requires",
")",
"# PEP 566",
"if",
"self",
".",
"long_description_content_type",
":",
"file",
".",
"write",
"(",
"'Description-Content-Type: %s\\n'",
"%",
"self",
".",
"long_description_content_type",
")",
"if",
"self",
".",
"provides_extras",
":",
"for",
"extra",
"in",
"sorted",
"(",
"self",
".",
"provides_extras",
")",
":",
"file",
".",
"write",
"(",
"'Provides-Extra: %s\\n'",
"%",
"extra",
")"
] | [
54,
0
] | [
122,
54
] | python | en | ['en', 'en', 'en'] | True |
write_pkg_info | (self, base_dir) | Write the PKG-INFO file into the release tree.
| Write the PKG-INFO file into the release tree.
| def write_pkg_info(self, base_dir):
"""Write the PKG-INFO file into the release tree.
"""
with open(os.path.join(base_dir, 'PKG-INFO'), 'w',
encoding='UTF-8') as pkg_info:
self.write_pkg_file(pkg_info) | [
"def",
"write_pkg_info",
"(",
"self",
",",
"base_dir",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base_dir",
",",
"'PKG-INFO'",
")",
",",
"'w'",
",",
"encoding",
"=",
"'UTF-8'",
")",
"as",
"pkg_info",
":",
"self",
".",
"write_pkg_file",
"(",
"pkg_info",
")"
] | [
126,
0
] | [
131,
37
] | python | en | ['en', 'en', 'en'] | True |
assert_string_list | (dist, attr, value) | Verify that value is a string list or None | Verify that value is a string list or None | def assert_string_list(dist, attr, value):
"""Verify that value is a string list or None"""
try:
assert ''.join(value) != value
except (TypeError, ValueError, AttributeError, AssertionError):
raise DistutilsSetupError(
"%r must be a list of strings (got %r)" % (attr, value)
) | [
"def",
"assert_string_list",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"try",
":",
"assert",
"''",
".",
"join",
"(",
"value",
")",
"!=",
"value",
"except",
"(",
"TypeError",
",",
"ValueError",
",",
"AttributeError",
",",
"AssertionError",
")",
":",
"raise",
"DistutilsSetupError",
"(",
"\"%r must be a list of strings (got %r)\"",
"%",
"(",
"attr",
",",
"value",
")",
")"
] | [
148,
0
] | [
155,
9
] | python | en | ['en', 'en', 'en'] | True |
check_nsp | (dist, attr, value) | Verify that namespace packages are valid | Verify that namespace packages are valid | def check_nsp(dist, attr, value):
"""Verify that namespace packages are valid"""
ns_packages = value
assert_string_list(dist, attr, ns_packages)
for nsp in ns_packages:
if not dist.has_contents_for(nsp):
raise DistutilsSetupError(
"Distribution contains no modules or packages for " +
"namespace package %r" % nsp
)
parent, sep, child = nsp.rpartition('.')
if parent and parent not in ns_packages:
distutils.log.warn(
"WARNING: %r is declared as a package namespace, but %r"
" is not: please correct this in setup.py", nsp, parent
) | [
"def",
"check_nsp",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"ns_packages",
"=",
"value",
"assert_string_list",
"(",
"dist",
",",
"attr",
",",
"ns_packages",
")",
"for",
"nsp",
"in",
"ns_packages",
":",
"if",
"not",
"dist",
".",
"has_contents_for",
"(",
"nsp",
")",
":",
"raise",
"DistutilsSetupError",
"(",
"\"Distribution contains no modules or packages for \"",
"+",
"\"namespace package %r\"",
"%",
"nsp",
")",
"parent",
",",
"sep",
",",
"child",
"=",
"nsp",
".",
"rpartition",
"(",
"'.'",
")",
"if",
"parent",
"and",
"parent",
"not",
"in",
"ns_packages",
":",
"distutils",
".",
"log",
".",
"warn",
"(",
"\"WARNING: %r is declared as a package namespace, but %r\"",
"\" is not: please correct this in setup.py\"",
",",
"nsp",
",",
"parent",
")"
] | [
158,
0
] | [
173,
13
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.