repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
jic-dtool/dtool-http
dtool_http/server.py
DtoolHTTPRequestHandler.generate_http_manifest
def generate_http_manifest(self): """Return http manifest. The http manifest is the resource that defines a dataset as HTTP enabled (published). """ base_path = os.path.dirname(self.translate_path(self.path)) self.dataset = dtoolcore.DataSet.from_uri(base_path) ...
python
def generate_http_manifest(self): """Return http manifest. The http manifest is the resource that defines a dataset as HTTP enabled (published). """ base_path = os.path.dirname(self.translate_path(self.path)) self.dataset = dtoolcore.DataSet.from_uri(base_path) ...
[ "def", "generate_http_manifest", "(", "self", ")", ":", "base_path", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "translate_path", "(", "self", ".", "path", ")", ")", "self", ".", "dataset", "=", "dtoolcore", ".", "DataSet", ".", "from_uri"...
Return http manifest. The http manifest is the resource that defines a dataset as HTTP enabled (published).
[ "Return", "http", "manifest", "." ]
7572221b07d5294aa9ead5097a4f16478837e742
https://github.com/jic-dtool/dtool-http/blob/7572221b07d5294aa9ead5097a4f16478837e742/dtool_http/server.py#L43-L63
train
57,000
jic-dtool/dtool-http
dtool_http/server.py
DtoolHTTPRequestHandler.do_GET
def do_GET(self): """Override inherited do_GET method. Include logic for returning a http manifest when the URL ends with "http_manifest.json". """ if self.path.endswith("http_manifest.json"): try: manifest = self.generate_http_manifest() ...
python
def do_GET(self): """Override inherited do_GET method. Include logic for returning a http manifest when the URL ends with "http_manifest.json". """ if self.path.endswith("http_manifest.json"): try: manifest = self.generate_http_manifest() ...
[ "def", "do_GET", "(", "self", ")", ":", "if", "self", ".", "path", ".", "endswith", "(", "\"http_manifest.json\"", ")", ":", "try", ":", "manifest", "=", "self", ".", "generate_http_manifest", "(", ")", "self", ".", "send_response", "(", "200", ")", "sel...
Override inherited do_GET method. Include logic for returning a http manifest when the URL ends with "http_manifest.json".
[ "Override", "inherited", "do_GET", "method", "." ]
7572221b07d5294aa9ead5097a4f16478837e742
https://github.com/jic-dtool/dtool-http/blob/7572221b07d5294aa9ead5097a4f16478837e742/dtool_http/server.py#L65-L82
train
57,001
chaosim/dao
dao/compilebase.py
Compiler.indent
def indent(self, code, level=1): '''python's famous indent''' lines = code.split('\n') lines = tuple(self.indent_space*level + line for line in lines) return '\n'.join(lines)
python
def indent(self, code, level=1): '''python's famous indent''' lines = code.split('\n') lines = tuple(self.indent_space*level + line for line in lines) return '\n'.join(lines)
[ "def", "indent", "(", "self", ",", "code", ",", "level", "=", "1", ")", ":", "lines", "=", "code", ".", "split", "(", "'\\n'", ")", "lines", "=", "tuple", "(", "self", ".", "indent_space", "*", "level", "+", "line", "for", "line", "in", "lines", ...
python's famous indent
[ "python", "s", "famous", "indent" ]
d7ba65c98ee063aefd1ff4eabb192d1536fdbaaa
https://github.com/chaosim/dao/blob/d7ba65c98ee063aefd1ff4eabb192d1536fdbaaa/dao/compilebase.py#L100-L104
train
57,002
ymotongpoo/pyoauth2
pyoauth2/client.py
OAuth2AuthorizationFlow.retrieve_authorization_code
def retrieve_authorization_code(self, redirect_func=None): """ retrieve authorization code to get access token """ request_param = { "client_id": self.client_id, "redirect_uri": self.redirect_uri, } if self.scope: request_param['s...
python
def retrieve_authorization_code(self, redirect_func=None): """ retrieve authorization code to get access token """ request_param = { "client_id": self.client_id, "redirect_uri": self.redirect_uri, } if self.scope: request_param['s...
[ "def", "retrieve_authorization_code", "(", "self", ",", "redirect_func", "=", "None", ")", ":", "request_param", "=", "{", "\"client_id\"", ":", "self", ".", "client_id", ",", "\"redirect_uri\"", ":", "self", ".", "redirect_uri", ",", "}", "if", "self", ".", ...
retrieve authorization code to get access token
[ "retrieve", "authorization", "code", "to", "get", "access", "token" ]
7fddaf5fba190cfbc025961ce5948267d3d688ad
https://github.com/ymotongpoo/pyoauth2/blob/7fddaf5fba190cfbc025961ce5948267d3d688ad/pyoauth2/client.py#L121-L145
train
57,003
ymotongpoo/pyoauth2
pyoauth2/client.py
OAuth2AuthorizationFlow.retrieve_token
def retrieve_token(self): """ retrieve access token with code fetched via retrieve_authorization_code method. """ if self.authorization_code: request_param = { "client_id": self.client_id, "client_secret": self.client_secret, ...
python
def retrieve_token(self): """ retrieve access token with code fetched via retrieve_authorization_code method. """ if self.authorization_code: request_param = { "client_id": self.client_id, "client_secret": self.client_secret, ...
[ "def", "retrieve_token", "(", "self", ")", ":", "if", "self", ".", "authorization_code", ":", "request_param", "=", "{", "\"client_id\"", ":", "self", ".", "client_id", ",", "\"client_secret\"", ":", "self", ".", "client_secret", ",", "\"redirect_uri\"", ":", ...
retrieve access token with code fetched via retrieve_authorization_code method.
[ "retrieve", "access", "token", "with", "code", "fetched", "via", "retrieve_authorization_code", "method", "." ]
7fddaf5fba190cfbc025961ce5948267d3d688ad
https://github.com/ymotongpoo/pyoauth2/blob/7fddaf5fba190cfbc025961ce5948267d3d688ad/pyoauth2/client.py#L151-L181
train
57,004
TissueMAPS/TmDeploy
tmdeploy/config.py
_SetupSection.to_dict
def to_dict(self): '''Represents the setup section in form of key-value pairs. Returns ------- dict ''' mapping = dict() for attr in dir(self): if attr.startswith('_'): continue if not isinstance(getattr(self.__class__, att...
python
def to_dict(self): '''Represents the setup section in form of key-value pairs. Returns ------- dict ''' mapping = dict() for attr in dir(self): if attr.startswith('_'): continue if not isinstance(getattr(self.__class__, att...
[ "def", "to_dict", "(", "self", ")", ":", "mapping", "=", "dict", "(", ")", "for", "attr", "in", "dir", "(", "self", ")", ":", "if", "attr", ".", "startswith", "(", "'_'", ")", ":", "continue", "if", "not", "isinstance", "(", "getattr", "(", "self",...
Represents the setup section in form of key-value pairs. Returns ------- dict
[ "Represents", "the", "setup", "section", "in", "form", "of", "key", "-", "value", "pairs", "." ]
f891b4ffb21431988bc4a063ae871da3bf284a45
https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/tmdeploy/config.py#L112-L138
train
57,005
hackedd/gw2api
gw2api/util.py
mtime
def mtime(path): """Get the modification time of a file, or -1 if the file does not exist. """ if not os.path.exists(path): return -1 stat = os.stat(path) return stat.st_mtime
python
def mtime(path): """Get the modification time of a file, or -1 if the file does not exist. """ if not os.path.exists(path): return -1 stat = os.stat(path) return stat.st_mtime
[ "def", "mtime", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "-", "1", "stat", "=", "os", ".", "stat", "(", "path", ")", "return", "stat", ".", "st_mtime" ]
Get the modification time of a file, or -1 if the file does not exist.
[ "Get", "the", "modification", "time", "of", "a", "file", "or", "-", "1", "if", "the", "file", "does", "not", "exist", "." ]
5543a78e6e3ed0573b7e84c142c44004b4779eac
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/util.py#L14-L20
train
57,006
hackedd/gw2api
gw2api/util.py
encode_coin_link
def encode_coin_link(copper, silver=0, gold=0): """Encode a chat link for an amount of coins. """ return encode_chat_link(gw2api.TYPE_COIN, copper=copper, silver=silver, gold=gold)
python
def encode_coin_link(copper, silver=0, gold=0): """Encode a chat link for an amount of coins. """ return encode_chat_link(gw2api.TYPE_COIN, copper=copper, silver=silver, gold=gold)
[ "def", "encode_coin_link", "(", "copper", ",", "silver", "=", "0", ",", "gold", "=", "0", ")", ":", "return", "encode_chat_link", "(", "gw2api", ".", "TYPE_COIN", ",", "copper", "=", "copper", ",", "silver", "=", "silver", ",", "gold", "=", "gold", ")"...
Encode a chat link for an amount of coins.
[ "Encode", "a", "chat", "link", "for", "an", "amount", "of", "coins", "." ]
5543a78e6e3ed0573b7e84c142c44004b4779eac
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/util.py#L72-L76
train
57,007
tradenity/python-sdk
tradenity/resources/store_credit_payment.py
StoreCreditPayment.status
def status(self, status): """Sets the status of this StoreCreditPayment. :param status: The status of this StoreCreditPayment. :type: str """ allowed_values = ["pending", "awaitingRetry", "successful", "failed"] if status is not None and status not in allowed_values: ...
python
def status(self, status): """Sets the status of this StoreCreditPayment. :param status: The status of this StoreCreditPayment. :type: str """ allowed_values = ["pending", "awaitingRetry", "successful", "failed"] if status is not None and status not in allowed_values: ...
[ "def", "status", "(", "self", ",", "status", ")", ":", "allowed_values", "=", "[", "\"pending\"", ",", "\"awaitingRetry\"", ",", "\"successful\"", ",", "\"failed\"", "]", "if", "status", "is", "not", "None", "and", "status", "not", "in", "allowed_values", ":...
Sets the status of this StoreCreditPayment. :param status: The status of this StoreCreditPayment. :type: str
[ "Sets", "the", "status", "of", "this", "StoreCreditPayment", "." ]
d13fbe23f4d6ff22554c6d8d2deaf209371adaf1
https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/store_credit_payment.py#L203-L217
train
57,008
inveniosoftware-attic/invenio-utils
invenio_utils/html.py
nmtoken_from_string
def nmtoken_from_string(text): """ Returns a Nmtoken from a string. It is useful to produce XHTML valid values for the 'name' attribute of an anchor. CAUTION: the function is surjective: 2 different texts might lead to the same result. This is improbable on a single page. Nmtoken is the ty...
python
def nmtoken_from_string(text): """ Returns a Nmtoken from a string. It is useful to produce XHTML valid values for the 'name' attribute of an anchor. CAUTION: the function is surjective: 2 different texts might lead to the same result. This is improbable on a single page. Nmtoken is the ty...
[ "def", "nmtoken_from_string", "(", "text", ")", ":", "text", "=", "text", ".", "replace", "(", "'-'", ",", "'--'", ")", "return", "''", ".", "join", "(", "[", "(", "(", "(", "not", "char", ".", "isalnum", "(", ")", "and", "char", "not", "in", "["...
Returns a Nmtoken from a string. It is useful to produce XHTML valid values for the 'name' attribute of an anchor. CAUTION: the function is surjective: 2 different texts might lead to the same result. This is improbable on a single page. Nmtoken is the type that is a mixture of characters supporte...
[ "Returns", "a", "Nmtoken", "from", "a", "string", ".", "It", "is", "useful", "to", "produce", "XHTML", "valid", "values", "for", "the", "name", "attribute", "of", "an", "anchor", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/html.py#L86-L108
train
57,009
inveniosoftware-attic/invenio-utils
invenio_utils/html.py
tidy_html
def tidy_html(html_buffer, cleaning_lib='utidylib'): """ Tidy up the input HTML using one of the installed cleaning libraries. @param html_buffer: the input HTML to clean up @type html_buffer: string @param cleaning_lib: chose the preferred library to clean the HTML. One of: ...
python
def tidy_html(html_buffer, cleaning_lib='utidylib'): """ Tidy up the input HTML using one of the installed cleaning libraries. @param html_buffer: the input HTML to clean up @type html_buffer: string @param cleaning_lib: chose the preferred library to clean the HTML. One of: ...
[ "def", "tidy_html", "(", "html_buffer", ",", "cleaning_lib", "=", "'utidylib'", ")", ":", "if", "CFG_TIDY_INSTALLED", "and", "cleaning_lib", "==", "'utidylib'", ":", "options", "=", "dict", "(", "output_xhtml", "=", "1", ",", "show_body_only", "=", "1", ",", ...
Tidy up the input HTML using one of the installed cleaning libraries. @param html_buffer: the input HTML to clean up @type html_buffer: string @param cleaning_lib: chose the preferred library to clean the HTML. One of: - utidylib - beautifulsoup @re...
[ "Tidy", "up", "the", "input", "HTML", "using", "one", "of", "the", "installed", "cleaning", "libraries", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/html.py#L413-L444
train
57,010
inveniosoftware-attic/invenio-utils
invenio_utils/html.py
remove_html_markup
def remove_html_markup(text, replacechar=' ', remove_escaped_chars_p=True): """ Remove HTML markup from text. @param text: Input text. @type text: string. @param replacechar: By which character should we replace HTML markup. Usually, a single space or an empty string are nice values. @t...
python
def remove_html_markup(text, replacechar=' ', remove_escaped_chars_p=True): """ Remove HTML markup from text. @param text: Input text. @type text: string. @param replacechar: By which character should we replace HTML markup. Usually, a single space or an empty string are nice values. @t...
[ "def", "remove_html_markup", "(", "text", ",", "replacechar", "=", "' '", ",", "remove_escaped_chars_p", "=", "True", ")", ":", "if", "not", "remove_escaped_chars_p", ":", "return", "RE_HTML_WITHOUT_ESCAPED_CHARS", ".", "sub", "(", "replacechar", ",", "text", ")",...
Remove HTML markup from text. @param text: Input text. @type text: string. @param replacechar: By which character should we replace HTML markup. Usually, a single space or an empty string are nice values. @type replacechar: string @param remove_escaped_chars_p: If True, also remove escaped ...
[ "Remove", "HTML", "markup", "from", "text", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/html.py#L661-L678
train
57,011
inveniosoftware-attic/invenio-utils
invenio_utils/html.py
create_html_select
def create_html_select( options, name=None, selected=None, disabled=None, multiple=False, attrs=None, **other_attrs): """ Create an HTML select box. >>> print create_html_select(["foo", "bar"], selected="bar", name="baz") <select name="baz...
python
def create_html_select( options, name=None, selected=None, disabled=None, multiple=False, attrs=None, **other_attrs): """ Create an HTML select box. >>> print create_html_select(["foo", "bar"], selected="bar", name="baz") <select name="baz...
[ "def", "create_html_select", "(", "options", ",", "name", "=", "None", ",", "selected", "=", "None", ",", "disabled", "=", "None", ",", "multiple", "=", "False", ",", "attrs", "=", "None", ",", "*", "*", "other_attrs", ")", ":", "body", "=", "[", "]"...
Create an HTML select box. >>> print create_html_select(["foo", "bar"], selected="bar", name="baz") <select name="baz"> <option selected="selected" value="bar"> bar </option> <option value="foo"> foo </option> </select> >>>...
[ "Create", "an", "HTML", "select", "box", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/html.py#L910-L1018
train
57,012
inveniosoftware-attic/invenio-utils
invenio_utils/html.py
HTMLWasher.wash
def wash( self, html_buffer, render_unallowed_tags=False, allowed_tag_whitelist=CFG_HTML_BUFFER_ALLOWED_TAG_WHITELIST, automatic_link_transformation=False, allowed_attribute_whitelist=CFG_HTML_BUFFER_ALLOWED_ATTRIBUTE_WHITELIST): """ ...
python
def wash( self, html_buffer, render_unallowed_tags=False, allowed_tag_whitelist=CFG_HTML_BUFFER_ALLOWED_TAG_WHITELIST, automatic_link_transformation=False, allowed_attribute_whitelist=CFG_HTML_BUFFER_ALLOWED_ATTRIBUTE_WHITELIST): """ ...
[ "def", "wash", "(", "self", ",", "html_buffer", ",", "render_unallowed_tags", "=", "False", ",", "allowed_tag_whitelist", "=", "CFG_HTML_BUFFER_ALLOWED_TAG_WHITELIST", ",", "automatic_link_transformation", "=", "False", ",", "allowed_attribute_whitelist", "=", "CFG_HTML_BUF...
Wash HTML buffer, escaping XSS attacks. @param html_buffer: text to escape @param render_unallowed_tags: if True, print unallowed tags escaping < and >. Else, only print content of unallowed tags. @param allowed_tag_whitelist: list of allowed tags @param allowed_attribute_wh...
[ "Wash", "HTML", "buffer", "escaping", "XSS", "attacks", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/html.py#L301-L329
train
57,013
Cecca/lydoc
lydoc/renderer.py
template_from_filename
def template_from_filename(filename): """Returns the appropriate template name based on the given file name.""" ext = filename.split(os.path.extsep)[-1] if not ext in TEMPLATES_MAP: raise ValueError("No template for file extension {}".format(ext)) return TEMPLATES_MAP[ext]
python
def template_from_filename(filename): """Returns the appropriate template name based on the given file name.""" ext = filename.split(os.path.extsep)[-1] if not ext in TEMPLATES_MAP: raise ValueError("No template for file extension {}".format(ext)) return TEMPLATES_MAP[ext]
[ "def", "template_from_filename", "(", "filename", ")", ":", "ext", "=", "filename", ".", "split", "(", "os", ".", "path", ".", "extsep", ")", "[", "-", "1", "]", "if", "not", "ext", "in", "TEMPLATES_MAP", ":", "raise", "ValueError", "(", "\"No template f...
Returns the appropriate template name based on the given file name.
[ "Returns", "the", "appropriate", "template", "name", "based", "on", "the", "given", "file", "name", "." ]
cd01dd5ed902b2574fb412c55bdc684276a88505
https://github.com/Cecca/lydoc/blob/cd01dd5ed902b2574fb412c55bdc684276a88505/lydoc/renderer.py#L41-L46
train
57,014
trevisanj/a99
a99/datetimefunc.py
dt2ts
def dt2ts(dt): """Converts to float representing number of seconds since 1970-01-01 GMT.""" # Note: no assertion to really keep this fast assert isinstance(dt, (datetime.datetime, datetime.date)) ret = time.mktime(dt.timetuple()) if isinstance(dt, datetime.datetime): ret += 1e-6 * dt.m...
python
def dt2ts(dt): """Converts to float representing number of seconds since 1970-01-01 GMT.""" # Note: no assertion to really keep this fast assert isinstance(dt, (datetime.datetime, datetime.date)) ret = time.mktime(dt.timetuple()) if isinstance(dt, datetime.datetime): ret += 1e-6 * dt.m...
[ "def", "dt2ts", "(", "dt", ")", ":", "# Note: no assertion to really keep this fast\r", "assert", "isinstance", "(", "dt", ",", "(", "datetime", ".", "datetime", ",", "datetime", ".", "date", ")", ")", "ret", "=", "time", ".", "mktime", "(", "dt", ".", "ti...
Converts to float representing number of seconds since 1970-01-01 GMT.
[ "Converts", "to", "float", "representing", "number", "of", "seconds", "since", "1970", "-", "01", "-", "01", "GMT", "." ]
193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539
https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/datetimefunc.py#L24-L31
train
57,015
trevisanj/a99
a99/datetimefunc.py
dt2str
def dt2str(dt, flagSeconds=True): """Converts datetime object to str if not yet an str.""" if isinstance(dt, str): return dt return dt.strftime(_FMTS if flagSeconds else _FMT)
python
def dt2str(dt, flagSeconds=True): """Converts datetime object to str if not yet an str.""" if isinstance(dt, str): return dt return dt.strftime(_FMTS if flagSeconds else _FMT)
[ "def", "dt2str", "(", "dt", ",", "flagSeconds", "=", "True", ")", ":", "if", "isinstance", "(", "dt", ",", "str", ")", ":", "return", "dt", "return", "dt", ".", "strftime", "(", "_FMTS", "if", "flagSeconds", "else", "_FMT", ")" ]
Converts datetime object to str if not yet an str.
[ "Converts", "datetime", "object", "to", "str", "if", "not", "yet", "an", "str", "." ]
193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539
https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/datetimefunc.py#L37-L41
train
57,016
trevisanj/a99
a99/datetimefunc.py
time2seconds
def time2seconds(t): """Returns seconds since 0h00.""" return t.hour * 3600 + t.minute * 60 + t.second + float(t.microsecond) / 1e6
python
def time2seconds(t): """Returns seconds since 0h00.""" return t.hour * 3600 + t.minute * 60 + t.second + float(t.microsecond) / 1e6
[ "def", "time2seconds", "(", "t", ")", ":", "return", "t", ".", "hour", "*", "3600", "+", "t", ".", "minute", "*", "60", "+", "t", ".", "second", "+", "float", "(", "t", ".", "microsecond", ")", "/", "1e6" ]
Returns seconds since 0h00.
[ "Returns", "seconds", "since", "0h00", "." ]
193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539
https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/datetimefunc.py#L54-L56
train
57,017
nuSTORM/gnomon
gnomon/processors/Fitter.py
VlenfPolynomialFitter.Fit
def Fit(self, zxq): """Perform a 2D fit on 2D points then return parameters :param zxq: A list where each element is (z, transverse, charge) """ z, trans, Q = zip(*zxq) assert len(trans) == len(z) ndf = len(z) - 3 z = np.array(z) trans = np.array(trans) ...
python
def Fit(self, zxq): """Perform a 2D fit on 2D points then return parameters :param zxq: A list where each element is (z, transverse, charge) """ z, trans, Q = zip(*zxq) assert len(trans) == len(z) ndf = len(z) - 3 z = np.array(z) trans = np.array(trans) ...
[ "def", "Fit", "(", "self", ",", "zxq", ")", ":", "z", ",", "trans", ",", "Q", "=", "zip", "(", "*", "zxq", ")", "assert", "len", "(", "trans", ")", "==", "len", "(", "z", ")", "ndf", "=", "len", "(", "z", ")", "-", "3", "z", "=", "np", ...
Perform a 2D fit on 2D points then return parameters :param zxq: A list where each element is (z, transverse, charge)
[ "Perform", "a", "2D", "fit", "on", "2D", "points", "then", "return", "parameters" ]
7616486ecd6e26b76f677c380e62db1c0ade558a
https://github.com/nuSTORM/gnomon/blob/7616486ecd6e26b76f677c380e62db1c0ade558a/gnomon/processors/Fitter.py#L317-L353
train
57,018
nuSTORM/gnomon
gnomon/processors/Fitter.py
VlenfPolynomialFitter._get_last_transverse_over_list
def _get_last_transverse_over_list(self, zxq): """ Get transverse coord at highest z :param zx: A list where each element is (z, transverse, charge) """ z_max = None x_of_interest = None for z, x, q in zxq: if z == None or z > z_max: x_of_int...
python
def _get_last_transverse_over_list(self, zxq): """ Get transverse coord at highest z :param zx: A list where each element is (z, transverse, charge) """ z_max = None x_of_interest = None for z, x, q in zxq: if z == None or z > z_max: x_of_int...
[ "def", "_get_last_transverse_over_list", "(", "self", ",", "zxq", ")", ":", "z_max", "=", "None", "x_of_interest", "=", "None", "for", "z", ",", "x", ",", "q", "in", "zxq", ":", "if", "z", "==", "None", "or", "z", ">", "z_max", ":", "x_of_interest", ...
Get transverse coord at highest z :param zx: A list where each element is (z, transverse, charge)
[ "Get", "transverse", "coord", "at", "highest", "z" ]
7616486ecd6e26b76f677c380e62db1c0ade558a
https://github.com/nuSTORM/gnomon/blob/7616486ecd6e26b76f677c380e62db1c0ade558a/gnomon/processors/Fitter.py#L363-L375
train
57,019
hackedd/gw2api
gw2api/items.py
item_details
def item_details(item_id, lang="en"): """This resource returns a details about a single item. :param item_id: The item to query for. :param lang: The language to display the texts in. The response is an object with at least the following properties. Note that the availability of some properties de...
python
def item_details(item_id, lang="en"): """This resource returns a details about a single item. :param item_id: The item to query for. :param lang: The language to display the texts in. The response is an object with at least the following properties. Note that the availability of some properties de...
[ "def", "item_details", "(", "item_id", ",", "lang", "=", "\"en\"", ")", ":", "params", "=", "{", "\"item_id\"", ":", "item_id", ",", "\"lang\"", ":", "lang", "}", "cache_name", "=", "\"item_details.%(item_id)s.%(lang)s.json\"", "%", "params", "return", "get_cach...
This resource returns a details about a single item. :param item_id: The item to query for. :param lang: The language to display the texts in. The response is an object with at least the following properties. Note that the availability of some properties depends on the type of the item. item_id (...
[ "This", "resource", "returns", "a", "details", "about", "a", "single", "item", "." ]
5543a78e6e3ed0573b7e84c142c44004b4779eac
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/items.py#L24-L85
train
57,020
hackedd/gw2api
gw2api/items.py
recipe_details
def recipe_details(recipe_id, lang="en"): """This resource returns a details about a single recipe. :param recipe_id: The recipe to query for. :param lang: The language to display the texts in. The response is an object with the following properties: recipe_id (number): The recipe id. ...
python
def recipe_details(recipe_id, lang="en"): """This resource returns a details about a single recipe. :param recipe_id: The recipe to query for. :param lang: The language to display the texts in. The response is an object with the following properties: recipe_id (number): The recipe id. ...
[ "def", "recipe_details", "(", "recipe_id", ",", "lang", "=", "\"en\"", ")", ":", "params", "=", "{", "\"recipe_id\"", ":", "recipe_id", ",", "\"lang\"", ":", "lang", "}", "cache_name", "=", "\"recipe_details.%(recipe_id)s.%(lang)s.json\"", "%", "params", "return",...
This resource returns a details about a single recipe. :param recipe_id: The recipe to query for. :param lang: The language to display the texts in. The response is an object with the following properties: recipe_id (number): The recipe id. type (string): The type of the produced...
[ "This", "resource", "returns", "a", "details", "about", "a", "single", "recipe", "." ]
5543a78e6e3ed0573b7e84c142c44004b4779eac
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/items.py#L88-L139
train
57,021
martymcguire/Flask-IndieAuth
flask_indieauth.py
requires_indieauth
def requires_indieauth(f): """Wraps a Flask handler to require a valid IndieAuth access token. """ @wraps(f) def decorated(*args, **kwargs): access_token = get_access_token() resp = check_auth(access_token) if isinstance(resp, Response): return resp return f(*ar...
python
def requires_indieauth(f): """Wraps a Flask handler to require a valid IndieAuth access token. """ @wraps(f) def decorated(*args, **kwargs): access_token = get_access_token() resp = check_auth(access_token) if isinstance(resp, Response): return resp return f(*ar...
[ "def", "requires_indieauth", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "access_token", "=", "get_access_token", "(", ")", "resp", "=", "check_auth", "(", "access_token", ")...
Wraps a Flask handler to require a valid IndieAuth access token.
[ "Wraps", "a", "Flask", "handler", "to", "require", "a", "valid", "IndieAuth", "access", "token", "." ]
6b5a816dabaa243d1833ff23a9d21d91d35e7461
https://github.com/martymcguire/Flask-IndieAuth/blob/6b5a816dabaa243d1833ff23a9d21d91d35e7461/flask_indieauth.py#L58-L68
train
57,022
martymcguire/Flask-IndieAuth
flask_indieauth.py
check_auth
def check_auth(access_token): """This function contacts the configured IndieAuth Token Endpoint to see if the given token is a valid token and for whom. """ if not access_token: current_app.logger.error('No access token.') return deny('No access token found.') request = Request( cu...
python
def check_auth(access_token): """This function contacts the configured IndieAuth Token Endpoint to see if the given token is a valid token and for whom. """ if not access_token: current_app.logger.error('No access token.') return deny('No access token found.') request = Request( cu...
[ "def", "check_auth", "(", "access_token", ")", ":", "if", "not", "access_token", ":", "current_app", ".", "logger", ".", "error", "(", "'No access token.'", ")", "return", "deny", "(", "'No access token found.'", ")", "request", "=", "Request", "(", "current_app...
This function contacts the configured IndieAuth Token Endpoint to see if the given token is a valid token and for whom.
[ "This", "function", "contacts", "the", "configured", "IndieAuth", "Token", "Endpoint", "to", "see", "if", "the", "given", "token", "is", "a", "valid", "token", "and", "for", "whom", "." ]
6b5a816dabaa243d1833ff23a9d21d91d35e7461
https://github.com/martymcguire/Flask-IndieAuth/blob/6b5a816dabaa243d1833ff23a9d21d91d35e7461/flask_indieauth.py#L70-L110
train
57,023
Julian/Minion
examples/flaskr.py
connect_db
def connect_db(config): """Connects to the specific database.""" rv = sqlite3.connect(config["database"]["uri"]) rv.row_factory = sqlite3.Row return rv
python
def connect_db(config): """Connects to the specific database.""" rv = sqlite3.connect(config["database"]["uri"]) rv.row_factory = sqlite3.Row return rv
[ "def", "connect_db", "(", "config", ")", ":", "rv", "=", "sqlite3", ".", "connect", "(", "config", "[", "\"database\"", "]", "[", "\"uri\"", "]", ")", "rv", ".", "row_factory", "=", "sqlite3", ".", "Row", "return", "rv" ]
Connects to the specific database.
[ "Connects", "to", "the", "specific", "database", "." ]
518d06f9ffd38dcacc0de4d94e72d1f8452157a8
https://github.com/Julian/Minion/blob/518d06f9ffd38dcacc0de4d94e72d1f8452157a8/examples/flaskr.py#L92-L96
train
57,024
inveniosoftware-attic/invenio-utils
invenio_utils/vcs/git.py
harvest_repo
def harvest_repo(root_url, archive_path, tag=None, archive_format='tar.gz'): """ Archives a specific tag in a specific Git repository. :param root_url: The URL to the Git repo - Supported protocols: git, ssh, http[s]. :param archive_path: A temporary path to clone the repo to - Must end in .git...
python
def harvest_repo(root_url, archive_path, tag=None, archive_format='tar.gz'): """ Archives a specific tag in a specific Git repository. :param root_url: The URL to the Git repo - Supported protocols: git, ssh, http[s]. :param archive_path: A temporary path to clone the repo to - Must end in .git...
[ "def", "harvest_repo", "(", "root_url", ",", "archive_path", ",", "tag", "=", "None", ",", "archive_format", "=", "'tar.gz'", ")", ":", "if", "not", "git_exists", "(", ")", ":", "raise", "Exception", "(", "\"Git not found. It probably needs installing.\"", ")", ...
Archives a specific tag in a specific Git repository. :param root_url: The URL to the Git repo - Supported protocols: git, ssh, http[s]. :param archive_path: A temporary path to clone the repo to - Must end in .git :param tag: The path to which the .tar.gz will go to - Must end in the same as f...
[ "Archives", "a", "specific", "tag", "in", "a", "specific", "Git", "repository", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/vcs/git.py#L49-L85
train
57,025
hayalasalah/adhan.py
adhan/calculations.py
gregorian_to_julian
def gregorian_to_julian(day): """Convert a datetime.date object to its corresponding Julian day. :param day: The datetime.date to convert to a Julian day :returns: A Julian day, as an integer """ before_march = 1 if day.month < MARCH else 0 # # Number of months since March # month_...
python
def gregorian_to_julian(day): """Convert a datetime.date object to its corresponding Julian day. :param day: The datetime.date to convert to a Julian day :returns: A Julian day, as an integer """ before_march = 1 if day.month < MARCH else 0 # # Number of months since March # month_...
[ "def", "gregorian_to_julian", "(", "day", ")", ":", "before_march", "=", "1", "if", "day", ".", "month", "<", "MARCH", "else", "0", "#", "# Number of months since March", "#", "month_index", "=", "day", ".", "month", "+", "MONTHS_PER_YEAR", "*", "before_march"...
Convert a datetime.date object to its corresponding Julian day. :param day: The datetime.date to convert to a Julian day :returns: A Julian day, as an integer
[ "Convert", "a", "datetime", ".", "date", "object", "to", "its", "corresponding", "Julian", "day", "." ]
a7c080ba48f70be9801f048451d2c91a7d579602
https://github.com/hayalasalah/adhan.py/blob/a7c080ba48f70be9801f048451d2c91a7d579602/adhan/calculations.py#L46-L78
train
57,026
hayalasalah/adhan.py
adhan/calculations.py
sun_declination
def sun_declination(day): """Compute the declination angle of the sun for the given date. Uses the Spencer Formula (found at http://www.illustratingshadows.com/www-formulae-collection.pdf) :param day: The datetime.date to compute the declination angle for :returns: The angle, in degrees, of the an...
python
def sun_declination(day): """Compute the declination angle of the sun for the given date. Uses the Spencer Formula (found at http://www.illustratingshadows.com/www-formulae-collection.pdf) :param day: The datetime.date to compute the declination angle for :returns: The angle, in degrees, of the an...
[ "def", "sun_declination", "(", "day", ")", ":", "day_of_year", "=", "day", ".", "toordinal", "(", ")", "-", "date", "(", "day", ".", "year", ",", "1", ",", "1", ")", ".", "toordinal", "(", ")", "day_angle", "=", "2", "*", "pi", "*", "day_of_year", ...
Compute the declination angle of the sun for the given date. Uses the Spencer Formula (found at http://www.illustratingshadows.com/www-formulae-collection.pdf) :param day: The datetime.date to compute the declination angle for :returns: The angle, in degrees, of the angle of declination
[ "Compute", "the", "declination", "angle", "of", "the", "sun", "for", "the", "given", "date", "." ]
a7c080ba48f70be9801f048451d2c91a7d579602
https://github.com/hayalasalah/adhan.py/blob/a7c080ba48f70be9801f048451d2c91a7d579602/adhan/calculations.py#L81-L102
train
57,027
hayalasalah/adhan.py
adhan/calculations.py
equation_of_time
def equation_of_time(day): """Compute the equation of time for the given date. Uses formula described at https://en.wikipedia.org/wiki/Equation_of_time#Alternative_calculation :param day: The datetime.date to compute the equation of time for :returns: The angle, in radians, of the Equation of Time...
python
def equation_of_time(day): """Compute the equation of time for the given date. Uses formula described at https://en.wikipedia.org/wiki/Equation_of_time#Alternative_calculation :param day: The datetime.date to compute the equation of time for :returns: The angle, in radians, of the Equation of Time...
[ "def", "equation_of_time", "(", "day", ")", ":", "day_of_year", "=", "day", ".", "toordinal", "(", ")", "-", "date", "(", "day", ".", "year", ",", "1", ",", "1", ")", ".", "toordinal", "(", ")", "# pylint: disable=invalid-name", "#", "# Distance Earth move...
Compute the equation of time for the given date. Uses formula described at https://en.wikipedia.org/wiki/Equation_of_time#Alternative_calculation :param day: The datetime.date to compute the equation of time for :returns: The angle, in radians, of the Equation of Time
[ "Compute", "the", "equation", "of", "time", "for", "the", "given", "date", "." ]
a7c080ba48f70be9801f048451d2c91a7d579602
https://github.com/hayalasalah/adhan.py/blob/a7c080ba48f70be9801f048451d2c91a7d579602/adhan/calculations.py#L105-L145
train
57,028
hayalasalah/adhan.py
adhan/calculations.py
compute_zuhr_utc
def compute_zuhr_utc(day, longitude): """Compute the UTC floating point time for Zuhr given date and longitude. This function is necessary since all other prayer times are based on the time for Zuhr :param day: The day to compute Zuhr adhan for :param longitude: Longitude of the place of interest ...
python
def compute_zuhr_utc(day, longitude): """Compute the UTC floating point time for Zuhr given date and longitude. This function is necessary since all other prayer times are based on the time for Zuhr :param day: The day to compute Zuhr adhan for :param longitude: Longitude of the place of interest ...
[ "def", "compute_zuhr_utc", "(", "day", ",", "longitude", ")", ":", "eot", "=", "equation_of_time", "(", "day", ")", "#", "# Formula as described by PrayTime.org doesn't work in Eastern hemisphere", "# because it expects to be subtracting a negative longitude. +abs() should", "# do ...
Compute the UTC floating point time for Zuhr given date and longitude. This function is necessary since all other prayer times are based on the time for Zuhr :param day: The day to compute Zuhr adhan for :param longitude: Longitude of the place of interest :returns: The UTC time for Zuhr, as a flo...
[ "Compute", "the", "UTC", "floating", "point", "time", "for", "Zuhr", "given", "date", "and", "longitude", "." ]
a7c080ba48f70be9801f048451d2c91a7d579602
https://github.com/hayalasalah/adhan.py/blob/a7c080ba48f70be9801f048451d2c91a7d579602/adhan/calculations.py#L148-L167
train
57,029
hayalasalah/adhan.py
adhan/calculations.py
compute_time_at_sun_angle
def compute_time_at_sun_angle(day, latitude, angle): """Compute the floating point time difference between mid-day and an angle. All the prayers are defined as certain angles from mid-day (Zuhr). This formula is taken from praytimes.org/calculation :param day: The day to which to compute for :para...
python
def compute_time_at_sun_angle(day, latitude, angle): """Compute the floating point time difference between mid-day and an angle. All the prayers are defined as certain angles from mid-day (Zuhr). This formula is taken from praytimes.org/calculation :param day: The day to which to compute for :para...
[ "def", "compute_time_at_sun_angle", "(", "day", ",", "latitude", ",", "angle", ")", ":", "positive_angle_rad", "=", "radians", "(", "abs", "(", "angle", ")", ")", "angle_sign", "=", "abs", "(", "angle", ")", "/", "angle", "latitude_rad", "=", "radians", "(...
Compute the floating point time difference between mid-day and an angle. All the prayers are defined as certain angles from mid-day (Zuhr). This formula is taken from praytimes.org/calculation :param day: The day to which to compute for :param longitude: Longitude of the place of interest :angle: ...
[ "Compute", "the", "floating", "point", "time", "difference", "between", "mid", "-", "day", "and", "an", "angle", "." ]
a7c080ba48f70be9801f048451d2c91a7d579602
https://github.com/hayalasalah/adhan.py/blob/a7c080ba48f70be9801f048451d2c91a7d579602/adhan/calculations.py#L170-L195
train
57,030
hayalasalah/adhan.py
adhan/calculations.py
time_at_shadow_length
def time_at_shadow_length(day, latitude, multiplier): """Compute the time at which an object's shadow is a multiple of its length. Specifically, determine the time the length of the shadow is a multiple of the object's length + the length of the object's shadow at noon This is used in the calculation ...
python
def time_at_shadow_length(day, latitude, multiplier): """Compute the time at which an object's shadow is a multiple of its length. Specifically, determine the time the length of the shadow is a multiple of the object's length + the length of the object's shadow at noon This is used in the calculation ...
[ "def", "time_at_shadow_length", "(", "day", ",", "latitude", ",", "multiplier", ")", ":", "latitude_rad", "=", "radians", "(", "latitude", ")", "declination", "=", "radians", "(", "sun_declination", "(", "day", ")", ")", "angle", "=", "arccot", "(", "multipl...
Compute the time at which an object's shadow is a multiple of its length. Specifically, determine the time the length of the shadow is a multiple of the object's length + the length of the object's shadow at noon This is used in the calculation for Asr time. Hanafi uses a multiplier of 2, and everyone...
[ "Compute", "the", "time", "at", "which", "an", "object", "s", "shadow", "is", "a", "multiple", "of", "its", "length", "." ]
a7c080ba48f70be9801f048451d2c91a7d579602
https://github.com/hayalasalah/adhan.py/blob/a7c080ba48f70be9801f048451d2c91a7d579602/adhan/calculations.py#L198-L226
train
57,031
koenedaele/pyramid_skosprovider
pyramid_skosprovider/utils.py
parse_range_header
def parse_range_header(range): ''' Parse a range header as used by the dojo Json Rest store. :param str range: The content of the range header to be parsed. eg. `items=0-9` :returns: A dict with keys start, finish and number or `False` if the range is invalid. ''' match = re.mat...
python
def parse_range_header(range): ''' Parse a range header as used by the dojo Json Rest store. :param str range: The content of the range header to be parsed. eg. `items=0-9` :returns: A dict with keys start, finish and number or `False` if the range is invalid. ''' match = re.mat...
[ "def", "parse_range_header", "(", "range", ")", ":", "match", "=", "re", ".", "match", "(", "'^items=([0-9]+)-([0-9]+)$'", ",", "range", ")", "if", "match", ":", "start", "=", "int", "(", "match", ".", "group", "(", "1", ")", ")", "finish", "=", "int",...
Parse a range header as used by the dojo Json Rest store. :param str range: The content of the range header to be parsed. eg. `items=0-9` :returns: A dict with keys start, finish and number or `False` if the range is invalid.
[ "Parse", "a", "range", "header", "as", "used", "by", "the", "dojo", "Json", "Rest", "store", "." ]
3affdb53cac7ad01bf3656ecd4c4d7ad9b4948b6
https://github.com/koenedaele/pyramid_skosprovider/blob/3affdb53cac7ad01bf3656ecd4c4d7ad9b4948b6/pyramid_skosprovider/utils.py#L65-L86
train
57,032
numberoverzero/accordian
accordian.py
Dispatch.on
def on(self, event): """ Returns a wrapper for the given event. Usage: @dispatch.on("my_event") def handle_my_event(foo, bar, baz): ... """ handler = self._handlers.get(event, None) if not handler: raise ValueError("U...
python
def on(self, event): """ Returns a wrapper for the given event. Usage: @dispatch.on("my_event") def handle_my_event(foo, bar, baz): ... """ handler = self._handlers.get(event, None) if not handler: raise ValueError("U...
[ "def", "on", "(", "self", ",", "event", ")", ":", "handler", "=", "self", ".", "_handlers", ".", "get", "(", "event", ",", "None", ")", "if", "not", "handler", ":", "raise", "ValueError", "(", "\"Unknown event '{}'\"", ".", "format", "(", "event", ")",...
Returns a wrapper for the given event. Usage: @dispatch.on("my_event") def handle_my_event(foo, bar, baz): ...
[ "Returns", "a", "wrapper", "for", "the", "given", "event", "." ]
f1fe44dc9c646006418017bbf70f597b180c8b97
https://github.com/numberoverzero/accordian/blob/f1fe44dc9c646006418017bbf70f597b180c8b97/accordian.py#L85-L99
train
57,033
numberoverzero/accordian
accordian.py
Dispatch.register
def register(self, event, keys): """ Register a new event with available keys. Raises ValueError when the event has already been registered. Usage: dispatch.register("my_event", ["foo", "bar", "baz"]) """ if self.running: raise RuntimeError("Can...
python
def register(self, event, keys): """ Register a new event with available keys. Raises ValueError when the event has already been registered. Usage: dispatch.register("my_event", ["foo", "bar", "baz"]) """ if self.running: raise RuntimeError("Can...
[ "def", "register", "(", "self", ",", "event", ",", "keys", ")", ":", "if", "self", ".", "running", ":", "raise", "RuntimeError", "(", "\"Can't register while running\"", ")", "handler", "=", "self", ".", "_handlers", ".", "get", "(", "event", ",", "None", ...
Register a new event with available keys. Raises ValueError when the event has already been registered. Usage: dispatch.register("my_event", ["foo", "bar", "baz"])
[ "Register", "a", "new", "event", "with", "available", "keys", ".", "Raises", "ValueError", "when", "the", "event", "has", "already", "been", "registered", "." ]
f1fe44dc9c646006418017bbf70f597b180c8b97
https://github.com/numberoverzero/accordian/blob/f1fe44dc9c646006418017bbf70f597b180c8b97/accordian.py#L101-L116
train
57,034
numberoverzero/accordian
accordian.py
Dispatch.unregister
def unregister(self, event): """ Remove all registered handlers for an event. Silent return when event was not registered. Usage: dispatch.unregister("my_event") dispatch.unregister("my_event") # no-op """ if self.running: raise Run...
python
def unregister(self, event): """ Remove all registered handlers for an event. Silent return when event was not registered. Usage: dispatch.unregister("my_event") dispatch.unregister("my_event") # no-op """ if self.running: raise Run...
[ "def", "unregister", "(", "self", ",", "event", ")", ":", "if", "self", ".", "running", ":", "raise", "RuntimeError", "(", "\"Can't unregister while running\"", ")", "self", ".", "_handlers", ".", "pop", "(", "event", ",", "None", ")" ]
Remove all registered handlers for an event. Silent return when event was not registered. Usage: dispatch.unregister("my_event") dispatch.unregister("my_event") # no-op
[ "Remove", "all", "registered", "handlers", "for", "an", "event", ".", "Silent", "return", "when", "event", "was", "not", "registered", "." ]
f1fe44dc9c646006418017bbf70f597b180c8b97
https://github.com/numberoverzero/accordian/blob/f1fe44dc9c646006418017bbf70f597b180c8b97/accordian.py#L118-L131
train
57,035
numberoverzero/accordian
accordian.py
Dispatch.trigger
async def trigger(self, event, kwargs): """ Enqueue an event for processing """ await self._queue.put((event, kwargs)) self._resume_processing.set()
python
async def trigger(self, event, kwargs): """ Enqueue an event for processing """ await self._queue.put((event, kwargs)) self._resume_processing.set()
[ "async", "def", "trigger", "(", "self", ",", "event", ",", "kwargs", ")", ":", "await", "self", ".", "_queue", ".", "put", "(", "(", "event", ",", "kwargs", ")", ")", "self", ".", "_resume_processing", ".", "set", "(", ")" ]
Enqueue an event for processing
[ "Enqueue", "an", "event", "for", "processing" ]
f1fe44dc9c646006418017bbf70f597b180c8b97
https://github.com/numberoverzero/accordian/blob/f1fe44dc9c646006418017bbf70f597b180c8b97/accordian.py#L133-L136
train
57,036
numberoverzero/accordian
accordian.py
Dispatch._task
async def _task(self): """ Main queue processor """ if self._handlers.values(): start_tasks = [h.start() for h in self._handlers.values()] await asyncio.wait(start_tasks, loop=self.loop) while self.running: if self.events: event, kwargs = awa...
python
async def _task(self): """ Main queue processor """ if self._handlers.values(): start_tasks = [h.start() for h in self._handlers.values()] await asyncio.wait(start_tasks, loop=self.loop) while self.running: if self.events: event, kwargs = awa...
[ "async", "def", "_task", "(", "self", ")", ":", "if", "self", ".", "_handlers", ".", "values", "(", ")", ":", "start_tasks", "=", "[", "h", ".", "start", "(", ")", "for", "h", "in", "self", ".", "_handlers", ".", "values", "(", ")", "]", "await",...
Main queue processor
[ "Main", "queue", "processor" ]
f1fe44dc9c646006418017bbf70f597b180c8b97
https://github.com/numberoverzero/accordian/blob/f1fe44dc9c646006418017bbf70f597b180c8b97/accordian.py#L148-L172
train
57,037
Titan-C/slaveparticles
examples/spins/plot_deg_2orb_fill.py
restriction
def restriction(lam, mu, orbitals, U, beta): """Equation that determines the restriction on lagrange multipier""" return 2*orbitals*fermi_dist(-(mu + lam), beta) - expected_filling(-1*lam, orbitals, U, beta)
python
def restriction(lam, mu, orbitals, U, beta): """Equation that determines the restriction on lagrange multipier""" return 2*orbitals*fermi_dist(-(mu + lam), beta) - expected_filling(-1*lam, orbitals, U, beta)
[ "def", "restriction", "(", "lam", ",", "mu", ",", "orbitals", ",", "U", ",", "beta", ")", ":", "return", "2", "*", "orbitals", "*", "fermi_dist", "(", "-", "(", "mu", "+", "lam", ")", ",", "beta", ")", "-", "expected_filling", "(", "-", "1", "*",...
Equation that determines the restriction on lagrange multipier
[ "Equation", "that", "determines", "the", "restriction", "on", "lagrange", "multipier" ]
e4c2f5afb1a7b195517ef2f1b5cc758965036aab
https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/examples/spins/plot_deg_2orb_fill.py#L29-L31
train
57,038
Titan-C/slaveparticles
examples/spins/plot_deg_2orb_fill.py
pressision_try
def pressision_try(orbitals, U, beta, step): """perform a better initial guess of lambda no improvement""" mu, lam = main(orbitals, U, beta, step) mu2, lam2 = linspace(0, U*orbitals, step), zeros(step) for i in range(99): lam2[i+1] = fsolve(restriction, lam2[i], (mu2[i+1], orbitals, U, be...
python
def pressision_try(orbitals, U, beta, step): """perform a better initial guess of lambda no improvement""" mu, lam = main(orbitals, U, beta, step) mu2, lam2 = linspace(0, U*orbitals, step), zeros(step) for i in range(99): lam2[i+1] = fsolve(restriction, lam2[i], (mu2[i+1], orbitals, U, be...
[ "def", "pressision_try", "(", "orbitals", ",", "U", ",", "beta", ",", "step", ")", ":", "mu", ",", "lam", "=", "main", "(", "orbitals", ",", "U", ",", "beta", ",", "step", ")", "mu2", ",", "lam2", "=", "linspace", "(", "0", ",", "U", "*", "orbi...
perform a better initial guess of lambda no improvement
[ "perform", "a", "better", "initial", "guess", "of", "lambda", "no", "improvement" ]
e4c2f5afb1a7b195517ef2f1b5cc758965036aab
https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/examples/spins/plot_deg_2orb_fill.py#L46-L54
train
57,039
Titan-C/slaveparticles
slaveparticles/quantum/spinmatrices.py
spin_z
def spin_z(particles, index): """Generates the spin_z projection operator for a system of N=particles and for the selected spin index name. where index=0..N-1""" mat = np.zeros((2**particles, 2**particles)) for i in range(2**particles): ispin = btest(i, index) if ispin == 1: ...
python
def spin_z(particles, index): """Generates the spin_z projection operator for a system of N=particles and for the selected spin index name. where index=0..N-1""" mat = np.zeros((2**particles, 2**particles)) for i in range(2**particles): ispin = btest(i, index) if ispin == 1: ...
[ "def", "spin_z", "(", "particles", ",", "index", ")", ":", "mat", "=", "np", ".", "zeros", "(", "(", "2", "**", "particles", ",", "2", "**", "particles", ")", ")", "for", "i", "in", "range", "(", "2", "**", "particles", ")", ":", "ispin", "=", ...
Generates the spin_z projection operator for a system of N=particles and for the selected spin index name. where index=0..N-1
[ "Generates", "the", "spin_z", "projection", "operator", "for", "a", "system", "of", "N", "=", "particles", "and", "for", "the", "selected", "spin", "index", "name", ".", "where", "index", "=", "0", "..", "N", "-", "1" ]
e4c2f5afb1a7b195517ef2f1b5cc758965036aab
https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/quantum/spinmatrices.py#L14-L25
train
57,040
Titan-C/slaveparticles
slaveparticles/quantum/spinmatrices.py
spin_gen
def spin_gen(particles, index, gauge=1): """Generates the generic spin operator in z basis for a system of N=particles and for the selected spin index name. where index=0..N-1 The gauge term sets the behavoir for a system away from half-filling""" mat = np.zeros((2**particles, 2**particles)) ...
python
def spin_gen(particles, index, gauge=1): """Generates the generic spin operator in z basis for a system of N=particles and for the selected spin index name. where index=0..N-1 The gauge term sets the behavoir for a system away from half-filling""" mat = np.zeros((2**particles, 2**particles)) ...
[ "def", "spin_gen", "(", "particles", ",", "index", ",", "gauge", "=", "1", ")", ":", "mat", "=", "np", ".", "zeros", "(", "(", "2", "**", "particles", ",", "2", "**", "particles", ")", ")", "flipper", "=", "2", "**", "index", "for", "i", "in", ...
Generates the generic spin operator in z basis for a system of N=particles and for the selected spin index name. where index=0..N-1 The gauge term sets the behavoir for a system away from half-filling
[ "Generates", "the", "generic", "spin", "operator", "in", "z", "basis", "for", "a", "system", "of", "N", "=", "particles", "and", "for", "the", "selected", "spin", "index", "name", ".", "where", "index", "=", "0", "..", "N", "-", "1", "The", "gauge", ...
e4c2f5afb1a7b195517ef2f1b5cc758965036aab
https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/quantum/spinmatrices.py#L27-L40
train
57,041
chrlie/shorten
shorten/redis_store.py
RedisStore.revoke
def revoke(self, token, pipe=None): """\ Revokes the key associated with the given revokation token. If the token does not exist, a :class:`KeyError <KeyError>` is thrown. Otherwise `None` is returned. If `pipe` is given, then a :class:`RevokeError <shorten.RevokeError>` will not...
python
def revoke(self, token, pipe=None): """\ Revokes the key associated with the given revokation token. If the token does not exist, a :class:`KeyError <KeyError>` is thrown. Otherwise `None` is returned. If `pipe` is given, then a :class:`RevokeError <shorten.RevokeError>` will not...
[ "def", "revoke", "(", "self", ",", "token", ",", "pipe", "=", "None", ")", ":", "p", "=", "self", ".", "redis", ".", "pipeline", "(", ")", "if", "pipe", "is", "None", "else", "pipe", "formatted_token", "=", "self", ".", "format_token", "(", "token", ...
\ Revokes the key associated with the given revokation token. If the token does not exist, a :class:`KeyError <KeyError>` is thrown. Otherwise `None` is returned. If `pipe` is given, then a :class:`RevokeError <shorten.RevokeError>` will not be thrown if the key does not exist. The n-t...
[ "\\", "Revokes", "the", "key", "associated", "with", "the", "given", "revokation", "token", "." ]
fb762a199979aefaa28c88fa035e88ea8ce4d639
https://github.com/chrlie/shorten/blob/fb762a199979aefaa28c88fa035e88ea8ce4d639/shorten/redis_store.py#L163-L213
train
57,042
klen/muffin-oauth
example/app.py
oauth
async def oauth(request): """Oauth example.""" provider = request.match_info.get('provider') client, _ = await app.ps.oauth.login(provider, request) user, data = await client.user_info() response = ( "<a href='/'>back</a><br/><br/>" "<ul>" "<li>ID: {u.id}</li>" "<li>U...
python
async def oauth(request): """Oauth example.""" provider = request.match_info.get('provider') client, _ = await app.ps.oauth.login(provider, request) user, data = await client.user_info() response = ( "<a href='/'>back</a><br/><br/>" "<ul>" "<li>ID: {u.id}</li>" "<li>U...
[ "async", "def", "oauth", "(", "request", ")", ":", "provider", "=", "request", ".", "match_info", ".", "get", "(", "'provider'", ")", "client", ",", "_", "=", "await", "app", ".", "ps", ".", "oauth", ".", "login", "(", "provider", ",", "request", ")"...
Oauth example.
[ "Oauth", "example", "." ]
2d169840e2d08b9ba4a2f0915f99344c5f2c4aa6
https://github.com/klen/muffin-oauth/blob/2d169840e2d08b9ba4a2f0915f99344c5f2c4aa6/example/app.py#L57-L75
train
57,043
nuSTORM/gnomon
gnomon/EventAction.py
EventAction.BeginOfEventAction
def BeginOfEventAction(self, event): """Save event number""" self.log.info("Simulating event %s", event.GetEventID()) self.sd.setEventNumber(event.GetEventID())
python
def BeginOfEventAction(self, event): """Save event number""" self.log.info("Simulating event %s", event.GetEventID()) self.sd.setEventNumber(event.GetEventID())
[ "def", "BeginOfEventAction", "(", "self", ",", "event", ")", ":", "self", ".", "log", ".", "info", "(", "\"Simulating event %s\"", ",", "event", ".", "GetEventID", "(", ")", ")", "self", ".", "sd", ".", "setEventNumber", "(", "event", ".", "GetEventID", ...
Save event number
[ "Save", "event", "number" ]
7616486ecd6e26b76f677c380e62db1c0ade558a
https://github.com/nuSTORM/gnomon/blob/7616486ecd6e26b76f677c380e62db1c0ade558a/gnomon/EventAction.py#L32-L35
train
57,044
nuSTORM/gnomon
gnomon/EventAction.py
EventAction.EndOfEventAction
def EndOfEventAction(self, event): """At the end of an event, grab sensitive detector hits then run processor loop""" self.log.debug('Processesing simulated event %d', event.GetEventID()) docs = self.sd.getDocs() self.sd.clearDocs() for processor in self.processors: ...
python
def EndOfEventAction(self, event): """At the end of an event, grab sensitive detector hits then run processor loop""" self.log.debug('Processesing simulated event %d', event.GetEventID()) docs = self.sd.getDocs() self.sd.clearDocs() for processor in self.processors: ...
[ "def", "EndOfEventAction", "(", "self", ",", "event", ")", ":", "self", ".", "log", ".", "debug", "(", "'Processesing simulated event %d'", ",", "event", ".", "GetEventID", "(", ")", ")", "docs", "=", "self", ".", "sd", ".", "getDocs", "(", ")", "self", ...
At the end of an event, grab sensitive detector hits then run processor loop
[ "At", "the", "end", "of", "an", "event", "grab", "sensitive", "detector", "hits", "then", "run", "processor", "loop" ]
7616486ecd6e26b76f677c380e62db1c0ade558a
https://github.com/nuSTORM/gnomon/blob/7616486ecd6e26b76f677c380e62db1c0ade558a/gnomon/EventAction.py#L43-L54
train
57,045
blockadeio/analyst_toolbench
blockade/cli/aws_serverless.py
generate_handler
def generate_handler(): """Create the Blockade user and give them permissions.""" logger.debug("[#] Setting up user, group and permissions") client = boto3.client("iam", region_name=PRIMARY_REGION) # Create the user try: response = client.create_user( UserName=BLOCKADE_USER ...
python
def generate_handler(): """Create the Blockade user and give them permissions.""" logger.debug("[#] Setting up user, group and permissions") client = boto3.client("iam", region_name=PRIMARY_REGION) # Create the user try: response = client.create_user( UserName=BLOCKADE_USER ...
[ "def", "generate_handler", "(", ")", ":", "logger", ".", "debug", "(", "\"[#] Setting up user, group and permissions\"", ")", "client", "=", "boto3", ".", "client", "(", "\"iam\"", ",", "region_name", "=", "PRIMARY_REGION", ")", "# Create the user", "try", ":", "r...
Create the Blockade user and give them permissions.
[ "Create", "the", "Blockade", "user", "and", "give", "them", "permissions", "." ]
159b6f8cf8a91c5ff050f1579636ea90ab269863
https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/cli/aws_serverless.py#L389-L461
train
57,046
blockadeio/analyst_toolbench
blockade/cli/aws_serverless.py
remove_handler
def remove_handler(): """Remove the user, group and policies for Blockade.""" logger.debug("[#] Removing user, group and permissions for Blockade") client = boto3.client("iam", region_name=PRIMARY_REGION) iam = boto3.resource('iam') account_id = iam.CurrentUser().arn.split(':')[4] try: ...
python
def remove_handler(): """Remove the user, group and policies for Blockade.""" logger.debug("[#] Removing user, group and permissions for Blockade") client = boto3.client("iam", region_name=PRIMARY_REGION) iam = boto3.resource('iam') account_id = iam.CurrentUser().arn.split(':')[4] try: ...
[ "def", "remove_handler", "(", ")", ":", "logger", ".", "debug", "(", "\"[#] Removing user, group and permissions for Blockade\"", ")", "client", "=", "boto3", ".", "client", "(", "\"iam\"", ",", "region_name", "=", "PRIMARY_REGION", ")", "iam", "=", "boto3", ".", ...
Remove the user, group and policies for Blockade.
[ "Remove", "the", "user", "group", "and", "policies", "for", "Blockade", "." ]
159b6f8cf8a91c5ff050f1579636ea90ab269863
https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/cli/aws_serverless.py#L464-L527
train
57,047
blockadeio/analyst_toolbench
blockade/cli/aws_serverless.py
generate_s3_bucket
def generate_s3_bucket(): """Create the blockade bucket if not already there.""" logger.debug("[#] Setting up S3 bucket") client = boto3.client("s3", region_name=PRIMARY_REGION) buckets = client.list_buckets() matches = [x for x in buckets.get('Buckets', list()) if x['Name'].startswit...
python
def generate_s3_bucket(): """Create the blockade bucket if not already there.""" logger.debug("[#] Setting up S3 bucket") client = boto3.client("s3", region_name=PRIMARY_REGION) buckets = client.list_buckets() matches = [x for x in buckets.get('Buckets', list()) if x['Name'].startswit...
[ "def", "generate_s3_bucket", "(", ")", ":", "logger", ".", "debug", "(", "\"[#] Setting up S3 bucket\"", ")", "client", "=", "boto3", ".", "client", "(", "\"s3\"", ",", "region_name", "=", "PRIMARY_REGION", ")", "buckets", "=", "client", ".", "list_buckets", "...
Create the blockade bucket if not already there.
[ "Create", "the", "blockade", "bucket", "if", "not", "already", "there", "." ]
159b6f8cf8a91c5ff050f1579636ea90ab269863
https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/cli/aws_serverless.py#L530-L549
train
57,048
blockadeio/analyst_toolbench
blockade/cli/aws_serverless.py
remove_s3_bucket
def remove_s3_bucket(): """Remove the Blockade bucket.""" logger.debug("[#] Removing S3 bucket") client = boto3.client("s3", region_name=PRIMARY_REGION) buckets = client.list_buckets() matches = [x for x in buckets.get('Buckets', list()) if x['Name'].startswith(S3_BUCKET_NAME)] if...
python
def remove_s3_bucket(): """Remove the Blockade bucket.""" logger.debug("[#] Removing S3 bucket") client = boto3.client("s3", region_name=PRIMARY_REGION) buckets = client.list_buckets() matches = [x for x in buckets.get('Buckets', list()) if x['Name'].startswith(S3_BUCKET_NAME)] if...
[ "def", "remove_s3_bucket", "(", ")", ":", "logger", ".", "debug", "(", "\"[#] Removing S3 bucket\"", ")", "client", "=", "boto3", ".", "client", "(", "\"s3\"", ",", "region_name", "=", "PRIMARY_REGION", ")", "buckets", "=", "client", ".", "list_buckets", "(", ...
Remove the Blockade bucket.
[ "Remove", "the", "Blockade", "bucket", "." ]
159b6f8cf8a91c5ff050f1579636ea90ab269863
https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/cli/aws_serverless.py#L552-L589
train
57,049
blockadeio/analyst_toolbench
blockade/cli/aws_serverless.py
generate_dynamodb_tables
def generate_dynamodb_tables(): """Create the Blockade DynamoDB tables.""" logger.debug("[#] Setting up DynamoDB tables") client = boto3.client('dynamodb', region_name=PRIMARY_REGION) existing_tables = client.list_tables()['TableNames'] responses = list() for label in DYNAMODB_TABLES: i...
python
def generate_dynamodb_tables(): """Create the Blockade DynamoDB tables.""" logger.debug("[#] Setting up DynamoDB tables") client = boto3.client('dynamodb', region_name=PRIMARY_REGION) existing_tables = client.list_tables()['TableNames'] responses = list() for label in DYNAMODB_TABLES: i...
[ "def", "generate_dynamodb_tables", "(", ")", ":", "logger", ".", "debug", "(", "\"[#] Setting up DynamoDB tables\"", ")", "client", "=", "boto3", ".", "client", "(", "'dynamodb'", ",", "region_name", "=", "PRIMARY_REGION", ")", "existing_tables", "=", "client", "....
Create the Blockade DynamoDB tables.
[ "Create", "the", "Blockade", "DynamoDB", "tables", "." ]
159b6f8cf8a91c5ff050f1579636ea90ab269863
https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/cli/aws_serverless.py#L592-L617
train
57,050
blockadeio/analyst_toolbench
blockade/cli/aws_serverless.py
remove_dynamodb_tables
def remove_dynamodb_tables(): """Remove the Blockade DynamoDB tables.""" logger.debug("[#] Removing DynamoDB tables") client = boto3.client('dynamodb', region_name=PRIMARY_REGION) responses = list() for label in DYNAMODB_TABLES: logger.debug("[*] Removing %s table" % (label)) try: ...
python
def remove_dynamodb_tables(): """Remove the Blockade DynamoDB tables.""" logger.debug("[#] Removing DynamoDB tables") client = boto3.client('dynamodb', region_name=PRIMARY_REGION) responses = list() for label in DYNAMODB_TABLES: logger.debug("[*] Removing %s table" % (label)) try: ...
[ "def", "remove_dynamodb_tables", "(", ")", ":", "logger", ".", "debug", "(", "\"[#] Removing DynamoDB tables\"", ")", "client", "=", "boto3", ".", "client", "(", "'dynamodb'", ",", "region_name", "=", "PRIMARY_REGION", ")", "responses", "=", "list", "(", ")", ...
Remove the Blockade DynamoDB tables.
[ "Remove", "the", "Blockade", "DynamoDB", "tables", "." ]
159b6f8cf8a91c5ff050f1579636ea90ab269863
https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/cli/aws_serverless.py#L620-L639
train
57,051
blockadeio/analyst_toolbench
blockade/cli/aws_serverless.py
generate_lambda_functions
def generate_lambda_functions(): """Create the Blockade lambda functions.""" logger.debug("[#] Setting up the Lambda functions") aws_lambda = boto3.client('lambda', region_name=PRIMARY_REGION) functions = aws_lambda.list_functions().get('Functions') existing_funcs = [x['FunctionName'] for x in funct...
python
def generate_lambda_functions(): """Create the Blockade lambda functions.""" logger.debug("[#] Setting up the Lambda functions") aws_lambda = boto3.client('lambda', region_name=PRIMARY_REGION) functions = aws_lambda.list_functions().get('Functions') existing_funcs = [x['FunctionName'] for x in funct...
[ "def", "generate_lambda_functions", "(", ")", ":", "logger", ".", "debug", "(", "\"[#] Setting up the Lambda functions\"", ")", "aws_lambda", "=", "boto3", ".", "client", "(", "'lambda'", ",", "region_name", "=", "PRIMARY_REGION", ")", "functions", "=", "aws_lambda"...
Create the Blockade lambda functions.
[ "Create", "the", "Blockade", "lambda", "functions", "." ]
159b6f8cf8a91c5ff050f1579636ea90ab269863
https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/cli/aws_serverless.py#L642-L677
train
57,052
blockadeio/analyst_toolbench
blockade/cli/aws_serverless.py
remove_lambda_functions
def remove_lambda_functions(): """Remove the Blockade Lambda functions.""" logger.debug("[#] Removing the Lambda functions") client = boto3.client('lambda', region_name=PRIMARY_REGION) responses = list() for label in LAMBDA_FUNCTIONS: try: response = client.delete_function( ...
python
def remove_lambda_functions(): """Remove the Blockade Lambda functions.""" logger.debug("[#] Removing the Lambda functions") client = boto3.client('lambda', region_name=PRIMARY_REGION) responses = list() for label in LAMBDA_FUNCTIONS: try: response = client.delete_function( ...
[ "def", "remove_lambda_functions", "(", ")", ":", "logger", ".", "debug", "(", "\"[#] Removing the Lambda functions\"", ")", "client", "=", "boto3", ".", "client", "(", "'lambda'", ",", "region_name", "=", "PRIMARY_REGION", ")", "responses", "=", "list", "(", ")"...
Remove the Blockade Lambda functions.
[ "Remove", "the", "Blockade", "Lambda", "functions", "." ]
159b6f8cf8a91c5ff050f1579636ea90ab269863
https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/cli/aws_serverless.py#L680-L698
train
57,053
blockadeio/analyst_toolbench
blockade/cli/aws_serverless.py
generate_api_gateway
def generate_api_gateway(): """Create the Blockade API Gateway REST service.""" logger.debug("[#] Setting up the API Gateway") client = boto3.client('apigateway', region_name=PRIMARY_REGION) matches = [x for x in client.get_rest_apis().get('items', list()) if x['name'] == API_GATEWAY] ...
python
def generate_api_gateway(): """Create the Blockade API Gateway REST service.""" logger.debug("[#] Setting up the API Gateway") client = boto3.client('apigateway', region_name=PRIMARY_REGION) matches = [x for x in client.get_rest_apis().get('items', list()) if x['name'] == API_GATEWAY] ...
[ "def", "generate_api_gateway", "(", ")", ":", "logger", ".", "debug", "(", "\"[#] Setting up the API Gateway\"", ")", "client", "=", "boto3", ".", "client", "(", "'apigateway'", ",", "region_name", "=", "PRIMARY_REGION", ")", "matches", "=", "[", "x", "for", "...
Create the Blockade API Gateway REST service.
[ "Create", "the", "Blockade", "API", "Gateway", "REST", "service", "." ]
159b6f8cf8a91c5ff050f1579636ea90ab269863
https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/cli/aws_serverless.py#L701-L717
train
57,054
blockadeio/analyst_toolbench
blockade/cli/aws_serverless.py
generate_admin_resource
def generate_admin_resource(): """Create the Blockade admin resource for the REST services.""" logger.debug("[#] Setting up the admin resource") client = boto3.client('apigateway', region_name=PRIMARY_REGION) existing = get_api_gateway_resource("admin") if existing: logger.debug("[#] API adm...
python
def generate_admin_resource(): """Create the Blockade admin resource for the REST services.""" logger.debug("[#] Setting up the admin resource") client = boto3.client('apigateway', region_name=PRIMARY_REGION) existing = get_api_gateway_resource("admin") if existing: logger.debug("[#] API adm...
[ "def", "generate_admin_resource", "(", ")", ":", "logger", ".", "debug", "(", "\"[#] Setting up the admin resource\"", ")", "client", "=", "boto3", ".", "client", "(", "'apigateway'", ",", "region_name", "=", "PRIMARY_REGION", ")", "existing", "=", "get_api_gateway_...
Create the Blockade admin resource for the REST services.
[ "Create", "the", "Blockade", "admin", "resource", "for", "the", "REST", "services", "." ]
159b6f8cf8a91c5ff050f1579636ea90ab269863
https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/cli/aws_serverless.py#L720-L739
train
57,055
blockadeio/analyst_toolbench
blockade/cli/aws_serverless.py
get_api_gateway_resource
def get_api_gateway_resource(name): """Get the resource associated with our gateway.""" client = boto3.client('apigateway', region_name=PRIMARY_REGION) matches = [x for x in client.get_rest_apis().get('items', list()) if x['name'] == API_GATEWAY] match = matches.pop() resources = clie...
python
def get_api_gateway_resource(name): """Get the resource associated with our gateway.""" client = boto3.client('apigateway', region_name=PRIMARY_REGION) matches = [x for x in client.get_rest_apis().get('items', list()) if x['name'] == API_GATEWAY] match = matches.pop() resources = clie...
[ "def", "get_api_gateway_resource", "(", "name", ")", ":", "client", "=", "boto3", ".", "client", "(", "'apigateway'", ",", "region_name", "=", "PRIMARY_REGION", ")", "matches", "=", "[", "x", "for", "x", "in", "client", ".", "get_rest_apis", "(", ")", ".",...
Get the resource associated with our gateway.
[ "Get", "the", "resource", "associated", "with", "our", "gateway", "." ]
159b6f8cf8a91c5ff050f1579636ea90ab269863
https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/cli/aws_serverless.py#L742-L754
train
57,056
blockadeio/analyst_toolbench
blockade/cli/aws_serverless.py
remove_api_gateway
def remove_api_gateway(): """Remove the Blockade REST API service.""" logger.debug("[#] Removing API Gateway") client = boto3.client('apigateway', region_name=PRIMARY_REGION) matches = [x for x in client.get_rest_apis().get('items', list()) if x['name'] == API_GATEWAY] if len(matches)...
python
def remove_api_gateway(): """Remove the Blockade REST API service.""" logger.debug("[#] Removing API Gateway") client = boto3.client('apigateway', region_name=PRIMARY_REGION) matches = [x for x in client.get_rest_apis().get('items', list()) if x['name'] == API_GATEWAY] if len(matches)...
[ "def", "remove_api_gateway", "(", ")", ":", "logger", ".", "debug", "(", "\"[#] Removing API Gateway\"", ")", "client", "=", "boto3", ".", "client", "(", "'apigateway'", ",", "region_name", "=", "PRIMARY_REGION", ")", "matches", "=", "[", "x", "for", "x", "i...
Remove the Blockade REST API service.
[ "Remove", "the", "Blockade", "REST", "API", "service", "." ]
159b6f8cf8a91c5ff050f1579636ea90ab269863
https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/cli/aws_serverless.py#L863-L878
train
57,057
Julian/Minion
minion/traversal.py
method_delegate
def method_delegate(**methods): """ Construct a renderer that delegates based on the request's HTTP method. """ methods = {k.upper(): v for k, v in iteritems(methods)} if PY3: methods = {k.encode("utf-8"): v for k, v in iteritems(methods)} def render(request): renderer = meth...
python
def method_delegate(**methods): """ Construct a renderer that delegates based on the request's HTTP method. """ methods = {k.upper(): v for k, v in iteritems(methods)} if PY3: methods = {k.encode("utf-8"): v for k, v in iteritems(methods)} def render(request): renderer = meth...
[ "def", "method_delegate", "(", "*", "*", "methods", ")", ":", "methods", "=", "{", "k", ".", "upper", "(", ")", ":", "v", "for", "k", ",", "v", "in", "iteritems", "(", "methods", ")", "}", "if", "PY3", ":", "methods", "=", "{", "k", ".", "encod...
Construct a renderer that delegates based on the request's HTTP method.
[ "Construct", "a", "renderer", "that", "delegates", "based", "on", "the", "request", "s", "HTTP", "method", "." ]
518d06f9ffd38dcacc0de4d94e72d1f8452157a8
https://github.com/Julian/Minion/blob/518d06f9ffd38dcacc0de4d94e72d1f8452157a8/minion/traversal.py#L45-L61
train
57,058
Julian/Minion
minion/traversal.py
traverse
def traverse(path, request, resource): """ Traverse a root resource, retrieving the appropriate child for the request. """ path = path.lstrip(b"/") for component in path and path.split(b"/"): if getattr(resource, "is_leaf", False): break resource = resource.get_child(na...
python
def traverse(path, request, resource): """ Traverse a root resource, retrieving the appropriate child for the request. """ path = path.lstrip(b"/") for component in path and path.split(b"/"): if getattr(resource, "is_leaf", False): break resource = resource.get_child(na...
[ "def", "traverse", "(", "path", ",", "request", ",", "resource", ")", ":", "path", "=", "path", ".", "lstrip", "(", "b\"/\"", ")", "for", "component", "in", "path", "and", "path", ".", "split", "(", "b\"/\"", ")", ":", "if", "getattr", "(", "resource...
Traverse a root resource, retrieving the appropriate child for the request.
[ "Traverse", "a", "root", "resource", "retrieving", "the", "appropriate", "child", "for", "the", "request", "." ]
518d06f9ffd38dcacc0de4d94e72d1f8452157a8
https://github.com/Julian/Minion/blob/518d06f9ffd38dcacc0de4d94e72d1f8452157a8/minion/traversal.py#L64-L75
train
57,059
inveniosoftware-attic/invenio-utils
invenio_utils/shell.py
escape_shell_arg
def escape_shell_arg(shell_arg): """Escape shell argument shell_arg by placing it within single-quotes. Any single quotes found within the shell argument string will be escaped. @param shell_arg: The shell argument to be escaped. @type shell_arg: string @return: The single-quote-escaped value ...
python
def escape_shell_arg(shell_arg): """Escape shell argument shell_arg by placing it within single-quotes. Any single quotes found within the shell argument string will be escaped. @param shell_arg: The shell argument to be escaped. @type shell_arg: string @return: The single-quote-escaped value ...
[ "def", "escape_shell_arg", "(", "shell_arg", ")", ":", "if", "isinstance", "(", "shell_arg", ",", "six", ".", "text_type", ")", ":", "msg", "=", "\"ERROR: escape_shell_arg() expected string argument but \"", "\"got '%s' of type '%s'.\"", "%", "(", "repr", "(", "shell_...
Escape shell argument shell_arg by placing it within single-quotes. Any single quotes found within the shell argument string will be escaped. @param shell_arg: The shell argument to be escaped. @type shell_arg: string @return: The single-quote-escaped value of the shell argument. @rtype: strin...
[ "Escape", "shell", "argument", "shell_arg", "by", "placing", "it", "within", "single", "-", "quotes", ".", "Any", "single", "quotes", "found", "within", "the", "shell", "argument", "string", "will", "be", "escaped", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/shell.py#L309-L327
train
57,060
inveniosoftware-attic/invenio-utils
invenio_utils/shell.py
retry_mkstemp
def retry_mkstemp(suffix='', prefix='tmp', directory=None, max_retries=3): """ Make mkstemp more robust against AFS glitches. """ if directory is None: directory = current_app.config['CFG_TMPSHAREDDIR'] for retry_count in range(1, max_retries + 1): try: tmp_file_fd, tmp_f...
python
def retry_mkstemp(suffix='', prefix='tmp', directory=None, max_retries=3): """ Make mkstemp more robust against AFS glitches. """ if directory is None: directory = current_app.config['CFG_TMPSHAREDDIR'] for retry_count in range(1, max_retries + 1): try: tmp_file_fd, tmp_f...
[ "def", "retry_mkstemp", "(", "suffix", "=", "''", ",", "prefix", "=", "'tmp'", ",", "directory", "=", "None", ",", "max_retries", "=", "3", ")", ":", "if", "directory", "is", "None", ":", "directory", "=", "current_app", ".", "config", "[", "'CFG_TMPSHAR...
Make mkstemp more robust against AFS glitches.
[ "Make", "mkstemp", "more", "robust", "against", "AFS", "glitches", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/shell.py#L330-L349
train
57,061
freevoid/django-datafilters
datafilters/declarative.py
declarative_fields
def declarative_fields(cls_filter, meta_base=type, extra_attr_name='base_fields'): """ Metaclass that converts Field attributes to a dictionary called 'base_fields', taking into account parent class 'cls_filter'. """ def __new__(cls, name, bases, attrs): attrs[extra_attr_name] = fields = get...
python
def declarative_fields(cls_filter, meta_base=type, extra_attr_name='base_fields'): """ Metaclass that converts Field attributes to a dictionary called 'base_fields', taking into account parent class 'cls_filter'. """ def __new__(cls, name, bases, attrs): attrs[extra_attr_name] = fields = get...
[ "def", "declarative_fields", "(", "cls_filter", ",", "meta_base", "=", "type", ",", "extra_attr_name", "=", "'base_fields'", ")", ":", "def", "__new__", "(", "cls", ",", "name", ",", "bases", ",", "attrs", ")", ":", "attrs", "[", "extra_attr_name", "]", "=...
Metaclass that converts Field attributes to a dictionary called 'base_fields', taking into account parent class 'cls_filter'.
[ "Metaclass", "that", "converts", "Field", "attributes", "to", "a", "dictionary", "called", "base_fields", "taking", "into", "account", "parent", "class", "cls_filter", "." ]
99051b3b3e97946981c0e9697576b0100093287c
https://github.com/freevoid/django-datafilters/blob/99051b3b3e97946981c0e9697576b0100093287c/datafilters/declarative.py#L40-L52
train
57,062
CodyKochmann/generators
generators/started.py
started
def started(generator_function): """ starts a generator when created """ @wraps(generator_function) def wrapper(*args, **kwargs): g = generator_function(*args, **kwargs) next(g) return g return wrapper
python
def started(generator_function): """ starts a generator when created """ @wraps(generator_function) def wrapper(*args, **kwargs): g = generator_function(*args, **kwargs) next(g) return g return wrapper
[ "def", "started", "(", "generator_function", ")", ":", "@", "wraps", "(", "generator_function", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "g", "=", "generator_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ...
starts a generator when created
[ "starts", "a", "generator", "when", "created" ]
e4ca4dd25d5023a94b0349c69d6224070cc2526f
https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/started.py#L11-L18
train
57,063
trevisanj/a99
a99/gui/_logpart.py
_LogPart.add_log_error
def add_log_error(self, x, flag_also_show=False, E=None): """Sets text of labelError.""" if len(x) == 0: x = "(empty error)" tb.print_stack() x_ = x if E is not None: a99.get_python_logger().exception(x_) else: a99.get_pyth...
python
def add_log_error(self, x, flag_also_show=False, E=None): """Sets text of labelError.""" if len(x) == 0: x = "(empty error)" tb.print_stack() x_ = x if E is not None: a99.get_python_logger().exception(x_) else: a99.get_pyth...
[ "def", "add_log_error", "(", "self", ",", "x", ",", "flag_also_show", "=", "False", ",", "E", "=", "None", ")", ":", "if", "len", "(", "x", ")", "==", "0", ":", "x", "=", "\"(empty error)\"", "tb", ".", "print_stack", "(", ")", "x_", "=", "x", "i...
Sets text of labelError.
[ "Sets", "text", "of", "labelError", "." ]
193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539
https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/gui/_logpart.py#L24-L38
train
57,064
ThomasChiroux/attowiki
src/attowiki/views.py
check_user
def check_user(user, password): """check the auth for user and password.""" return ((user == attowiki.user or attowiki.user is None) and (password == attowiki.password or attowiki.password is None))
python
def check_user(user, password): """check the auth for user and password.""" return ((user == attowiki.user or attowiki.user is None) and (password == attowiki.password or attowiki.password is None))
[ "def", "check_user", "(", "user", ",", "password", ")", ":", "return", "(", "(", "user", "==", "attowiki", ".", "user", "or", "attowiki", ".", "user", "is", "None", ")", "and", "(", "password", "==", "attowiki", ".", "password", "or", "attowiki", ".", ...
check the auth for user and password.
[ "check", "the", "auth", "for", "user", "and", "password", "." ]
6c93c420305490d324fdc95a7b40b2283a222183
https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/views.py#L55-L58
train
57,065
ThomasChiroux/attowiki
src/attowiki/views.py
view_meta_index
def view_meta_index(): """List all the available .rst files in the directory. view_meta_index is called by the 'meta' url : /__index__ """ rst_files = [filename[2:-4] for filename in sorted(glob.glob("./*.rst"))] rst_files.reverse() return template('index', type="view", ...
python
def view_meta_index(): """List all the available .rst files in the directory. view_meta_index is called by the 'meta' url : /__index__ """ rst_files = [filename[2:-4] for filename in sorted(glob.glob("./*.rst"))] rst_files.reverse() return template('index', type="view", ...
[ "def", "view_meta_index", "(", ")", ":", "rst_files", "=", "[", "filename", "[", "2", ":", "-", "4", "]", "for", "filename", "in", "sorted", "(", "glob", ".", "glob", "(", "\"./*.rst\"", ")", ")", "]", "rst_files", ".", "reverse", "(", ")", "return",...
List all the available .rst files in the directory. view_meta_index is called by the 'meta' url : /__index__
[ "List", "all", "the", "available", ".", "rst", "files", "in", "the", "directory", "." ]
6c93c420305490d324fdc95a7b40b2283a222183
https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/views.py#L68-L82
train
57,066
ThomasChiroux/attowiki
src/attowiki/views.py
view_cancel_edit
def view_cancel_edit(name=None): """Cancel the edition of an existing page. Then render the last modification status .. note:: this is a bottle view if no page name is given, do nothing (it may leave some .tmp. files in the directory). Keyword Arguments: :name: (str) -- name of the p...
python
def view_cancel_edit(name=None): """Cancel the edition of an existing page. Then render the last modification status .. note:: this is a bottle view if no page name is given, do nothing (it may leave some .tmp. files in the directory). Keyword Arguments: :name: (str) -- name of the p...
[ "def", "view_cancel_edit", "(", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "return", "redirect", "(", "'/'", ")", "else", ":", "files", "=", "glob", ".", "glob", "(", "\"{0}.rst\"", ".", "format", "(", "name", ")", ")", "if", "...
Cancel the edition of an existing page. Then render the last modification status .. note:: this is a bottle view if no page name is given, do nothing (it may leave some .tmp. files in the directory). Keyword Arguments: :name: (str) -- name of the page (OPTIONAL) Returns: bot...
[ "Cancel", "the", "edition", "of", "an", "existing", "page", "." ]
6c93c420305490d324fdc95a7b40b2283a222183
https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/views.py#L211-L235
train
57,067
ThomasChiroux/attowiki
src/attowiki/views.py
view_edit
def view_edit(name=None): """Edit or creates a new page. .. note:: this is a bottle view if no page name is given, creates a new page. Keyword Arguments: :name: (str) -- name of the page (OPTIONAL) Returns: bottle response object """ response.set_header('Cache-control', '...
python
def view_edit(name=None): """Edit or creates a new page. .. note:: this is a bottle view if no page name is given, creates a new page. Keyword Arguments: :name: (str) -- name of the page (OPTIONAL) Returns: bottle response object """ response.set_header('Cache-control', '...
[ "def", "view_edit", "(", "name", "=", "None", ")", ":", "response", ".", "set_header", "(", "'Cache-control'", ",", "'no-cache'", ")", "response", ".", "set_header", "(", "'Pragma'", ",", "'no-cache'", ")", "if", "name", "is", "None", ":", "# new page", "r...
Edit or creates a new page. .. note:: this is a bottle view if no page name is given, creates a new page. Keyword Arguments: :name: (str) -- name of the page (OPTIONAL) Returns: bottle response object
[ "Edit", "or", "creates", "a", "new", "page", "." ]
6c93c420305490d324fdc95a7b40b2283a222183
https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/views.py#L239-L279
train
57,068
ThomasChiroux/attowiki
src/attowiki/views.py
view_pdf
def view_pdf(name=None): """Render a pdf file based on the given page. .. note:: this is a bottle view Keyword Arguments: :name: (str) -- name of the rest file (without the .rst extension) MANDATORY """ if name is None: return view_meta_index() files = ...
python
def view_pdf(name=None): """Render a pdf file based on the given page. .. note:: this is a bottle view Keyword Arguments: :name: (str) -- name of the rest file (without the .rst extension) MANDATORY """ if name is None: return view_meta_index() files = ...
[ "def", "view_pdf", "(", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "return", "view_meta_index", "(", ")", "files", "=", "glob", ".", "glob", "(", "\"{0}.rst\"", ".", "format", "(", "name", ")", ")", "if", "len", "(", "files", "...
Render a pdf file based on the given page. .. note:: this is a bottle view Keyword Arguments: :name: (str) -- name of the rest file (without the .rst extension) MANDATORY
[ "Render", "a", "pdf", "file", "based", "on", "the", "given", "page", "." ]
6c93c420305490d324fdc95a7b40b2283a222183
https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/views.py#L283-L310
train
57,069
ThomasChiroux/attowiki
src/attowiki/views.py
view_page
def view_page(name=None): """Serve a page name. .. note:: this is a bottle view * if the view is called with the POST method, write the new page content to the file, commit the modification and then display the html rendering of the restructured text file * if the view is called with the ...
python
def view_page(name=None): """Serve a page name. .. note:: this is a bottle view * if the view is called with the POST method, write the new page content to the file, commit the modification and then display the html rendering of the restructured text file * if the view is called with the ...
[ "def", "view_page", "(", "name", "=", "None", ")", ":", "if", "request", ".", "method", "==", "'POST'", ":", "if", "name", "is", "None", ":", "# new file", "if", "len", "(", "request", ".", "forms", ".", "filename", ")", ">", "0", ":", "name", "=",...
Serve a page name. .. note:: this is a bottle view * if the view is called with the POST method, write the new page content to the file, commit the modification and then display the html rendering of the restructured text file * if the view is called with the GET method, directly display the ...
[ "Serve", "a", "page", "name", "." ]
6c93c420305490d324fdc95a7b40b2283a222183
https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/views.py#L314-L378
train
57,070
ThomasChiroux/attowiki
src/attowiki/views.py
view_quick_save_page
def view_quick_save_page(name=None): """Quick save a page. .. note:: this is a bottle view * this view must be called with the PUT method write the new page content to the file, and not not commit or redirect Keyword Arguments: :name: (str) -- name of the rest file (without the .rst ext...
python
def view_quick_save_page(name=None): """Quick save a page. .. note:: this is a bottle view * this view must be called with the PUT method write the new page content to the file, and not not commit or redirect Keyword Arguments: :name: (str) -- name of the rest file (without the .rst ext...
[ "def", "view_quick_save_page", "(", "name", "=", "None", ")", ":", "response", ".", "set_header", "(", "'Cache-control'", ",", "'no-cache'", ")", "response", ".", "set_header", "(", "'Pragma'", ",", "'no-cache'", ")", "if", "request", ".", "method", "==", "'...
Quick save a page. .. note:: this is a bottle view * this view must be called with the PUT method write the new page content to the file, and not not commit or redirect Keyword Arguments: :name: (str) -- name of the rest file (without the .rst extension) Returns: bottle respons...
[ "Quick", "save", "a", "page", "." ]
6c93c420305490d324fdc95a7b40b2283a222183
https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/views.py#L508-L539
train
57,071
trevisanj/f311
f311/hapi.py
getHelp
def getHelp(arg=None): """ This function provides interactive manuals and tutorials. """ if arg==None: print('--------------------------------------------------------------') print('Hello, this is an interactive help system of HITRANonline API.') print('--------------------------...
python
def getHelp(arg=None): """ This function provides interactive manuals and tutorials. """ if arg==None: print('--------------------------------------------------------------') print('Hello, this is an interactive help system of HITRANonline API.') print('--------------------------...
[ "def", "getHelp", "(", "arg", "=", "None", ")", ":", "if", "arg", "==", "None", ":", "print", "(", "'--------------------------------------------------------------'", ")", "print", "(", "'Hello, this is an interactive help system of HITRANonline API.'", ")", "print", "(",...
This function provides interactive manuals and tutorials.
[ "This", "function", "provides", "interactive", "manuals", "and", "tutorials", "." ]
9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7
https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/hapi.py#L4956-L5049
train
57,072
trevisanj/f311
f311/hapi.py
convolveSpectrumSame
def convolveSpectrumSame(Omega,CrossSection,Resolution=0.1,AF_wing=10., SlitFunction=SLIT_RECTANGULAR): """ Convolves cross section with a slit function with given parameters. """ step = Omega[1]-Omega[0] x = arange(-AF_wing,AF_wing+step,step) slit = SlitFunction(x,Resol...
python
def convolveSpectrumSame(Omega,CrossSection,Resolution=0.1,AF_wing=10., SlitFunction=SLIT_RECTANGULAR): """ Convolves cross section with a slit function with given parameters. """ step = Omega[1]-Omega[0] x = arange(-AF_wing,AF_wing+step,step) slit = SlitFunction(x,Resol...
[ "def", "convolveSpectrumSame", "(", "Omega", ",", "CrossSection", ",", "Resolution", "=", "0.1", ",", "AF_wing", "=", "10.", ",", "SlitFunction", "=", "SLIT_RECTANGULAR", ")", ":", "step", "=", "Omega", "[", "1", "]", "-", "Omega", "[", "0", "]", "x", ...
Convolves cross section with a slit function with given parameters.
[ "Convolves", "cross", "section", "with", "a", "slit", "function", "with", "given", "parameters", "." ]
9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7
https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/hapi.py#L11918-L11933
train
57,073
nuSTORM/gnomon
gnomon/processors/DataManager.py
CouchManager.setup_db
def setup_db(self, couch, dbname): """Setup and configure DB """ # Avoid race condition of two creating db my_db = None self.log.debug('Setting up DB: %s' % dbname) if dbname not in couch: self.log.info("DB doesn't exist so creating DB: %s", dbname) ...
python
def setup_db(self, couch, dbname): """Setup and configure DB """ # Avoid race condition of two creating db my_db = None self.log.debug('Setting up DB: %s' % dbname) if dbname not in couch: self.log.info("DB doesn't exist so creating DB: %s", dbname) ...
[ "def", "setup_db", "(", "self", ",", "couch", ",", "dbname", ")", ":", "# Avoid race condition of two creating db", "my_db", "=", "None", "self", ".", "log", ".", "debug", "(", "'Setting up DB: %s'", "%", "dbname", ")", "if", "dbname", "not", "in", "couch", ...
Setup and configure DB
[ "Setup", "and", "configure", "DB" ]
7616486ecd6e26b76f677c380e62db1c0ade558a
https://github.com/nuSTORM/gnomon/blob/7616486ecd6e26b76f677c380e62db1c0ade558a/gnomon/processors/DataManager.py#L62-L101
train
57,074
nuSTORM/gnomon
gnomon/processors/DataManager.py
CouchManager.commit
def commit(self, force=False): """Commit data to couchdb Compared to threshold (unless forced) then sends data to couch """ self.log.debug('Bulk commit requested') size = sys.getsizeof(self.docs) self.log.debug('Size of docs in KB: %d', size) if size > self.comm...
python
def commit(self, force=False): """Commit data to couchdb Compared to threshold (unless forced) then sends data to couch """ self.log.debug('Bulk commit requested') size = sys.getsizeof(self.docs) self.log.debug('Size of docs in KB: %d', size) if size > self.comm...
[ "def", "commit", "(", "self", ",", "force", "=", "False", ")", ":", "self", ".", "log", ".", "debug", "(", "'Bulk commit requested'", ")", "size", "=", "sys", ".", "getsizeof", "(", "self", ".", "docs", ")", "self", ".", "log", ".", "debug", "(", "...
Commit data to couchdb Compared to threshold (unless forced) then sends data to couch
[ "Commit", "data", "to", "couchdb" ]
7616486ecd6e26b76f677c380e62db1c0ade558a
https://github.com/nuSTORM/gnomon/blob/7616486ecd6e26b76f677c380e62db1c0ade558a/gnomon/processors/DataManager.py#L103-L115
train
57,075
nuSTORM/gnomon
gnomon/processors/DataManager.py
CouchManager.save
def save(self, doc): """Save a doc to cache """ self.log.debug('save()') self.docs.append(doc) self.commit()
python
def save(self, doc): """Save a doc to cache """ self.log.debug('save()') self.docs.append(doc) self.commit()
[ "def", "save", "(", "self", ",", "doc", ")", ":", "self", ".", "log", ".", "debug", "(", "'save()'", ")", "self", ".", "docs", ".", "append", "(", "doc", ")", "self", ".", "commit", "(", ")" ]
Save a doc to cache
[ "Save", "a", "doc", "to", "cache" ]
7616486ecd6e26b76f677c380e62db1c0ade558a
https://github.com/nuSTORM/gnomon/blob/7616486ecd6e26b76f677c380e62db1c0ade558a/gnomon/processors/DataManager.py#L117-L122
train
57,076
mixer/beam-interactive-python
beam_interactive/helpers.py
start
def start(address, channel, key, loop=None): """Starts a new Interactive client. Takes the remote address of the Tetris robot, as well as the channel number and auth key to use. Additionally, it takes a list of handler. This should be a dict of protobuf wire IDs to handler functions (from the .prot...
python
def start(address, channel, key, loop=None): """Starts a new Interactive client. Takes the remote address of the Tetris robot, as well as the channel number and auth key to use. Additionally, it takes a list of handler. This should be a dict of protobuf wire IDs to handler functions (from the .prot...
[ "def", "start", "(", "address", ",", "channel", ",", "key", ",", "loop", "=", "None", ")", ":", "if", "loop", "is", "None", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "socket", "=", "yield", "from", "websockets", ".", "connect", "(...
Starts a new Interactive client. Takes the remote address of the Tetris robot, as well as the channel number and auth key to use. Additionally, it takes a list of handler. This should be a dict of protobuf wire IDs to handler functions (from the .proto package).
[ "Starts", "a", "new", "Interactive", "client", "." ]
e035bc45515dea9315b77648a24b5ae8685aa5cf
https://github.com/mixer/beam-interactive-python/blob/e035bc45515dea9315b77648a24b5ae8685aa5cf/beam_interactive/helpers.py#L8-L25
train
57,077
mixer/beam-interactive-python
beam_interactive/helpers.py
_create_handshake
def _create_handshake(channel, key): """ Creates and returns a Handshake packet that authenticates on the channel with the given stream key. """ hsk = Handshake() hsk.channel = channel hsk.streamKey = key return hsk
python
def _create_handshake(channel, key): """ Creates and returns a Handshake packet that authenticates on the channel with the given stream key. """ hsk = Handshake() hsk.channel = channel hsk.streamKey = key return hsk
[ "def", "_create_handshake", "(", "channel", ",", "key", ")", ":", "hsk", "=", "Handshake", "(", ")", "hsk", ".", "channel", "=", "channel", "hsk", ".", "streamKey", "=", "key", "return", "hsk" ]
Creates and returns a Handshake packet that authenticates on the channel with the given stream key.
[ "Creates", "and", "returns", "a", "Handshake", "packet", "that", "authenticates", "on", "the", "channel", "with", "the", "given", "stream", "key", "." ]
e035bc45515dea9315b77648a24b5ae8685aa5cf
https://github.com/mixer/beam-interactive-python/blob/e035bc45515dea9315b77648a24b5ae8685aa5cf/beam_interactive/helpers.py#L28-L36
train
57,078
bogdanvuk/pygears-tools
pygears_tools/utils.py
shell_source
def shell_source(script): """Sometime you want to emulate the action of "source" in bash, settings some environment variables. Here is a way to do it.""" pipe = subprocess.Popen( ". %s; env" % script, stdout=subprocess.PIPE, shell=True) output = pipe.communicate()[0].decode() env = {} fo...
python
def shell_source(script): """Sometime you want to emulate the action of "source" in bash, settings some environment variables. Here is a way to do it.""" pipe = subprocess.Popen( ". %s; env" % script, stdout=subprocess.PIPE, shell=True) output = pipe.communicate()[0].decode() env = {} fo...
[ "def", "shell_source", "(", "script", ")", ":", "pipe", "=", "subprocess", ".", "Popen", "(", "\". %s; env\"", "%", "script", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "shell", "=", "True", ")", "output", "=", "pipe", ".", "communicate", "(", ...
Sometime you want to emulate the action of "source" in bash, settings some environment variables. Here is a way to do it.
[ "Sometime", "you", "want", "to", "emulate", "the", "action", "of", "source", "in", "bash", "settings", "some", "environment", "variables", ".", "Here", "is", "a", "way", "to", "do", "it", "." ]
47e3287add1cbc5d2efc9e35aa55fce69e440dc9
https://github.com/bogdanvuk/pygears-tools/blob/47e3287add1cbc5d2efc9e35aa55fce69e440dc9/pygears_tools/utils.py#L170-L184
train
57,079
jkitzes/macroeco
macroeco/compare/_compare.py
nll
def nll(data, model): """ Negative log likelihood given data and a model Parameters ---------- {0} {1} Returns ------- float Negative log likelihood Examples --------- >>> import macroeco.models as md >>> import macroeco.compare as comp >>> # Generate...
python
def nll(data, model): """ Negative log likelihood given data and a model Parameters ---------- {0} {1} Returns ------- float Negative log likelihood Examples --------- >>> import macroeco.models as md >>> import macroeco.compare as comp >>> # Generate...
[ "def", "nll", "(", "data", ",", "model", ")", ":", "try", ":", "log_lik_vals", "=", "model", ".", "logpmf", "(", "data", ")", "except", ":", "log_lik_vals", "=", "model", ".", "logpdf", "(", "data", ")", "return", "-", "np", ".", "sum", "(", "log_l...
Negative log likelihood given data and a model Parameters ---------- {0} {1} Returns ------- float Negative log likelihood Examples --------- >>> import macroeco.models as md >>> import macroeco.compare as comp >>> # Generate random data >>> rand_samp = m...
[ "Negative", "log", "likelihood", "given", "data", "and", "a", "model" ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/compare/_compare.py#L27-L65
train
57,080
jkitzes/macroeco
macroeco/compare/_compare.py
lrt
def lrt(data, model_full, model_reduced, df=None): """ Compare two nested models using a likelihood ratio test Parameters ---------- {0} model_full : obj A frozen scipy distribution object representing the full model (more complex model). model_reduced : scipy distribution o...
python
def lrt(data, model_full, model_reduced, df=None): """ Compare two nested models using a likelihood ratio test Parameters ---------- {0} model_full : obj A frozen scipy distribution object representing the full model (more complex model). model_reduced : scipy distribution o...
[ "def", "lrt", "(", "data", ",", "model_full", ",", "model_reduced", ",", "df", "=", "None", ")", ":", "# Calculate G^2 statistic", "ll_full", "=", "nll", "(", "data", ",", "model_full", ")", "*", "-", "1", "ll_reduced", "=", "nll", "(", "data", ",", "m...
Compare two nested models using a likelihood ratio test Parameters ---------- {0} model_full : obj A frozen scipy distribution object representing the full model (more complex model). model_reduced : scipy distribution object A frozen scipy distribution object representing t...
[ "Compare", "two", "nested", "models", "using", "a", "likelihood", "ratio", "test" ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/compare/_compare.py#L69-L139
train
57,081
jkitzes/macroeco
macroeco/compare/_compare.py
AIC
def AIC(data, model, params=None, corrected=True): """ Akaike Information Criteria given data and a model Parameters ---------- {0} {1} params : int Number of parameters in the model. If None, calculated from model object. corrected : bool If True, calculates the...
python
def AIC(data, model, params=None, corrected=True): """ Akaike Information Criteria given data and a model Parameters ---------- {0} {1} params : int Number of parameters in the model. If None, calculated from model object. corrected : bool If True, calculates the...
[ "def", "AIC", "(", "data", ",", "model", ",", "params", "=", "None", ",", "corrected", "=", "True", ")", ":", "n", "=", "len", "(", "data", ")", "# Number of observations", "L", "=", "nll", "(", "data", ",", "model", ")", "if", "not", "params", ":"...
Akaike Information Criteria given data and a model Parameters ---------- {0} {1} params : int Number of parameters in the model. If None, calculated from model object. corrected : bool If True, calculates the small-sample size correct AICC. Default True. Returns ...
[ "Akaike", "Information", "Criteria", "given", "data", "and", "a", "model" ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/compare/_compare.py#L143-L221
train
57,082
jkitzes/macroeco
macroeco/compare/_compare.py
AIC_compare
def AIC_compare(aic_list): """ Calculates delta AIC and AIC weights from a list of AIC values Parameters ----------------- aic_list : iterable AIC values from set of candidat models Returns ------------- tuple First element contains the delta AIC values, second element ...
python
def AIC_compare(aic_list): """ Calculates delta AIC and AIC weights from a list of AIC values Parameters ----------------- aic_list : iterable AIC values from set of candidat models Returns ------------- tuple First element contains the delta AIC values, second element ...
[ "def", "AIC_compare", "(", "aic_list", ")", ":", "aic_values", "=", "np", ".", "array", "(", "aic_list", ")", "minimum", "=", "np", ".", "min", "(", "aic_values", ")", "delta", "=", "aic_values", "-", "minimum", "values", "=", "np", ".", "exp", "(", ...
Calculates delta AIC and AIC weights from a list of AIC values Parameters ----------------- aic_list : iterable AIC values from set of candidat models Returns ------------- tuple First element contains the delta AIC values, second element contains the relative AIC weigh...
[ "Calculates", "delta", "AIC", "and", "AIC", "weights", "from", "a", "list", "of", "AIC", "values" ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/compare/_compare.py#L224-L278
train
57,083
jkitzes/macroeco
macroeco/compare/_compare.py
sum_of_squares
def sum_of_squares(obs, pred): """ Sum of squares between observed and predicted data Parameters ---------- obs : iterable Observed data pred : iterable Predicted data Returns ------- float Sum of squares Notes ----- The length of observed and p...
python
def sum_of_squares(obs, pred): """ Sum of squares between observed and predicted data Parameters ---------- obs : iterable Observed data pred : iterable Predicted data Returns ------- float Sum of squares Notes ----- The length of observed and p...
[ "def", "sum_of_squares", "(", "obs", ",", "pred", ")", ":", "return", "np", ".", "sum", "(", "(", "np", ".", "array", "(", "obs", ")", "-", "np", ".", "array", "(", "pred", ")", ")", "**", "2", ")" ]
Sum of squares between observed and predicted data Parameters ---------- obs : iterable Observed data pred : iterable Predicted data Returns ------- float Sum of squares Notes ----- The length of observed and predicted data must match.
[ "Sum", "of", "squares", "between", "observed", "and", "predicted", "data" ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/compare/_compare.py#L281-L303
train
57,084
jkitzes/macroeco
macroeco/compare/_compare.py
r_squared
def r_squared(obs, pred, one_to_one=False, log_trans=False): """ R^2 value for a regression of observed and predicted data Parameters ---------- obs : iterable Observed data pred : iterable Predicted data one_to_one : bool If True, calculates the R^2 based on the one...
python
def r_squared(obs, pred, one_to_one=False, log_trans=False): """ R^2 value for a regression of observed and predicted data Parameters ---------- obs : iterable Observed data pred : iterable Predicted data one_to_one : bool If True, calculates the R^2 based on the one...
[ "def", "r_squared", "(", "obs", ",", "pred", ",", "one_to_one", "=", "False", ",", "log_trans", "=", "False", ")", ":", "if", "log_trans", ":", "obs", "=", "np", ".", "log", "(", "obs", ")", "pred", "=", "np", ".", "log", "(", "pred", ")", "if", ...
R^2 value for a regression of observed and predicted data Parameters ---------- obs : iterable Observed data pred : iterable Predicted data one_to_one : bool If True, calculates the R^2 based on the one-to-one line (see [#]_), and if False, calculates the standard R^...
[ "R^2", "value", "for", "a", "regression", "of", "observed", "and", "predicted", "data" ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/compare/_compare.py#L306-L384
train
57,085
jkitzes/macroeco
macroeco/compare/_compare.py
preston_bin
def preston_bin(data, max_num): """ Bins data on base 2 using Preston's method Parameters ---------- data : array-like Data to be binned max_num : float The maximum upper value of the data Returns ------- tuple (binned_data, bin_edges) Notes ----- ...
python
def preston_bin(data, max_num): """ Bins data on base 2 using Preston's method Parameters ---------- data : array-like Data to be binned max_num : float The maximum upper value of the data Returns ------- tuple (binned_data, bin_edges) Notes ----- ...
[ "def", "preston_bin", "(", "data", ",", "max_num", ")", ":", "log_ub", "=", "np", ".", "ceil", "(", "np", ".", "log2", "(", "max_num", ")", ")", "# Make an exclusive lower bound in keeping with Preston", "if", "log_ub", "==", "0", ":", "boundaries", "=", "np...
Bins data on base 2 using Preston's method Parameters ---------- data : array-like Data to be binned max_num : float The maximum upper value of the data Returns ------- tuple (binned_data, bin_edges) Notes ----- Uses Preston's method of binning, which ...
[ "Bins", "data", "on", "base", "2", "using", "Preston", "s", "method" ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/compare/_compare.py#L386-L440
train
57,086
consbio/parserutils
parserutils/urls.py
url_to_parts
def url_to_parts(url): """ Split url urlsplit style, but return path as a list and query as a dict """ if not url: return None scheme, netloc, path, query, fragment = _urlsplit(url) if not path or path == '/': path = [] else: path = path.strip('/').split('/') if not q...
python
def url_to_parts(url): """ Split url urlsplit style, but return path as a list and query as a dict """ if not url: return None scheme, netloc, path, query, fragment = _urlsplit(url) if not path or path == '/': path = [] else: path = path.strip('/').split('/') if not q...
[ "def", "url_to_parts", "(", "url", ")", ":", "if", "not", "url", ":", "return", "None", "scheme", ",", "netloc", ",", "path", ",", "query", ",", "fragment", "=", "_urlsplit", "(", "url", ")", "if", "not", "path", "or", "path", "==", "'/'", ":", "pa...
Split url urlsplit style, but return path as a list and query as a dict
[ "Split", "url", "urlsplit", "style", "but", "return", "path", "as", "a", "list", "and", "query", "as", "a", "dict" ]
f13f80db99ed43479336b116e38512e3566e4623
https://github.com/consbio/parserutils/blob/f13f80db99ed43479336b116e38512e3566e4623/parserutils/urls.py#L59-L77
train
57,087
flashashen/flange
flange/cfg.py
Cfg.__visit_index_model_instance
def __visit_index_model_instance(self, models, p, k, v): """ Called during model research on merged data """ # print 'model visit {} on {}'.format(model, v) cp = p + (k,) for model in models: try: if model.validator(v): ...
python
def __visit_index_model_instance(self, models, p, k, v): """ Called during model research on merged data """ # print 'model visit {} on {}'.format(model, v) cp = p + (k,) for model in models: try: if model.validator(v): ...
[ "def", "__visit_index_model_instance", "(", "self", ",", "models", ",", "p", ",", "k", ",", "v", ")", ":", "# print 'model visit {} on {}'.format(model, v)", "cp", "=", "p", "+", "(", "k", ",", ")", "for", "model", "in", "models", ":", "try", ":", "if", ...
Called during model research on merged data
[ "Called", "during", "model", "research", "on", "merged", "data" ]
67ebaf70e39887f65ce1163168d182a8e4c2774a
https://github.com/flashashen/flange/blob/67ebaf70e39887f65ce1163168d182a8e4c2774a/flange/cfg.py#L530-L547
train
57,088
Aluriak/bubble-tools
bubbletools/bbltree.py
BubbleTree.compute_edge_reduction
def compute_edge_reduction(self) -> float: """Compute the edge reduction. Costly computation""" nb_init_edge = self.init_edge_number() nb_poweredge = self.edge_number() return (nb_init_edge - nb_poweredge) / (nb_init_edge)
python
def compute_edge_reduction(self) -> float: """Compute the edge reduction. Costly computation""" nb_init_edge = self.init_edge_number() nb_poweredge = self.edge_number() return (nb_init_edge - nb_poweredge) / (nb_init_edge)
[ "def", "compute_edge_reduction", "(", "self", ")", "->", "float", ":", "nb_init_edge", "=", "self", ".", "init_edge_number", "(", ")", "nb_poweredge", "=", "self", ".", "edge_number", "(", ")", "return", "(", "nb_init_edge", "-", "nb_poweredge", ")", "/", "(...
Compute the edge reduction. Costly computation
[ "Compute", "the", "edge", "reduction", ".", "Costly", "computation" ]
f014f4a1986abefc80dc418feaa05ed258c2221a
https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/bbltree.py#L30-L34
train
57,089
Aluriak/bubble-tools
bubbletools/bbltree.py
BubbleTree.init_edge_number
def init_edge_number(self) -> int: """Return the number of edges present in the non-compressed graph""" return len(frozenset(frozenset(edge) for edge in self.initial_edges()))
python
def init_edge_number(self) -> int: """Return the number of edges present in the non-compressed graph""" return len(frozenset(frozenset(edge) for edge in self.initial_edges()))
[ "def", "init_edge_number", "(", "self", ")", "->", "int", ":", "return", "len", "(", "frozenset", "(", "frozenset", "(", "edge", ")", "for", "edge", "in", "self", ".", "initial_edges", "(", ")", ")", ")" ]
Return the number of edges present in the non-compressed graph
[ "Return", "the", "number", "of", "edges", "present", "in", "the", "non", "-", "compressed", "graph" ]
f014f4a1986abefc80dc418feaa05ed258c2221a
https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/bbltree.py#L36-L38
train
57,090
Aluriak/bubble-tools
bubbletools/bbltree.py
BubbleTree.assert_powernode
def assert_powernode(self, name:str) -> None or ValueError: """Do nothing if given name refers to a powernode in given graph. Raise a ValueError in any other case. """ if name not in self.inclusions: raise ValueError("Powernode '{}' does not exists.".format(name)) if...
python
def assert_powernode(self, name:str) -> None or ValueError: """Do nothing if given name refers to a powernode in given graph. Raise a ValueError in any other case. """ if name not in self.inclusions: raise ValueError("Powernode '{}' does not exists.".format(name)) if...
[ "def", "assert_powernode", "(", "self", ",", "name", ":", "str", ")", "->", "None", "or", "ValueError", ":", "if", "name", "not", "in", "self", ".", "inclusions", ":", "raise", "ValueError", "(", "\"Powernode '{}' does not exists.\"", ".", "format", "(", "na...
Do nothing if given name refers to a powernode in given graph. Raise a ValueError in any other case.
[ "Do", "nothing", "if", "given", "name", "refers", "to", "a", "powernode", "in", "given", "graph", ".", "Raise", "a", "ValueError", "in", "any", "other", "case", "." ]
f014f4a1986abefc80dc418feaa05ed258c2221a
https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/bbltree.py#L99-L107
train
57,091
Aluriak/bubble-tools
bubbletools/bbltree.py
BubbleTree.powernode_data
def powernode_data(self, name:str) -> Powernode: """Return a Powernode object describing the given powernode""" self.assert_powernode(name) contained_nodes = frozenset(self.nodes_in(name)) return Powernode( size=len(contained_nodes), contained=frozenset(self.all_i...
python
def powernode_data(self, name:str) -> Powernode: """Return a Powernode object describing the given powernode""" self.assert_powernode(name) contained_nodes = frozenset(self.nodes_in(name)) return Powernode( size=len(contained_nodes), contained=frozenset(self.all_i...
[ "def", "powernode_data", "(", "self", ",", "name", ":", "str", ")", "->", "Powernode", ":", "self", ".", "assert_powernode", "(", "name", ")", "contained_nodes", "=", "frozenset", "(", "self", ".", "nodes_in", "(", "name", ")", ")", "return", "Powernode", ...
Return a Powernode object describing the given powernode
[ "Return", "a", "Powernode", "object", "describing", "the", "given", "powernode" ]
f014f4a1986abefc80dc418feaa05ed258c2221a
https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/bbltree.py#L110-L119
train
57,092
Aluriak/bubble-tools
bubbletools/bbltree.py
BubbleTree.node_number
def node_number(self, *, count_pnode=True) -> int: """Return the number of node""" return (sum(1 for n in self.nodes()) + (sum(1 for n in self.powernodes()) if count_pnode else 0))
python
def node_number(self, *, count_pnode=True) -> int: """Return the number of node""" return (sum(1 for n in self.nodes()) + (sum(1 for n in self.powernodes()) if count_pnode else 0))
[ "def", "node_number", "(", "self", ",", "*", ",", "count_pnode", "=", "True", ")", "->", "int", ":", "return", "(", "sum", "(", "1", "for", "n", "in", "self", ".", "nodes", "(", ")", ")", "+", "(", "sum", "(", "1", "for", "n", "in", "self", "...
Return the number of node
[ "Return", "the", "number", "of", "node" ]
f014f4a1986abefc80dc418feaa05ed258c2221a
https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/bbltree.py#L122-L125
train
57,093
Aluriak/bubble-tools
bubbletools/bbltree.py
BubbleTree.write_bubble
def write_bubble(self, filename:str): """Write in given filename the lines of bubble describing this instance""" from bubbletools import converter converter.tree_to_bubble(self, filename)
python
def write_bubble(self, filename:str): """Write in given filename the lines of bubble describing this instance""" from bubbletools import converter converter.tree_to_bubble(self, filename)
[ "def", "write_bubble", "(", "self", ",", "filename", ":", "str", ")", ":", "from", "bubbletools", "import", "converter", "converter", ".", "tree_to_bubble", "(", "self", ",", "filename", ")" ]
Write in given filename the lines of bubble describing this instance
[ "Write", "in", "given", "filename", "the", "lines", "of", "bubble", "describing", "this", "instance" ]
f014f4a1986abefc80dc418feaa05ed258c2221a
https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/bbltree.py#L193-L196
train
57,094
Aluriak/bubble-tools
bubbletools/bbltree.py
BubbleTree.from_bubble_file
def from_bubble_file(bblfile:str, oriented:bool=False, symmetric_edges:bool=True) -> 'BubbleTree': """Extract data from given bubble file, then call from_bubble_data method """ return BubbleTree.from_bubble_data(utils.data_from_bubble(bblfile), ...
python
def from_bubble_file(bblfile:str, oriented:bool=False, symmetric_edges:bool=True) -> 'BubbleTree': """Extract data from given bubble file, then call from_bubble_data method """ return BubbleTree.from_bubble_data(utils.data_from_bubble(bblfile), ...
[ "def", "from_bubble_file", "(", "bblfile", ":", "str", ",", "oriented", ":", "bool", "=", "False", ",", "symmetric_edges", ":", "bool", "=", "True", ")", "->", "'BubbleTree'", ":", "return", "BubbleTree", ".", "from_bubble_data", "(", "utils", ".", "data_fro...
Extract data from given bubble file, then call from_bubble_data method
[ "Extract", "data", "from", "given", "bubble", "file", "then", "call", "from_bubble_data", "method" ]
f014f4a1986abefc80dc418feaa05ed258c2221a
https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/bbltree.py#L200-L207
train
57,095
Aluriak/bubble-tools
bubbletools/comparers.py
set_from_tree
def set_from_tree(root:str, graph:dict) -> frozenset: """Return a recursive structure describing given tree""" Node = namedtuple('Node', 'id succs') succs = graph[root] if succs: return (len(succs), sorted(tuple(set_from_tree(succ, graph) for succ in succs))) else: return 0, ()
python
def set_from_tree(root:str, graph:dict) -> frozenset: """Return a recursive structure describing given tree""" Node = namedtuple('Node', 'id succs') succs = graph[root] if succs: return (len(succs), sorted(tuple(set_from_tree(succ, graph) for succ in succs))) else: return 0, ()
[ "def", "set_from_tree", "(", "root", ":", "str", ",", "graph", ":", "dict", ")", "->", "frozenset", ":", "Node", "=", "namedtuple", "(", "'Node'", ",", "'id succs'", ")", "succs", "=", "graph", "[", "root", "]", "if", "succs", ":", "return", "(", "le...
Return a recursive structure describing given tree
[ "Return", "a", "recursive", "structure", "describing", "given", "tree" ]
f014f4a1986abefc80dc418feaa05ed258c2221a
https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/comparers.py#L27-L34
train
57,096
trevisanj/f311
f311/collaboration.py
get_suitable_vis_classes
def get_suitable_vis_classes(obj): """Retuns a list of Vis classes that can handle obj.""" ret = [] for class_ in classes_vis(): if isinstance(obj, class_.input_classes): ret.append(class_) return ret
python
def get_suitable_vis_classes(obj): """Retuns a list of Vis classes that can handle obj.""" ret = [] for class_ in classes_vis(): if isinstance(obj, class_.input_classes): ret.append(class_) return ret
[ "def", "get_suitable_vis_classes", "(", "obj", ")", ":", "ret", "=", "[", "]", "for", "class_", "in", "classes_vis", "(", ")", ":", "if", "isinstance", "(", "obj", ",", "class_", ".", "input_classes", ")", ":", "ret", ".", "append", "(", "class_", ")",...
Retuns a list of Vis classes that can handle obj.
[ "Retuns", "a", "list", "of", "Vis", "classes", "that", "can", "handle", "obj", "." ]
9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7
https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/collaboration.py#L51-L58
train
57,097
trevisanj/f311
f311/collaboration.py
get_suitable_vis_list_classes
def get_suitable_vis_list_classes(objs): """Retuns a list of VisList classes that can handle a list of objects.""" from f311 import explorer as ex ret = [] for class_ in classes_vis(): if isinstance(class_, ex.VisList): flag_can = True for obj in objs: i...
python
def get_suitable_vis_list_classes(objs): """Retuns a list of VisList classes that can handle a list of objects.""" from f311 import explorer as ex ret = [] for class_ in classes_vis(): if isinstance(class_, ex.VisList): flag_can = True for obj in objs: i...
[ "def", "get_suitable_vis_list_classes", "(", "objs", ")", ":", "from", "f311", "import", "explorer", "as", "ex", "ret", "=", "[", "]", "for", "class_", "in", "classes_vis", "(", ")", ":", "if", "isinstance", "(", "class_", ",", "ex", ".", "VisList", ")",...
Retuns a list of VisList classes that can handle a list of objects.
[ "Retuns", "a", "list", "of", "VisList", "classes", "that", "can", "handle", "a", "list", "of", "objects", "." ]
9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7
https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/collaboration.py#L61-L76
train
57,098
trevisanj/f311
f311/collaboration.py
_get_programs_dict
def _get_programs_dict(): """ Builds and returns programs dictionary This will have to import the packages in COLLABORATORS_S in order to get their absolute path. Returns: dictionary: {"packagename": [ExeInfo0, ...], ...} "packagename" examples: "f311.explorer", "numpy" """ global...
python
def _get_programs_dict(): """ Builds and returns programs dictionary This will have to import the packages in COLLABORATORS_S in order to get their absolute path. Returns: dictionary: {"packagename": [ExeInfo0, ...], ...} "packagename" examples: "f311.explorer", "numpy" """ global...
[ "def", "_get_programs_dict", "(", ")", ":", "global", "__programs_dict", "if", "__programs_dict", "is", "not", "None", ":", "return", "__programs_dict", "d", "=", "__programs_dict", "=", "OrderedDict", "(", ")", "for", "pkgname", "in", "COLLABORATORS_S", ":", "t...
Builds and returns programs dictionary This will have to import the packages in COLLABORATORS_S in order to get their absolute path. Returns: dictionary: {"packagename": [ExeInfo0, ...], ...} "packagename" examples: "f311.explorer", "numpy"
[ "Builds", "and", "returns", "programs", "dictionary" ]
9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7
https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/collaboration.py#L216-L245
train
57,099