id int32 0 252k | 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 list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
242,100 | lsst-sqre/sqre-apikit | apikit/convenience.py | raise_from_response | def raise_from_response(resp):
"""Turn a failed request response into a BackendError. Handy for
reflecting HTTP errors from farther back in the call chain.
Parameters
----------
resp: :class:`requests.Response`
Raises
------
:class:`apikit.BackendError`
If `resp.status_code` i... | python | def raise_from_response(resp):
"""Turn a failed request response into a BackendError. Handy for
reflecting HTTP errors from farther back in the call chain.
Parameters
----------
resp: :class:`requests.Response`
Raises
------
:class:`apikit.BackendError`
If `resp.status_code` i... | [
"def",
"raise_from_response",
"(",
"resp",
")",
":",
"if",
"resp",
".",
"status_code",
"<",
"400",
":",
"# Request was successful. Or at least, not a failure.",
"return",
"raise",
"BackendError",
"(",
"status_code",
"=",
"resp",
".",
"status_code",
",",
"reason",
"... | Turn a failed request response into a BackendError. Handy for
reflecting HTTP errors from farther back in the call chain.
Parameters
----------
resp: :class:`requests.Response`
Raises
------
:class:`apikit.BackendError`
If `resp.status_code` is equal to or greater than 400. | [
"Turn",
"a",
"failed",
"request",
"response",
"into",
"a",
"BackendError",
".",
"Handy",
"for",
"reflecting",
"HTTP",
"errors",
"from",
"farther",
"back",
"in",
"the",
"call",
"chain",
"."
] | ff505b63d2e29303ff7f05f2bd5eabd0f6d7026e | https://github.com/lsst-sqre/sqre-apikit/blob/ff505b63d2e29303ff7f05f2bd5eabd0f6d7026e/apikit/convenience.py#L262-L280 |
242,101 | lsst-sqre/sqre-apikit | apikit/convenience.py | get_logger | def get_logger(file=None, syslog=False, loghost=None, level=None):
"""Creates a logging object compatible with Python standard logging,
but which, as a `structlog` instance, emits JSON.
Parameters
----------
file: `None` or `str` (default `None`)
If given, send log output to file; otherw... | python | def get_logger(file=None, syslog=False, loghost=None, level=None):
"""Creates a logging object compatible with Python standard logging,
but which, as a `structlog` instance, emits JSON.
Parameters
----------
file: `None` or `str` (default `None`)
If given, send log output to file; otherw... | [
"def",
"get_logger",
"(",
"file",
"=",
"None",
",",
"syslog",
"=",
"False",
",",
"loghost",
"=",
"None",
",",
"level",
"=",
"None",
")",
":",
"if",
"not",
"syslog",
":",
"if",
"not",
"file",
":",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
... | Creates a logging object compatible with Python standard logging,
but which, as a `structlog` instance, emits JSON.
Parameters
----------
file: `None` or `str` (default `None`)
If given, send log output to file; otherwise, to `stdout`.
syslog: `bool` (default `False`)
If `True`, ... | [
"Creates",
"a",
"logging",
"object",
"compatible",
"with",
"Python",
"standard",
"logging",
"but",
"which",
"as",
"a",
"structlog",
"instance",
"emits",
"JSON",
"."
] | ff505b63d2e29303ff7f05f2bd5eabd0f6d7026e | https://github.com/lsst-sqre/sqre-apikit/blob/ff505b63d2e29303ff7f05f2bd5eabd0f6d7026e/apikit/convenience.py#L283-L348 |
242,102 | Deisss/python-sockjsroom | sockjsroom/httpJsonHandler.py | JsonDefaultHandler.getBody | def getBody(self):
""" Extract body json """
data = None
try:
data = json.loads(self.request.body)
except:
data = json.loads(urllib.unquote_plus(self.request.body))
return data | python | def getBody(self):
""" Extract body json """
data = None
try:
data = json.loads(self.request.body)
except:
data = json.loads(urllib.unquote_plus(self.request.body))
return data | [
"def",
"getBody",
"(",
"self",
")",
":",
"data",
"=",
"None",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"request",
".",
"body",
")",
"except",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"urllib",
".",
"unquote_plus",
"(",
... | Extract body json | [
"Extract",
"body",
"json"
] | 7c20187571d39e7fede848dc98f954235ca77241 | https://github.com/Deisss/python-sockjsroom/blob/7c20187571d39e7fede848dc98f954235ca77241/sockjsroom/httpJsonHandler.py#L25-L32 |
242,103 | Deisss/python-sockjsroom | sockjsroom/httpJsonHandler.py | JsonDefaultHandler.write | def write(self, obj):
""" Print object on output """
accept = self.request.headers.get("Accept")
if "json" in accept:
if JsonDefaultHandler.__parser is None:
JsonDefaultHandler.__parser = Parser()
super(JsonDefaultHandler, self).write(JsonDefaultHandler.__... | python | def write(self, obj):
""" Print object on output """
accept = self.request.headers.get("Accept")
if "json" in accept:
if JsonDefaultHandler.__parser is None:
JsonDefaultHandler.__parser = Parser()
super(JsonDefaultHandler, self).write(JsonDefaultHandler.__... | [
"def",
"write",
"(",
"self",
",",
"obj",
")",
":",
"accept",
"=",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"\"Accept\"",
")",
"if",
"\"json\"",
"in",
"accept",
":",
"if",
"JsonDefaultHandler",
".",
"__parser",
"is",
"None",
":",
"JsonDe... | Print object on output | [
"Print",
"object",
"on",
"output"
] | 7c20187571d39e7fede848dc98f954235ca77241 | https://github.com/Deisss/python-sockjsroom/blob/7c20187571d39e7fede848dc98f954235ca77241/sockjsroom/httpJsonHandler.py#L34-L43 |
242,104 | funkybob/antfarm | antfarm/request.py | Request.raw_cookies | def raw_cookies(self):
'''Raw access to cookies'''
cookie_data = self.environ.get('HTTP_COOKIE', '')
cookies = SimpleCookie()
if not cookie_data:
return cookies
cookies.load(cookie_data)
return cookies | python | def raw_cookies(self):
'''Raw access to cookies'''
cookie_data = self.environ.get('HTTP_COOKIE', '')
cookies = SimpleCookie()
if not cookie_data:
return cookies
cookies.load(cookie_data)
return cookies | [
"def",
"raw_cookies",
"(",
"self",
")",
":",
"cookie_data",
"=",
"self",
".",
"environ",
".",
"get",
"(",
"'HTTP_COOKIE'",
",",
"''",
")",
"cookies",
"=",
"SimpleCookie",
"(",
")",
"if",
"not",
"cookie_data",
":",
"return",
"cookies",
"cookies",
".",
"lo... | Raw access to cookies | [
"Raw",
"access",
"to",
"cookies"
] | 40a7cc450eba09a280b7bc8f7c68a807b0177c62 | https://github.com/funkybob/antfarm/blob/40a7cc450eba09a280b7bc8f7c68a807b0177c62/antfarm/request.py#L22-L29 |
242,105 | funkybob/antfarm | antfarm/request.py | Request.cookies | def cookies(self):
'''Simplified Cookie access'''
return {
key: self.raw_cookies[key].value
for key in self.raw_cookies.keys()
} | python | def cookies(self):
'''Simplified Cookie access'''
return {
key: self.raw_cookies[key].value
for key in self.raw_cookies.keys()
} | [
"def",
"cookies",
"(",
"self",
")",
":",
"return",
"{",
"key",
":",
"self",
".",
"raw_cookies",
"[",
"key",
"]",
".",
"value",
"for",
"key",
"in",
"self",
".",
"raw_cookies",
".",
"keys",
"(",
")",
"}"
] | Simplified Cookie access | [
"Simplified",
"Cookie",
"access"
] | 40a7cc450eba09a280b7bc8f7c68a807b0177c62 | https://github.com/funkybob/antfarm/blob/40a7cc450eba09a280b7bc8f7c68a807b0177c62/antfarm/request.py#L32-L37 |
242,106 | honzamach/pynspect | pynspect/benchmark/bench_jpath.py | random_jpath | def random_jpath(depth = 3):
"""
Generate random JPath with given node depth.
"""
chunks = []
while depth > 0:
length = random.randint(5, 15)
ident = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for _ in range(length))
if random.choice((True, False)... | python | def random_jpath(depth = 3):
"""
Generate random JPath with given node depth.
"""
chunks = []
while depth > 0:
length = random.randint(5, 15)
ident = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for _ in range(length))
if random.choice((True, False)... | [
"def",
"random_jpath",
"(",
"depth",
"=",
"3",
")",
":",
"chunks",
"=",
"[",
"]",
"while",
"depth",
">",
"0",
":",
"length",
"=",
"random",
".",
"randint",
"(",
"5",
",",
"15",
")",
"ident",
"=",
"''",
".",
"join",
"(",
"random",
".",
"choice",
... | Generate random JPath with given node depth. | [
"Generate",
"random",
"JPath",
"with",
"given",
"node",
"depth",
"."
] | 0582dcc1f7aafe50e25a21c792ea1b3367ea5881 | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/benchmark/bench_jpath.py#L36-L49 |
242,107 | praekelt/jmbo-twitter | jmbo_twitter/admin_views.py | feed_fetch_force | def feed_fetch_force(request, id, redirect_to):
"""Forcibly fetch tweets for the feed"""
feed = Feed.objects.get(id=id)
feed.fetch(force=True)
msg = _("Fetched tweets for %s" % feed.name)
messages.success(request, msg, fail_silently=True)
return HttpResponseRedirect(redirect_to) | python | def feed_fetch_force(request, id, redirect_to):
"""Forcibly fetch tweets for the feed"""
feed = Feed.objects.get(id=id)
feed.fetch(force=True)
msg = _("Fetched tweets for %s" % feed.name)
messages.success(request, msg, fail_silently=True)
return HttpResponseRedirect(redirect_to) | [
"def",
"feed_fetch_force",
"(",
"request",
",",
"id",
",",
"redirect_to",
")",
":",
"feed",
"=",
"Feed",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"id",
")",
"feed",
".",
"fetch",
"(",
"force",
"=",
"True",
")",
"msg",
"=",
"_",
"(",
"\"Fetched t... | Forcibly fetch tweets for the feed | [
"Forcibly",
"fetch",
"tweets",
"for",
"the",
"feed"
] | 12e8eb08efcbc9d1423fc213b2f2d9d7fed8a775 | https://github.com/praekelt/jmbo-twitter/blob/12e8eb08efcbc9d1423fc213b2f2d9d7fed8a775/jmbo_twitter/admin_views.py#L12-L18 |
242,108 | praekelt/jmbo-twitter | jmbo_twitter/admin_views.py | search_fetch_force | def search_fetch_force(request, id, redirect_to):
"""Forcibly fetch tweets for the search"""
search = Search.objects.get(id=id)
search.fetch(force=True)
msg = _("Fetched tweets for %s" % search.criteria)
messages.success(request, msg, fail_silently=True)
return HttpResponseRedirect(redirect_to) | python | def search_fetch_force(request, id, redirect_to):
"""Forcibly fetch tweets for the search"""
search = Search.objects.get(id=id)
search.fetch(force=True)
msg = _("Fetched tweets for %s" % search.criteria)
messages.success(request, msg, fail_silently=True)
return HttpResponseRedirect(redirect_to) | [
"def",
"search_fetch_force",
"(",
"request",
",",
"id",
",",
"redirect_to",
")",
":",
"search",
"=",
"Search",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"id",
")",
"search",
".",
"fetch",
"(",
"force",
"=",
"True",
")",
"msg",
"=",
"_",
"(",
"\"F... | Forcibly fetch tweets for the search | [
"Forcibly",
"fetch",
"tweets",
"for",
"the",
"search"
] | 12e8eb08efcbc9d1423fc213b2f2d9d7fed8a775 | https://github.com/praekelt/jmbo-twitter/blob/12e8eb08efcbc9d1423fc213b2f2d9d7fed8a775/jmbo_twitter/admin_views.py#L32-L38 |
242,109 | Rafiot/PubSubLogger | pubsublogger/publisher.py | __connect | def __connect():
"""
Connect to a redis instance.
"""
global redis_instance
if use_tcp_socket:
redis_instance = redis.StrictRedis(host=hostname, port=port)
else:
redis_instance = redis.StrictRedis(unix_socket_path=unix_socket) | python | def __connect():
"""
Connect to a redis instance.
"""
global redis_instance
if use_tcp_socket:
redis_instance = redis.StrictRedis(host=hostname, port=port)
else:
redis_instance = redis.StrictRedis(unix_socket_path=unix_socket) | [
"def",
"__connect",
"(",
")",
":",
"global",
"redis_instance",
"if",
"use_tcp_socket",
":",
"redis_instance",
"=",
"redis",
".",
"StrictRedis",
"(",
"host",
"=",
"hostname",
",",
"port",
"=",
"port",
")",
"else",
":",
"redis_instance",
"=",
"redis",
".",
"... | Connect to a redis instance. | [
"Connect",
"to",
"a",
"redis",
"instance",
"."
] | 4f28ad673f42ee2ec7792d414d325aef9a56da53 | https://github.com/Rafiot/PubSubLogger/blob/4f28ad673f42ee2ec7792d414d325aef9a56da53/pubsublogger/publisher.py#L35-L43 |
242,110 | Rafiot/PubSubLogger | pubsublogger/publisher.py | log | def log(level, message):
"""
Publish `message` with the `level` the redis `channel`.
:param level: the level of the message
:param message: the message you want to log
"""
if redis_instance is None:
__connect()
if level not in __error_levels:
raise InvalidErrorLevel('You ha... | python | def log(level, message):
"""
Publish `message` with the `level` the redis `channel`.
:param level: the level of the message
:param message: the message you want to log
"""
if redis_instance is None:
__connect()
if level not in __error_levels:
raise InvalidErrorLevel('You ha... | [
"def",
"log",
"(",
"level",
",",
"message",
")",
":",
"if",
"redis_instance",
"is",
"None",
":",
"__connect",
"(",
")",
"if",
"level",
"not",
"in",
"__error_levels",
":",
"raise",
"InvalidErrorLevel",
"(",
"'You have used an invalid error level. \\\n ... | Publish `message` with the `level` the redis `channel`.
:param level: the level of the message
:param message: the message you want to log | [
"Publish",
"message",
"with",
"the",
"level",
"the",
"redis",
"channel",
"."
] | 4f28ad673f42ee2ec7792d414d325aef9a56da53 | https://github.com/Rafiot/PubSubLogger/blob/4f28ad673f42ee2ec7792d414d325aef9a56da53/pubsublogger/publisher.py#L46-L62 |
242,111 | JNRowe/jnrbase | jnrbase/httplib2_certs.py | find_certs | def find_certs() -> str:
"""Find suitable certificates for ``httplib2``.
Warning:
The default behaviour is to fall back to the bundled certificates when
no system certificates can be found. If you're packaging ``jnrbase``
*please* set ``ALLOW_FALLBACK`` to ``False`` to disable this ver... | python | def find_certs() -> str:
"""Find suitable certificates for ``httplib2``.
Warning:
The default behaviour is to fall back to the bundled certificates when
no system certificates can be found. If you're packaging ``jnrbase``
*please* set ``ALLOW_FALLBACK`` to ``False`` to disable this ver... | [
"def",
"find_certs",
"(",
")",
"->",
"str",
":",
"bundle",
"=",
"path",
".",
"realpath",
"(",
"path",
".",
"dirname",
"(",
"httplib2",
".",
"CA_CERTS",
")",
")",
"# Some distros symlink the bundled path location to the system certs",
"if",
"not",
"bundle",
".",
... | Find suitable certificates for ``httplib2``.
Warning:
The default behaviour is to fall back to the bundled certificates when
no system certificates can be found. If you're packaging ``jnrbase``
*please* set ``ALLOW_FALLBACK`` to ``False`` to disable this very much
unwanted behaviou... | [
"Find",
"suitable",
"certificates",
"for",
"httplib2",
"."
] | ae505ef69a9feb739b5f4e62c5a8e6533104d3ea | https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/httplib2_certs.py#L41-L76 |
242,112 | tBaxter/tango-articles | build/lib/articles/models.py | Article.get_absolute_url | def get_absolute_url(self):
"""
If override_url was given, use that.
Otherwise, if the content belongs to a blog, use a blog url.
If not, use a regular article url.
"""
if self.override_url:
return self.override_url
if self.destination.is_blog:... | python | def get_absolute_url(self):
"""
If override_url was given, use that.
Otherwise, if the content belongs to a blog, use a blog url.
If not, use a regular article url.
"""
if self.override_url:
return self.override_url
if self.destination.is_blog:... | [
"def",
"get_absolute_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"override_url",
":",
"return",
"self",
".",
"override_url",
"if",
"self",
".",
"destination",
".",
"is_blog",
":",
"return",
"reverse",
"(",
"'blog_entry_detail'",
",",
"args",
"=",
"[",
... | If override_url was given, use that.
Otherwise, if the content belongs to a blog, use a blog url.
If not, use a regular article url. | [
"If",
"override_url",
"was",
"given",
"use",
"that",
".",
"Otherwise",
"if",
"the",
"content",
"belongs",
"to",
"a",
"blog",
"use",
"a",
"blog",
"url",
".",
"If",
"not",
"use",
"a",
"regular",
"article",
"url",
"."
] | 93818dcca1b62042a4fc19af63474691b0fe931c | https://github.com/tBaxter/tango-articles/blob/93818dcca1b62042a4fc19af63474691b0fe931c/build/lib/articles/models.py#L183-L193 |
242,113 | tBaxter/tango-articles | build/lib/articles/models.py | Article.save | def save(self, *args, **kwargs):
"""
Store summary if none was given
and created formatted version of body text.
"""
if not self.summary:
self.summary = truncatewords(self.body, 50)
self.body_formatted = sanetize_text(self.body)
super(Article, ... | python | def save(self, *args, **kwargs):
"""
Store summary if none was given
and created formatted version of body text.
"""
if not self.summary:
self.summary = truncatewords(self.body, 50)
self.body_formatted = sanetize_text(self.body)
super(Article, ... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"summary",
":",
"self",
".",
"summary",
"=",
"truncatewords",
"(",
"self",
".",
"body",
",",
"50",
")",
"self",
".",
"body_formatted",
"=",
... | Store summary if none was given
and created formatted version of body text. | [
"Store",
"summary",
"if",
"none",
"was",
"given",
"and",
"created",
"formatted",
"version",
"of",
"body",
"text",
"."
] | 93818dcca1b62042a4fc19af63474691b0fe931c | https://github.com/tBaxter/tango-articles/blob/93818dcca1b62042a4fc19af63474691b0fe931c/build/lib/articles/models.py#L195-L203 |
242,114 | bsvetchine/django-payzen | django_payzen/models.py | PaymentRequest.set_vads_payment_config | def set_vads_payment_config(self):
"""
vads_payment_config can be set only after object saving.
A custom payment config can be set once PaymentRequest saved
(adding elements to the m2m relationship). As a consequence
we set vads_payment_config just before sending data elements
... | python | def set_vads_payment_config(self):
"""
vads_payment_config can be set only after object saving.
A custom payment config can be set once PaymentRequest saved
(adding elements to the m2m relationship). As a consequence
we set vads_payment_config just before sending data elements
... | [
"def",
"set_vads_payment_config",
"(",
"self",
")",
":",
"self",
".",
"vads_payment_config",
"=",
"tools",
".",
"get_vads_payment_config",
"(",
"self",
".",
"payment_config",
",",
"self",
".",
"custom_payment_config",
".",
"all",
"(",
")",
")"
] | vads_payment_config can be set only after object saving.
A custom payment config can be set once PaymentRequest saved
(adding elements to the m2m relationship). As a consequence
we set vads_payment_config just before sending data elements
to payzen. | [
"vads_payment_config",
"can",
"be",
"set",
"only",
"after",
"object",
"saving",
"."
] | 944c3026120151495310cb1eb3c6370dc2db3db9 | https://github.com/bsvetchine/django-payzen/blob/944c3026120151495310cb1eb3c6370dc2db3db9/django_payzen/models.py#L407-L416 |
242,115 | bsvetchine/django-payzen | django_payzen/models.py | PaymentRequest.save | def save(self):
"""
We set up vads_trans_id and theme according to payzen format.
If fields values are explicitely set by user, we do not override
their values.
"""
if not self.vads_trans_date:
self.vads_trans_date = datetime.datetime.utcnow().replace(
... | python | def save(self):
"""
We set up vads_trans_id and theme according to payzen format.
If fields values are explicitely set by user, we do not override
their values.
"""
if not self.vads_trans_date:
self.vads_trans_date = datetime.datetime.utcnow().replace(
... | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"vads_trans_date",
":",
"self",
".",
"vads_trans_date",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"utc",
")",
".",
"strftime",
"(",
"... | We set up vads_trans_id and theme according to payzen format.
If fields values are explicitely set by user, we do not override
their values. | [
"We",
"set",
"up",
"vads_trans_id",
"and",
"theme",
"according",
"to",
"payzen",
"format",
"."
] | 944c3026120151495310cb1eb3c6370dc2db3db9 | https://github.com/bsvetchine/django-payzen/blob/944c3026120151495310cb1eb3c6370dc2db3db9/django_payzen/models.py#L435-L454 |
242,116 | casebeer/factual | factual/v2/responses.py | V2ReadResponse.records | def records(self):
'''Return a list of dicts corresponding to the data returned by Factual.'''
if self._records == None:
self._records = self._get_records()
return self._records | python | def records(self):
'''Return a list of dicts corresponding to the data returned by Factual.'''
if self._records == None:
self._records = self._get_records()
return self._records | [
"def",
"records",
"(",
"self",
")",
":",
"if",
"self",
".",
"_records",
"==",
"None",
":",
"self",
".",
"_records",
"=",
"self",
".",
"_get_records",
"(",
")",
"return",
"self",
".",
"_records"
] | Return a list of dicts corresponding to the data returned by Factual. | [
"Return",
"a",
"list",
"of",
"dicts",
"corresponding",
"to",
"the",
"data",
"returned",
"by",
"Factual",
"."
] | f2795a8c9fd447c5d62887ae0f960481ce13be84 | https://github.com/casebeer/factual/blob/f2795a8c9fd447c5d62887ae0f960481ce13be84/factual/v2/responses.py#L20-L24 |
242,117 | Fuyukai/ConfigMaster | configmaster/ConfigGenerator.py | GenerateConfigFile | def GenerateConfigFile(load_hook, dump_hook, **kwargs) -> ConfigFile:
"""
Generates a ConfigFile object using the specified hooks.
These hooks should be functions, and have one argument.
When a hook is called, the ConfigFile object is passed to it. Use this to load your data from the fd object, or requ... | python | def GenerateConfigFile(load_hook, dump_hook, **kwargs) -> ConfigFile:
"""
Generates a ConfigFile object using the specified hooks.
These hooks should be functions, and have one argument.
When a hook is called, the ConfigFile object is passed to it. Use this to load your data from the fd object, or requ... | [
"def",
"GenerateConfigFile",
"(",
"load_hook",
",",
"dump_hook",
",",
"*",
"*",
"kwargs",
")",
"->",
"ConfigFile",
":",
"def",
"ConfigFileGenerator",
"(",
"filename",
",",
"safe_load",
":",
"bool",
"=",
"True",
")",
":",
"cfg",
"=",
"ConfigFile",
"(",
"fd"... | Generates a ConfigFile object using the specified hooks.
These hooks should be functions, and have one argument.
When a hook is called, the ConfigFile object is passed to it. Use this to load your data from the fd object, or request, or whatever.
This returns a ConfigFile object. | [
"Generates",
"a",
"ConfigFile",
"object",
"using",
"the",
"specified",
"hooks",
"."
] | 8018aa415da55c84edaa8a49664f674758a14edd | https://github.com/Fuyukai/ConfigMaster/blob/8018aa415da55c84edaa8a49664f674758a14edd/configmaster/ConfigGenerator.py#L3-L16 |
242,118 | Fuyukai/ConfigMaster | configmaster/ConfigGenerator.py | GenerateNetworkedConfigFile | def GenerateNetworkedConfigFile(load_hook, normal_class_load_hook, normal_class_dump_hook, **kwargs) -> NetworkedConfigObject:
"""
Generates a NetworkedConfigObject using the specified hooks.
"""
def NetworkedConfigObjectGenerator(url, safe_load: bool=True):
cfg = NetworkedConfigObject(url=url, ... | python | def GenerateNetworkedConfigFile(load_hook, normal_class_load_hook, normal_class_dump_hook, **kwargs) -> NetworkedConfigObject:
"""
Generates a NetworkedConfigObject using the specified hooks.
"""
def NetworkedConfigObjectGenerator(url, safe_load: bool=True):
cfg = NetworkedConfigObject(url=url, ... | [
"def",
"GenerateNetworkedConfigFile",
"(",
"load_hook",
",",
"normal_class_load_hook",
",",
"normal_class_dump_hook",
",",
"*",
"*",
"kwargs",
")",
"->",
"NetworkedConfigObject",
":",
"def",
"NetworkedConfigObjectGenerator",
"(",
"url",
",",
"safe_load",
":",
"bool",
... | Generates a NetworkedConfigObject using the specified hooks. | [
"Generates",
"a",
"NetworkedConfigObject",
"using",
"the",
"specified",
"hooks",
"."
] | 8018aa415da55c84edaa8a49664f674758a14edd | https://github.com/Fuyukai/ConfigMaster/blob/8018aa415da55c84edaa8a49664f674758a14edd/configmaster/ConfigGenerator.py#L18-L28 |
242,119 | Meseira/subordinate | subordinate/idrangeset.py | IdRangeSet.append | def append(self, first, count):
"""
Add to the set a range of count consecutive ids
starting at id first.
"""
self.__range.append(IdRange(first, count)) | python | def append(self, first, count):
"""
Add to the set a range of count consecutive ids
starting at id first.
"""
self.__range.append(IdRange(first, count)) | [
"def",
"append",
"(",
"self",
",",
"first",
",",
"count",
")",
":",
"self",
".",
"__range",
".",
"append",
"(",
"IdRange",
"(",
"first",
",",
"count",
")",
")"
] | Add to the set a range of count consecutive ids
starting at id first. | [
"Add",
"to",
"the",
"set",
"a",
"range",
"of",
"count",
"consecutive",
"ids",
"starting",
"at",
"id",
"first",
"."
] | 3438df304af3dccc5bd1515231402afa708f1cc3 | https://github.com/Meseira/subordinate/blob/3438df304af3dccc5bd1515231402afa708f1cc3/subordinate/idrangeset.py#L90-L96 |
242,120 | Meseira/subordinate | subordinate/idrangeset.py | IdRangeSet.remove | def remove(self, first, count):
"""
Remove a range of count consecutive ids starting at id first
from all the ranges in the set.
"""
# Avoid trivialities
if first < 0 or count < 1:
return
new_range = []
last = first + count - 1
for r ... | python | def remove(self, first, count):
"""
Remove a range of count consecutive ids starting at id first
from all the ranges in the set.
"""
# Avoid trivialities
if first < 0 or count < 1:
return
new_range = []
last = first + count - 1
for r ... | [
"def",
"remove",
"(",
"self",
",",
"first",
",",
"count",
")",
":",
"# Avoid trivialities",
"if",
"first",
"<",
"0",
"or",
"count",
"<",
"1",
":",
"return",
"new_range",
"=",
"[",
"]",
"last",
"=",
"first",
"+",
"count",
"-",
"1",
"for",
"r",
"in",... | Remove a range of count consecutive ids starting at id first
from all the ranges in the set. | [
"Remove",
"a",
"range",
"of",
"count",
"consecutive",
"ids",
"starting",
"at",
"id",
"first",
"from",
"all",
"the",
"ranges",
"in",
"the",
"set",
"."
] | 3438df304af3dccc5bd1515231402afa708f1cc3 | https://github.com/Meseira/subordinate/blob/3438df304af3dccc5bd1515231402afa708f1cc3/subordinate/idrangeset.py#L103-L126 |
242,121 | Meseira/subordinate | subordinate/idrangeset.py | IdRangeSet.simplify | def simplify(self):
"""
Reorganize the ranges in the set in order to ensure that each range
is unique and that there is not overlap between to ranges.
"""
# Sort the ranges
self.__range.sort()
new_range = []
new_first = self.__range[0].first
new_... | python | def simplify(self):
"""
Reorganize the ranges in the set in order to ensure that each range
is unique and that there is not overlap between to ranges.
"""
# Sort the ranges
self.__range.sort()
new_range = []
new_first = self.__range[0].first
new_... | [
"def",
"simplify",
"(",
"self",
")",
":",
"# Sort the ranges",
"self",
".",
"__range",
".",
"sort",
"(",
")",
"new_range",
"=",
"[",
"]",
"new_first",
"=",
"self",
".",
"__range",
"[",
"0",
"]",
".",
"first",
"new_count",
"=",
"self",
".",
"__range",
... | Reorganize the ranges in the set in order to ensure that each range
is unique and that there is not overlap between to ranges. | [
"Reorganize",
"the",
"ranges",
"in",
"the",
"set",
"in",
"order",
"to",
"ensure",
"that",
"each",
"range",
"is",
"unique",
"and",
"that",
"there",
"is",
"not",
"overlap",
"between",
"to",
"ranges",
"."
] | 3438df304af3dccc5bd1515231402afa708f1cc3 | https://github.com/Meseira/subordinate/blob/3438df304af3dccc5bd1515231402afa708f1cc3/subordinate/idrangeset.py#L128-L159 |
242,122 | fixmydjango/fixmydjango-lib | fixmydjango/__init__.py | ExceptionReporterPatch._get_fix_my_django_submission_url | def _get_fix_my_django_submission_url(self, tb_info, sanitized_tb):
"""
Links to the error submission url with pre filled fields
"""
err_post_create_path = '/create/'
url = '{0}{1}'.format(base_url, err_post_create_path)
return '{url}?{query}'.format(
url=url,... | python | def _get_fix_my_django_submission_url(self, tb_info, sanitized_tb):
"""
Links to the error submission url with pre filled fields
"""
err_post_create_path = '/create/'
url = '{0}{1}'.format(base_url, err_post_create_path)
return '{url}?{query}'.format(
url=url,... | [
"def",
"_get_fix_my_django_submission_url",
"(",
"self",
",",
"tb_info",
",",
"sanitized_tb",
")",
":",
"err_post_create_path",
"=",
"'/create/'",
"url",
"=",
"'{0}{1}'",
".",
"format",
"(",
"base_url",
",",
"err_post_create_path",
")",
"return",
"'{url}?{query}'",
... | Links to the error submission url with pre filled fields | [
"Links",
"to",
"the",
"error",
"submission",
"url",
"with",
"pre",
"filled",
"fields"
] | 5402e9cb15d85daa68bb5f2418ff9c4ea966d306 | https://github.com/fixmydjango/fixmydjango-lib/blob/5402e9cb15d85daa68bb5f2418ff9c4ea966d306/fixmydjango/__init__.py#L62-L75 |
242,123 | iamFIREcracker/aadbook | aadbook/config.py | _get_config | def _get_config(config_file):
'''find, read and parse configuraton.'''
parser = ConfigParser.SafeConfigParser()
if os.path.lexists(config_file):
try:
log.info('Reading config: %s', config_file)
inp = open(config_file)
parser.readfp(inp)
return parser
... | python | def _get_config(config_file):
'''find, read and parse configuraton.'''
parser = ConfigParser.SafeConfigParser()
if os.path.lexists(config_file):
try:
log.info('Reading config: %s', config_file)
inp = open(config_file)
parser.readfp(inp)
return parser
... | [
"def",
"_get_config",
"(",
"config_file",
")",
":",
"parser",
"=",
"ConfigParser",
".",
"SafeConfigParser",
"(",
")",
"if",
"os",
".",
"path",
".",
"lexists",
"(",
"config_file",
")",
":",
"try",
":",
"log",
".",
"info",
"(",
"'Reading config: %s'",
",",
... | find, read and parse configuraton. | [
"find",
"read",
"and",
"parse",
"configuraton",
"."
] | d191e9d36a2309449ab91c1728eaf5901b7ef91c | https://github.com/iamFIREcracker/aadbook/blob/d191e9d36a2309449ab91c1728eaf5901b7ef91c/aadbook/config.py#L65-L76 |
242,124 | bretth/djset | djset/utils.py | getbool | def getbool(key, default=False):
"""
Returns True or False for any TRUE, FALSE, 0, or 1.
Other values return default.
"""
value = os.getenv(key)
if value and value.lower() in ('true', '1'):
value = True
elif value and value.lower() in ('false', '0'):
value = False
else:
... | python | def getbool(key, default=False):
"""
Returns True or False for any TRUE, FALSE, 0, or 1.
Other values return default.
"""
value = os.getenv(key)
if value and value.lower() in ('true', '1'):
value = True
elif value and value.lower() in ('false', '0'):
value = False
else:
... | [
"def",
"getbool",
"(",
"key",
",",
"default",
"=",
"False",
")",
":",
"value",
"=",
"os",
".",
"getenv",
"(",
"key",
")",
"if",
"value",
"and",
"value",
".",
"lower",
"(",
")",
"in",
"(",
"'true'",
",",
"'1'",
")",
":",
"value",
"=",
"True",
"e... | Returns True or False for any TRUE, FALSE, 0, or 1.
Other values return default. | [
"Returns",
"True",
"or",
"False",
"for",
"any",
"TRUE",
"FALSE",
"0",
"or",
"1",
".",
"Other",
"values",
"return",
"default",
"."
] | e04cbcadc311f6edec50a718415d0004aa304034 | https://github.com/bretth/djset/blob/e04cbcadc311f6edec50a718415d0004aa304034/djset/utils.py#L4-L16 |
242,125 | bretth/djset | djset/utils.py | _locate_settings | def _locate_settings(settings=''):
"Return the path to the DJANGO_SETTINGS_MODULE"
import imp
import sys
sys.path.append(os.getcwd())
settings = settings or os.getenv('DJANGO_SETTINGS_MODULE')
if settings:
parts = settings.split('.')
f = imp.find_module(parts[0])[1]
args... | python | def _locate_settings(settings=''):
"Return the path to the DJANGO_SETTINGS_MODULE"
import imp
import sys
sys.path.append(os.getcwd())
settings = settings or os.getenv('DJANGO_SETTINGS_MODULE')
if settings:
parts = settings.split('.')
f = imp.find_module(parts[0])[1]
args... | [
"def",
"_locate_settings",
"(",
"settings",
"=",
"''",
")",
":",
"import",
"imp",
"import",
"sys",
"sys",
".",
"path",
".",
"append",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
"settings",
"=",
"settings",
"or",
"os",
".",
"getenv",
"(",
"'DJANGO_SETTING... | Return the path to the DJANGO_SETTINGS_MODULE | [
"Return",
"the",
"path",
"to",
"the",
"DJANGO_SETTINGS_MODULE"
] | e04cbcadc311f6edec50a718415d0004aa304034 | https://github.com/bretth/djset/blob/e04cbcadc311f6edec50a718415d0004aa304034/djset/utils.py#L19-L33 |
242,126 | saltzm/yadi | yadi/datalog2sql/ast2sql/sql_generator.py | ConjunctiveQuerySQLGenerator.get_from_relations | def get_from_relations(self, query,aliases):
'''
Returns list of the names of all positive relations in the query
'''
return [aliases[rel.get_name()] for rel in query.get_relations() if not rel.is_negated()] | python | def get_from_relations(self, query,aliases):
'''
Returns list of the names of all positive relations in the query
'''
return [aliases[rel.get_name()] for rel in query.get_relations() if not rel.is_negated()] | [
"def",
"get_from_relations",
"(",
"self",
",",
"query",
",",
"aliases",
")",
":",
"return",
"[",
"aliases",
"[",
"rel",
".",
"get_name",
"(",
")",
"]",
"for",
"rel",
"in",
"query",
".",
"get_relations",
"(",
")",
"if",
"not",
"rel",
".",
"is_negated",
... | Returns list of the names of all positive relations in the query | [
"Returns",
"list",
"of",
"the",
"names",
"of",
"all",
"positive",
"relations",
"in",
"the",
"query"
] | 755790167c350e650c1e8b15c6f9209a97be9e42 | https://github.com/saltzm/yadi/blob/755790167c350e650c1e8b15c6f9209a97be9e42/yadi/datalog2sql/ast2sql/sql_generator.py#L181-L185 |
242,127 | gear11/pypelogs | pypein/flickr.py | Flickr.photo | def photo(self, args):
"""
Retrieves metadata for a specific photo.
flickr:(credsfile),photo,(photo_id)
"""
rsp = self._load_rsp(self.flickr.photos_getInfo(photo_id=args[0]))
p = rsp['photo']
yield self._prep(p) | python | def photo(self, args):
"""
Retrieves metadata for a specific photo.
flickr:(credsfile),photo,(photo_id)
"""
rsp = self._load_rsp(self.flickr.photos_getInfo(photo_id=args[0]))
p = rsp['photo']
yield self._prep(p) | [
"def",
"photo",
"(",
"self",
",",
"args",
")",
":",
"rsp",
"=",
"self",
".",
"_load_rsp",
"(",
"self",
".",
"flickr",
".",
"photos_getInfo",
"(",
"photo_id",
"=",
"args",
"[",
"0",
"]",
")",
")",
"p",
"=",
"rsp",
"[",
"'photo'",
"]",
"yield",
"se... | Retrieves metadata for a specific photo.
flickr:(credsfile),photo,(photo_id) | [
"Retrieves",
"metadata",
"for",
"a",
"specific",
"photo",
"."
] | da5dc0fee5373a4be294798b5e32cd0a803d8bbe | https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L58-L66 |
242,128 | gear11/pypelogs | pypein/flickr.py | Flickr.interesting | def interesting(self, args=None):
"""
Gets interesting photos.
flickr:(credsfile),interesting
"""
kwargs = {'extras': ','.join(args) if args else 'last_update,geo,owner_name,url_sq'}
return self._paged_api_call(self.flickr.interestingness_getList, kwargs) | python | def interesting(self, args=None):
"""
Gets interesting photos.
flickr:(credsfile),interesting
"""
kwargs = {'extras': ','.join(args) if args else 'last_update,geo,owner_name,url_sq'}
return self._paged_api_call(self.flickr.interestingness_getList, kwargs) | [
"def",
"interesting",
"(",
"self",
",",
"args",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"'extras'",
":",
"','",
".",
"join",
"(",
"args",
")",
"if",
"args",
"else",
"'last_update,geo,owner_name,url_sq'",
"}",
"return",
"self",
".",
"_paged_api_call",
"(... | Gets interesting photos.
flickr:(credsfile),interesting | [
"Gets",
"interesting",
"photos",
"."
] | da5dc0fee5373a4be294798b5e32cd0a803d8bbe | https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L80-L88 |
242,129 | gear11/pypelogs | pypein/flickr.py | Flickr._paged_api_call | def _paged_api_call(self, func, kwargs, item_type='photo'):
"""
Takes a Flickr API function object and dict of keyword args and calls the
API call repeatedly with an incrementing page value until all contents are exhausted.
Flickr seems to limit to about 500 items.
"""
pa... | python | def _paged_api_call(self, func, kwargs, item_type='photo'):
"""
Takes a Flickr API function object and dict of keyword args and calls the
API call repeatedly with an incrementing page value until all contents are exhausted.
Flickr seems to limit to about 500 items.
"""
pa... | [
"def",
"_paged_api_call",
"(",
"self",
",",
"func",
",",
"kwargs",
",",
"item_type",
"=",
"'photo'",
")",
":",
"page",
"=",
"1",
"while",
"True",
":",
"LOG",
".",
"info",
"(",
"\"Fetching page %s\"",
"%",
"page",
")",
"kwargs",
"[",
"'page'",
"]",
"=",... | Takes a Flickr API function object and dict of keyword args and calls the
API call repeatedly with an incrementing page value until all contents are exhausted.
Flickr seems to limit to about 500 items. | [
"Takes",
"a",
"Flickr",
"API",
"function",
"object",
"and",
"dict",
"of",
"keyword",
"args",
"and",
"calls",
"the",
"API",
"call",
"repeatedly",
"with",
"an",
"incrementing",
"page",
"value",
"until",
"all",
"contents",
"are",
"exhausted",
".",
"Flickr",
"se... | da5dc0fee5373a4be294798b5e32cd0a803d8bbe | https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L108-L133 |
242,130 | gear11/pypelogs | pypein/flickr.py | Flickr._prep | def _prep(e):
"""
Normalizes lastupdate to a timestamp, and constructs a URL from the embedded attributes.
"""
if 'lastupdate' in e:
e['lastupdate'] = datetime.datetime.fromtimestamp(int(e['lastupdate']))
for k in ['farm', 'server', 'id', 'secret']:
if not... | python | def _prep(e):
"""
Normalizes lastupdate to a timestamp, and constructs a URL from the embedded attributes.
"""
if 'lastupdate' in e:
e['lastupdate'] = datetime.datetime.fromtimestamp(int(e['lastupdate']))
for k in ['farm', 'server', 'id', 'secret']:
if not... | [
"def",
"_prep",
"(",
"e",
")",
":",
"if",
"'lastupdate'",
"in",
"e",
":",
"e",
"[",
"'lastupdate'",
"]",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"int",
"(",
"e",
"[",
"'lastupdate'",
"]",
")",
")",
"for",
"k",
"in",
"[",
"'farm... | Normalizes lastupdate to a timestamp, and constructs a URL from the embedded attributes. | [
"Normalizes",
"lastupdate",
"to",
"a",
"timestamp",
"and",
"constructs",
"a",
"URL",
"from",
"the",
"embedded",
"attributes",
"."
] | da5dc0fee5373a4be294798b5e32cd0a803d8bbe | https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L136-L146 |
242,131 | gear11/pypelogs | pypein/flickr.py | Flickr._load_rsp | def _load_rsp(rsp):
"""
Converts raw Flickr string response to Python dict
"""
first = rsp.find('(') + 1
last = rsp.rfind(')')
return json.loads(rsp[first:last]) | python | def _load_rsp(rsp):
"""
Converts raw Flickr string response to Python dict
"""
first = rsp.find('(') + 1
last = rsp.rfind(')')
return json.loads(rsp[first:last]) | [
"def",
"_load_rsp",
"(",
"rsp",
")",
":",
"first",
"=",
"rsp",
".",
"find",
"(",
"'('",
")",
"+",
"1",
"last",
"=",
"rsp",
".",
"rfind",
"(",
"')'",
")",
"return",
"json",
".",
"loads",
"(",
"rsp",
"[",
"first",
":",
"last",
"]",
")"
] | Converts raw Flickr string response to Python dict | [
"Converts",
"raw",
"Flickr",
"string",
"response",
"to",
"Python",
"dict"
] | da5dc0fee5373a4be294798b5e32cd0a803d8bbe | https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L149-L155 |
242,132 | BlackEarth/bf | bf/styles.py | Styles.styleProperties | def styleProperties(Class, style):
"""return a properties dict from a given cssutils style
"""
properties = Dict()
for property in style.getProperties(all=True):
stylename = property.name + ':'
properties[stylename] = property.value
if property.priorit... | python | def styleProperties(Class, style):
"""return a properties dict from a given cssutils style
"""
properties = Dict()
for property in style.getProperties(all=True):
stylename = property.name + ':'
properties[stylename] = property.value
if property.priorit... | [
"def",
"styleProperties",
"(",
"Class",
",",
"style",
")",
":",
"properties",
"=",
"Dict",
"(",
")",
"for",
"property",
"in",
"style",
".",
"getProperties",
"(",
"all",
"=",
"True",
")",
":",
"stylename",
"=",
"property",
".",
"name",
"+",
"':'",
"prop... | return a properties dict from a given cssutils style | [
"return",
"a",
"properties",
"dict",
"from",
"a",
"given",
"cssutils",
"style"
] | 376041168874bbd6dee5ccfeece4a9e553223316 | https://github.com/BlackEarth/bf/blob/376041168874bbd6dee5ccfeece4a9e553223316/bf/styles.py#L14-L23 |
242,133 | BlackEarth/bf | bf/styles.py | Styles.from_css | def from_css(Class, csstext, encoding=None, href=None, media=None, title=None, validate=None):
"""parse CSS text into a Styles object, using cssutils
"""
styles = Class()
cssStyleSheet = cssutils.parseString(csstext, encoding=encoding, href=href, media=media, title=title, validate=valida... | python | def from_css(Class, csstext, encoding=None, href=None, media=None, title=None, validate=None):
"""parse CSS text into a Styles object, using cssutils
"""
styles = Class()
cssStyleSheet = cssutils.parseString(csstext, encoding=encoding, href=href, media=media, title=title, validate=valida... | [
"def",
"from_css",
"(",
"Class",
",",
"csstext",
",",
"encoding",
"=",
"None",
",",
"href",
"=",
"None",
",",
"media",
"=",
"None",
",",
"title",
"=",
"None",
",",
"validate",
"=",
"None",
")",
":",
"styles",
"=",
"Class",
"(",
")",
"cssStyleSheet",
... | parse CSS text into a Styles object, using cssutils | [
"parse",
"CSS",
"text",
"into",
"a",
"Styles",
"object",
"using",
"cssutils"
] | 376041168874bbd6dee5ccfeece4a9e553223316 | https://github.com/BlackEarth/bf/blob/376041168874bbd6dee5ccfeece4a9e553223316/bf/styles.py#L26-L70 |
242,134 | aliafshar/oa2 | oa2.py | get_token | def get_token(code, token_service, client_id, client_secret, redirect_uri,
grant_type):
"""Fetches an OAuth 2 token."""
data = {
'code': code,
'client_id': client_id,
'client_secret': client_secret,
'redirect_uri': redirect_uri,
'grant_type': grant_type,
}
# Get the d... | python | def get_token(code, token_service, client_id, client_secret, redirect_uri,
grant_type):
"""Fetches an OAuth 2 token."""
data = {
'code': code,
'client_id': client_id,
'client_secret': client_secret,
'redirect_uri': redirect_uri,
'grant_type': grant_type,
}
# Get the d... | [
"def",
"get_token",
"(",
"code",
",",
"token_service",
",",
"client_id",
",",
"client_secret",
",",
"redirect_uri",
",",
"grant_type",
")",
":",
"data",
"=",
"{",
"'code'",
":",
"code",
",",
"'client_id'",
":",
"client_id",
",",
"'client_secret'",
":",
"clie... | Fetches an OAuth 2 token. | [
"Fetches",
"an",
"OAuth",
"2",
"token",
"."
] | 0df67aea6b393e5a463e90d79bf2c3168e5fcc48 | https://github.com/aliafshar/oa2/blob/0df67aea6b393e5a463e90d79bf2c3168e5fcc48/oa2.py#L160-L172 |
242,135 | aliafshar/oa2 | oa2.py | get_auth_uri | def get_auth_uri(auth_service, client_id, scope, redirect_uri, response_type,
state, access_type, approval_prompt):
"""Generates an authorization uri."""
errors = []
if response_type not in VALID_RESPONSE_TYPES:
errors.append(
'{0} is not a valid response_type, must be {1}.'.format(
... | python | def get_auth_uri(auth_service, client_id, scope, redirect_uri, response_type,
state, access_type, approval_prompt):
"""Generates an authorization uri."""
errors = []
if response_type not in VALID_RESPONSE_TYPES:
errors.append(
'{0} is not a valid response_type, must be {1}.'.format(
... | [
"def",
"get_auth_uri",
"(",
"auth_service",
",",
"client_id",
",",
"scope",
",",
"redirect_uri",
",",
"response_type",
",",
"state",
",",
"access_type",
",",
"approval_prompt",
")",
":",
"errors",
"=",
"[",
"]",
"if",
"response_type",
"not",
"in",
"VALID_RESPO... | Generates an authorization uri. | [
"Generates",
"an",
"authorization",
"uri",
"."
] | 0df67aea6b393e5a463e90d79bf2c3168e5fcc48 | https://github.com/aliafshar/oa2/blob/0df67aea6b393e5a463e90d79bf2c3168e5fcc48/oa2.py#L174-L203 |
242,136 | aliafshar/oa2 | oa2.py | refresh_token | def refresh_token(token_service, refresh_token, client_id, client_secret):
"""Refreshes a token."""
data = {
'client_id': client_id,
'client_secret': client_secret,
'refresh_token': refresh_token,
'grant_type': 'refresh_token',
}
resp = requests.post(token_service, data)
print resp, 'refreshin... | python | def refresh_token(token_service, refresh_token, client_id, client_secret):
"""Refreshes a token."""
data = {
'client_id': client_id,
'client_secret': client_secret,
'refresh_token': refresh_token,
'grant_type': 'refresh_token',
}
resp = requests.post(token_service, data)
print resp, 'refreshin... | [
"def",
"refresh_token",
"(",
"token_service",
",",
"refresh_token",
",",
"client_id",
",",
"client_secret",
")",
":",
"data",
"=",
"{",
"'client_id'",
":",
"client_id",
",",
"'client_secret'",
":",
"client_secret",
",",
"'refresh_token'",
":",
"refresh_token",
","... | Refreshes a token. | [
"Refreshes",
"a",
"token",
"."
] | 0df67aea6b393e5a463e90d79bf2c3168e5fcc48 | https://github.com/aliafshar/oa2/blob/0df67aea6b393e5a463e90d79bf2c3168e5fcc48/oa2.py#L205-L215 |
242,137 | aliafshar/oa2 | oa2.py | run_local | def run_local(client):
"""Starts a local web server and wait for a redirect."""
webbrowser.open(client.get_auth_uri())
code = wait_for_redirect()
return client.get_token(code) | python | def run_local(client):
"""Starts a local web server and wait for a redirect."""
webbrowser.open(client.get_auth_uri())
code = wait_for_redirect()
return client.get_token(code) | [
"def",
"run_local",
"(",
"client",
")",
":",
"webbrowser",
".",
"open",
"(",
"client",
".",
"get_auth_uri",
"(",
")",
")",
"code",
"=",
"wait_for_redirect",
"(",
")",
"return",
"client",
".",
"get_token",
"(",
"code",
")"
] | Starts a local web server and wait for a redirect. | [
"Starts",
"a",
"local",
"web",
"server",
"and",
"wait",
"for",
"a",
"redirect",
"."
] | 0df67aea6b393e5a463e90d79bf2c3168e5fcc48 | https://github.com/aliafshar/oa2/blob/0df67aea6b393e5a463e90d79bf2c3168e5fcc48/oa2.py#L323-L327 |
242,138 | aliafshar/oa2 | oa2.py | main | def main(argv):
"""Entry point for command line script to perform OAuth 2.0."""
p = argparse.ArgumentParser()
p.add_argument('-s', '--scope', nargs='+')
p.add_argument('-o', '--oauth-service', default='google')
p.add_argument('-i', '--client-id')
p.add_argument('-x', '--client-secret')
p.add_argument('-r'... | python | def main(argv):
"""Entry point for command line script to perform OAuth 2.0."""
p = argparse.ArgumentParser()
p.add_argument('-s', '--scope', nargs='+')
p.add_argument('-o', '--oauth-service', default='google')
p.add_argument('-i', '--client-id')
p.add_argument('-x', '--client-secret')
p.add_argument('-r'... | [
"def",
"main",
"(",
"argv",
")",
":",
"p",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"p",
".",
"add_argument",
"(",
"'-s'",
",",
"'--scope'",
",",
"nargs",
"=",
"'+'",
")",
"p",
".",
"add_argument",
"(",
"'-o'",
",",
"'--oauth-service'",
",",
... | Entry point for command line script to perform OAuth 2.0. | [
"Entry",
"point",
"for",
"command",
"line",
"script",
"to",
"perform",
"OAuth",
"2",
".",
"0",
"."
] | 0df67aea6b393e5a463e90d79bf2c3168e5fcc48 | https://github.com/aliafshar/oa2/blob/0df67aea6b393e5a463e90d79bf2c3168e5fcc48/oa2.py#L382-L406 |
242,139 | BlueHack-Core/blueforge | blueforge/util/file.py | check_and_create_directories | def check_and_create_directories(paths):
"""
Check and create directories.
If the directory is exist, It will remove it and create new folder.
:type paths: Array of string or string
:param paths: the location of directory
"""
for path in paths:
if os.path.exists(pat... | python | def check_and_create_directories(paths):
"""
Check and create directories.
If the directory is exist, It will remove it and create new folder.
:type paths: Array of string or string
:param paths: the location of directory
"""
for path in paths:
if os.path.exists(pat... | [
"def",
"check_and_create_directories",
"(",
"paths",
")",
":",
"for",
"path",
"in",
"paths",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"shutil",
".",
"rmtree",
"(",
"path",
")",
"os",
".",
"mkdir",
"(",
"path",
")"
] | Check and create directories.
If the directory is exist, It will remove it and create new folder.
:type paths: Array of string or string
:param paths: the location of directory | [
"Check",
"and",
"create",
"directories",
"."
] | ac40a888ee9c388638a8f312c51f7500b8891b6c | https://github.com/BlueHack-Core/blueforge/blob/ac40a888ee9c388638a8f312c51f7500b8891b6c/blueforge/util/file.py#L12-L24 |
242,140 | BlueHack-Core/blueforge | blueforge/util/file.py | delete_directories | def delete_directories(paths):
"""
Delete directories.
If the directory is exist, It will delete it including files.
:type paths: Array of string or string
:param paths: the location of directory
"""
for path in paths:
if os.path.exists(path):
shutil.rmt... | python | def delete_directories(paths):
"""
Delete directories.
If the directory is exist, It will delete it including files.
:type paths: Array of string or string
:param paths: the location of directory
"""
for path in paths:
if os.path.exists(path):
shutil.rmt... | [
"def",
"delete_directories",
"(",
"paths",
")",
":",
"for",
"path",
"in",
"paths",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"shutil",
".",
"rmtree",
"(",
"path",
")"
] | Delete directories.
If the directory is exist, It will delete it including files.
:type paths: Array of string or string
:param paths: the location of directory | [
"Delete",
"directories",
"."
] | ac40a888ee9c388638a8f312c51f7500b8891b6c | https://github.com/BlueHack-Core/blueforge/blob/ac40a888ee9c388638a8f312c51f7500b8891b6c/blueforge/util/file.py#L27-L38 |
242,141 | BlueHack-Core/blueforge | blueforge/util/file.py | delete_files | def delete_files(paths):
"""
Delete files.
If the file is exist, It will delete it.
:type paths: Array of string or string
:param paths: the location of file
"""
for path in paths:
if os.path.exists(path):
os.remove(path) | python | def delete_files(paths):
"""
Delete files.
If the file is exist, It will delete it.
:type paths: Array of string or string
:param paths: the location of file
"""
for path in paths:
if os.path.exists(path):
os.remove(path) | [
"def",
"delete_files",
"(",
"paths",
")",
":",
"for",
"path",
"in",
"paths",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"remove",
"(",
"path",
")"
] | Delete files.
If the file is exist, It will delete it.
:type paths: Array of string or string
:param paths: the location of file | [
"Delete",
"files",
"."
] | ac40a888ee9c388638a8f312c51f7500b8891b6c | https://github.com/BlueHack-Core/blueforge/blob/ac40a888ee9c388638a8f312c51f7500b8891b6c/blueforge/util/file.py#L41-L52 |
242,142 | firstprayer/monsql | monsql/wrapper_postgresql.py | PostgreSQLDatabase.truncate_table | def truncate_table(self, tablename):
"""
Use 'TRUNCATE TABLE' to truncate the given table
"""
self.cursor.execute('TRUNCATE TABLE %s' %tablename)
self.db.commit() | python | def truncate_table(self, tablename):
"""
Use 'TRUNCATE TABLE' to truncate the given table
"""
self.cursor.execute('TRUNCATE TABLE %s' %tablename)
self.db.commit() | [
"def",
"truncate_table",
"(",
"self",
",",
"tablename",
")",
":",
"self",
".",
"cursor",
".",
"execute",
"(",
"'TRUNCATE TABLE %s'",
"%",
"tablename",
")",
"self",
".",
"db",
".",
"commit",
"(",
")"
] | Use 'TRUNCATE TABLE' to truncate the given table | [
"Use",
"TRUNCATE",
"TABLE",
"to",
"truncate",
"the",
"given",
"table"
] | 6285c15b574c8664046eae2edfeb548c7b173efd | https://github.com/firstprayer/monsql/blob/6285c15b574c8664046eae2edfeb548c7b173efd/monsql/wrapper_postgresql.py#L52-L57 |
242,143 | firstprayer/monsql | monsql/wrapper_postgresql.py | PostgreSQLDatabase.create_schema | def create_schema(self, schema_name):
"""
Create schema. This method only implemented for this class
"""
try:
self.cursor.execute('CREATE SCHEMA %s' % schema_name)
except Exception as e:
raise e
finally:
self.db.commit() | python | def create_schema(self, schema_name):
"""
Create schema. This method only implemented for this class
"""
try:
self.cursor.execute('CREATE SCHEMA %s' % schema_name)
except Exception as e:
raise e
finally:
self.db.commit() | [
"def",
"create_schema",
"(",
"self",
",",
"schema_name",
")",
":",
"try",
":",
"self",
".",
"cursor",
".",
"execute",
"(",
"'CREATE SCHEMA %s'",
"%",
"schema_name",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"e",
"finally",
":",
"self",
".",
"d... | Create schema. This method only implemented for this class | [
"Create",
"schema",
".",
"This",
"method",
"only",
"implemented",
"for",
"this",
"class"
] | 6285c15b574c8664046eae2edfeb548c7b173efd | https://github.com/firstprayer/monsql/blob/6285c15b574c8664046eae2edfeb548c7b173efd/monsql/wrapper_postgresql.py#L59-L68 |
242,144 | hobson/pug-dj | pug/dj/sqlserver.py | datatype | def datatype(dbtype, description, cursor):
"""Google AppEngine Helper to convert a data type into a string."""
dt = cursor.db.introspection.get_field_type(dbtype, description)
if type(dt) is tuple:
return dt[0]
else:
return dt | python | def datatype(dbtype, description, cursor):
"""Google AppEngine Helper to convert a data type into a string."""
dt = cursor.db.introspection.get_field_type(dbtype, description)
if type(dt) is tuple:
return dt[0]
else:
return dt | [
"def",
"datatype",
"(",
"dbtype",
",",
"description",
",",
"cursor",
")",
":",
"dt",
"=",
"cursor",
".",
"db",
".",
"introspection",
".",
"get_field_type",
"(",
"dbtype",
",",
"description",
")",
"if",
"type",
"(",
"dt",
")",
"is",
"tuple",
":",
"retur... | Google AppEngine Helper to convert a data type into a string. | [
"Google",
"AppEngine",
"Helper",
"to",
"convert",
"a",
"data",
"type",
"into",
"a",
"string",
"."
] | 55678b08755a55366ce18e7d3b8ea8fa4491ab04 | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/sqlserver.py#L90-L96 |
242,145 | flytrap/flytrap-base | flytrap/base/backends.py | MongoDjangoFilterBackend.get_filter_class | def get_filter_class(self, view, queryset=None):
"""
Return the django-filters `FilterSet` used to filter the queryset.
"""
filter_class = getattr(view, 'filter_class', None)
if filter_class:
filter_model = filter_class.Meta.model
assert issubclass(querys... | python | def get_filter_class(self, view, queryset=None):
"""
Return the django-filters `FilterSet` used to filter the queryset.
"""
filter_class = getattr(view, 'filter_class', None)
if filter_class:
filter_model = filter_class.Meta.model
assert issubclass(querys... | [
"def",
"get_filter_class",
"(",
"self",
",",
"view",
",",
"queryset",
"=",
"None",
")",
":",
"filter_class",
"=",
"getattr",
"(",
"view",
",",
"'filter_class'",
",",
"None",
")",
"if",
"filter_class",
":",
"filter_model",
"=",
"filter_class",
".",
"Meta",
... | Return the django-filters `FilterSet` used to filter the queryset. | [
"Return",
"the",
"django",
"-",
"filters",
"FilterSet",
"used",
"to",
"filter",
"the",
"queryset",
"."
] | fa5a3135ce669725f88ef61d5d9f548cedfaf0ff | https://github.com/flytrap/flytrap-base/blob/fa5a3135ce669725f88ef61d5d9f548cedfaf0ff/flytrap/base/backends.py#L11-L24 |
242,146 | pycontribs/pyversion | version/tag_command.py | tag.run | def run(self):
"""Will tag the currently active git commit id with the next release tag id"""
sha = VersionUtils.run_git_command(["rev-parse", "HEAD"], self.git_dir)
tag = self.distribution.get_version()
if self.has_tag(tag, sha):
tags_sha = VersionUtils.run_git_command(["re... | python | def run(self):
"""Will tag the currently active git commit id with the next release tag id"""
sha = VersionUtils.run_git_command(["rev-parse", "HEAD"], self.git_dir)
tag = self.distribution.get_version()
if self.has_tag(tag, sha):
tags_sha = VersionUtils.run_git_command(["re... | [
"def",
"run",
"(",
"self",
")",
":",
"sha",
"=",
"VersionUtils",
".",
"run_git_command",
"(",
"[",
"\"rev-parse\"",
",",
"\"HEAD\"",
"]",
",",
"self",
".",
"git_dir",
")",
"tag",
"=",
"self",
".",
"distribution",
".",
"get_version",
"(",
")",
"if",
"se... | Will tag the currently active git commit id with the next release tag id | [
"Will",
"tag",
"the",
"currently",
"active",
"git",
"commit",
"id",
"with",
"the",
"next",
"release",
"tag",
"id"
] | 6bbb799846ed4e97e84a3f0f2dbe14685f2ddb39 | https://github.com/pycontribs/pyversion/blob/6bbb799846ed4e97e84a3f0f2dbe14685f2ddb39/version/tag_command.py#L38-L68 |
242,147 | CTPUG/mdx_attr_cols | mdx_attr_cols.py | AttrColExtension.extendMarkdown | def extendMarkdown(self, md, md_globals=None):
"""Initializes markdown extension components."""
if any(
x not in md.treeprocessors
for x in self.REQUIRED_EXTENSION_INTERNAL_NAMES):
raise RuntimeError(
"The attr_cols markdown extension depends t... | python | def extendMarkdown(self, md, md_globals=None):
"""Initializes markdown extension components."""
if any(
x not in md.treeprocessors
for x in self.REQUIRED_EXTENSION_INTERNAL_NAMES):
raise RuntimeError(
"The attr_cols markdown extension depends t... | [
"def",
"extendMarkdown",
"(",
"self",
",",
"md",
",",
"md_globals",
"=",
"None",
")",
":",
"if",
"any",
"(",
"x",
"not",
"in",
"md",
".",
"treeprocessors",
"for",
"x",
"in",
"self",
".",
"REQUIRED_EXTENSION_INTERNAL_NAMES",
")",
":",
"raise",
"RuntimeError... | Initializes markdown extension components. | [
"Initializes",
"markdown",
"extension",
"components",
"."
] | 46329b676842205b75b368a7cf2aeba0474c2870 | https://github.com/CTPUG/mdx_attr_cols/blob/46329b676842205b75b368a7cf2aeba0474c2870/mdx_attr_cols.py#L71-L83 |
242,148 | FlorianLudwig/rueckenwind | rw/cfg.py | read_file | def read_file(paths):
"""read config from path or list of paths
:param str|list[str] paths: path or list of paths
:return dict: loaded and merged config
"""
if isinstance(paths, str):
paths = [paths]
re = {}
for path in paths:
cfg = yaml.load(open(path))
merge(re, ... | python | def read_file(paths):
"""read config from path or list of paths
:param str|list[str] paths: path or list of paths
:return dict: loaded and merged config
"""
if isinstance(paths, str):
paths = [paths]
re = {}
for path in paths:
cfg = yaml.load(open(path))
merge(re, ... | [
"def",
"read_file",
"(",
"paths",
")",
":",
"if",
"isinstance",
"(",
"paths",
",",
"str",
")",
":",
"paths",
"=",
"[",
"paths",
"]",
"re",
"=",
"{",
"}",
"for",
"path",
"in",
"paths",
":",
"cfg",
"=",
"yaml",
".",
"load",
"(",
"open",
"(",
"pat... | read config from path or list of paths
:param str|list[str] paths: path or list of paths
:return dict: loaded and merged config | [
"read",
"config",
"from",
"path",
"or",
"list",
"of",
"paths"
] | 47fec7af05ea10b3cf6d59b9f7bf4d12c02dddea | https://github.com/FlorianLudwig/rueckenwind/blob/47fec7af05ea10b3cf6d59b9f7bf4d12c02dddea/rw/cfg.py#L29-L44 |
242,149 | openp2pdesign/makerlabs | makerlabs/diybio_org.py | data_from_diybio_org | def data_from_diybio_org():
"""Scrapes data from diybio.org."""
r = requests.get(diy_bio_labs_url)
if r.status_code == 200:
# Fix a problem in the html source while loading it
data = BeautifulSoup(r.text.replace(u'\xa0', u''), "lxml")
else:
data = "There was an error while acce... | python | def data_from_diybio_org():
"""Scrapes data from diybio.org."""
r = requests.get(diy_bio_labs_url)
if r.status_code == 200:
# Fix a problem in the html source while loading it
data = BeautifulSoup(r.text.replace(u'\xa0', u''), "lxml")
else:
data = "There was an error while acce... | [
"def",
"data_from_diybio_org",
"(",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"diy_bio_labs_url",
")",
"if",
"r",
".",
"status_code",
"==",
"200",
":",
"# Fix a problem in the html source while loading it",
"data",
"=",
"BeautifulSoup",
"(",
"r",
".",
"te... | Scrapes data from diybio.org. | [
"Scrapes",
"data",
"from",
"diybio",
".",
"org",
"."
] | b5838440174f10d370abb671358db9a99d7739fd | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/diybio_org.py#L34-L45 |
242,150 | jeffrimko/Auxly | lib/auxly/__init__.py | open | def open(target):
"""Opens the target file or URL in the default application.
**Attribution**:
Written by user4815162342 and originally posted on
`Stack Overflow <http://stackoverflow.com/a/17317468>`_.
**Examples**:
::
auxly.open("myfile.txt")
auxly.open("https://www.github.co... | python | def open(target):
"""Opens the target file or URL in the default application.
**Attribution**:
Written by user4815162342 and originally posted on
`Stack Overflow <http://stackoverflow.com/a/17317468>`_.
**Examples**:
::
auxly.open("myfile.txt")
auxly.open("https://www.github.co... | [
"def",
"open",
"(",
"target",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"\"win32\"",
":",
"os",
".",
"startfile",
"(",
"target",
")",
"else",
":",
"opener",
"=",
"\"open\"",
"if",
"sys",
".",
"platform",
"==",
"\"darwin\"",
"else",
"\"xdg-open\"",
... | Opens the target file or URL in the default application.
**Attribution**:
Written by user4815162342 and originally posted on
`Stack Overflow <http://stackoverflow.com/a/17317468>`_.
**Examples**:
::
auxly.open("myfile.txt")
auxly.open("https://www.github.com/") | [
"Opens",
"the",
"target",
"file",
"or",
"URL",
"in",
"the",
"default",
"application",
"."
] | 5aae876bcb6ca117c81d904f9455764cdc78cd48 | https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/__init__.py#L25-L41 |
242,151 | jeffrimko/Auxly | lib/auxly/__init__.py | verbose | def verbose(enabled):
"""Returns normal print function if enable, otherwise a dummy print
function is returned which will suppress output."""
def _vprint(msg, **kwargs):
print(msg, **kwargs)
def _nprint(msg, **kwargs):
pass
return _vprint if enabled else _nprint | python | def verbose(enabled):
"""Returns normal print function if enable, otherwise a dummy print
function is returned which will suppress output."""
def _vprint(msg, **kwargs):
print(msg, **kwargs)
def _nprint(msg, **kwargs):
pass
return _vprint if enabled else _nprint | [
"def",
"verbose",
"(",
"enabled",
")",
":",
"def",
"_vprint",
"(",
"msg",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
"(",
"msg",
",",
"*",
"*",
"kwargs",
")",
"def",
"_nprint",
"(",
"msg",
",",
"*",
"*",
"kwargs",
")",
":",
"pass",
"return",
"... | Returns normal print function if enable, otherwise a dummy print
function is returned which will suppress output. | [
"Returns",
"normal",
"print",
"function",
"if",
"enable",
"otherwise",
"a",
"dummy",
"print",
"function",
"is",
"returned",
"which",
"will",
"suppress",
"output",
"."
] | 5aae876bcb6ca117c81d904f9455764cdc78cd48 | https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/__init__.py#L55-L62 |
242,152 | jeffrimko/Auxly | lib/auxly/__init__.py | callstop | def callstop(*args, **kwargs):
"""Limits the number of times a function can be called. Can be used as a
function decorator or as a function that accepts another function. If used
as a function, it returns a new function that will be call limited.
**Params**:
- func (func) - Function to call. Only... | python | def callstop(*args, **kwargs):
"""Limits the number of times a function can be called. Can be used as a
function decorator or as a function that accepts another function. If used
as a function, it returns a new function that will be call limited.
**Params**:
- func (func) - Function to call. Only... | [
"def",
"callstop",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"limit",
"=",
"kwargs",
".",
"get",
"(",
"'limit'",
",",
"1",
")",
"def",
"decor",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
... | Limits the number of times a function can be called. Can be used as a
function decorator or as a function that accepts another function. If used
as a function, it returns a new function that will be call limited.
**Params**:
- func (func) - Function to call. Only available when used as a function.
... | [
"Limits",
"the",
"number",
"of",
"times",
"a",
"function",
"can",
"be",
"called",
".",
"Can",
"be",
"used",
"as",
"a",
"function",
"decorator",
"or",
"as",
"a",
"function",
"that",
"accepts",
"another",
"function",
".",
"If",
"used",
"as",
"a",
"function... | 5aae876bcb6ca117c81d904f9455764cdc78cd48 | https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/__init__.py#L97-L122 |
242,153 | 50onRed/smr | smr/ec2.py | wait_for_instance | def wait_for_instance(instance):
""" wait for instance status to be 'running' in which case return True, False otherwise """
status = None
print("getting status for instance {} ...".format(instance.id))
while status is None:
try:
status = instance.update()
if status is N... | python | def wait_for_instance(instance):
""" wait for instance status to be 'running' in which case return True, False otherwise """
status = None
print("getting status for instance {} ...".format(instance.id))
while status is None:
try:
status = instance.update()
if status is N... | [
"def",
"wait_for_instance",
"(",
"instance",
")",
":",
"status",
"=",
"None",
"print",
"(",
"\"getting status for instance {} ...\"",
".",
"format",
"(",
"instance",
".",
"id",
")",
")",
"while",
"status",
"is",
"None",
":",
"try",
":",
"status",
"=",
"insta... | wait for instance status to be 'running' in which case return True, False otherwise | [
"wait",
"for",
"instance",
"status",
"to",
"be",
"running",
"in",
"which",
"case",
"return",
"True",
"False",
"otherwise"
] | 999b33d86b6a900d7c4aadf03cf4a661acba9f1b | https://github.com/50onRed/smr/blob/999b33d86b6a900d7c4aadf03cf4a661acba9f1b/smr/ec2.py#L78-L102 |
242,154 | openknowledge-archive/datapackage-validate-py | datapackage_validate/validate.py | validate | def validate(datapackage, schema='base'):
'''Validate Data Package datapackage.json files against a jsonschema.
Args:
datapackage (str or dict): The Data Package descriptor file (i.e.
datapackage.json) as a dict or its contents in a string.
schema (str or dict): If a string, it can ... | python | def validate(datapackage, schema='base'):
'''Validate Data Package datapackage.json files against a jsonschema.
Args:
datapackage (str or dict): The Data Package descriptor file (i.e.
datapackage.json) as a dict or its contents in a string.
schema (str or dict): If a string, it can ... | [
"def",
"validate",
"(",
"datapackage",
",",
"schema",
"=",
"'base'",
")",
":",
"errors",
"=",
"[",
"]",
"schema_obj",
"=",
"None",
"datapackage_obj",
"=",
"None",
"# Sanity check datapackage",
"# If datapackage is a str, check json is well formed",
"if",
"isinstance",
... | Validate Data Package datapackage.json files against a jsonschema.
Args:
datapackage (str or dict): The Data Package descriptor file (i.e.
datapackage.json) as a dict or its contents in a string.
schema (str or dict): If a string, it can be the schema ID in the
registry, a l... | [
"Validate",
"Data",
"Package",
"datapackage",
".",
"json",
"files",
"against",
"a",
"jsonschema",
"."
] | 5f906bd4e0baa78dfd45f48e7fa3c5d649e6846a | https://github.com/openknowledge-archive/datapackage-validate-py/blob/5f906bd4e0baa78dfd45f48e7fa3c5d649e6846a/datapackage_validate/validate.py#L19-L78 |
242,155 | lextoumbourou/txstripe | txstripe/resource.py | make_request | def make_request(
ins, method, url, stripe_account=None, params=None, headers=None, **kwargs
):
"""
Return a deferred or handle error.
For overriding in various classes.
"""
if txstripe.api_key is None:
raise error.AuthenticationError(
'No API key provided. (HINT: set your A... | python | def make_request(
ins, method, url, stripe_account=None, params=None, headers=None, **kwargs
):
"""
Return a deferred or handle error.
For overriding in various classes.
"""
if txstripe.api_key is None:
raise error.AuthenticationError(
'No API key provided. (HINT: set your A... | [
"def",
"make_request",
"(",
"ins",
",",
"method",
",",
"url",
",",
"stripe_account",
"=",
"None",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"txstripe",
".",
"api_key",
"is",
"None",
":",
"raise"... | Return a deferred or handle error.
For overriding in various classes. | [
"Return",
"a",
"deferred",
"or",
"handle",
"error",
"."
] | a69e67f524258026fd1840655a0578311bba3b89 | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L52-L110 |
242,156 | jashort/SmartFileSorter | smartfilesorter/smartfilesorter.py | SmartFileSorter.create_logger | def create_logger(self, args={}):
"""
Create and configure the program's logger object.
Log levels:
DEBUG - Log everything. Hidden unless --debug is used.
INFO - information only
ERROR - Critical error
:param args: Object containing program's parsed command line ... | python | def create_logger(self, args={}):
"""
Create and configure the program's logger object.
Log levels:
DEBUG - Log everything. Hidden unless --debug is used.
INFO - information only
ERROR - Critical error
:param args: Object containing program's parsed command line ... | [
"def",
"create_logger",
"(",
"self",
",",
"args",
"=",
"{",
"}",
")",
":",
"# Set up logging",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"\"SmartFileSorter\"",
")",
"logger",
".",
"level",
"=",
"logging",
".",
"INFO",
"if",
"'--debug'",
"in",
"args"... | Create and configure the program's logger object.
Log levels:
DEBUG - Log everything. Hidden unless --debug is used.
INFO - information only
ERROR - Critical error
:param args: Object containing program's parsed command line arguments
:return: None | [
"Create",
"and",
"configure",
"the",
"program",
"s",
"logger",
"object",
"."
] | 77faf09e5a737da93e16e71a64707366b8307910 | https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/smartfilesorter.py#L45-L81 |
242,157 | jashort/SmartFileSorter | smartfilesorter/smartfilesorter.py | SmartFileSorter.load_plugins | def load_plugins(self, plugin_path):
"""
Loads plugins from modules in plugin_path. Looks for the config_name property
in each object that's found. If so, adds that to the dictionary with the
config_name as the key. config_name should be unique between different plugins.
:param ... | python | def load_plugins(self, plugin_path):
"""
Loads plugins from modules in plugin_path. Looks for the config_name property
in each object that's found. If so, adds that to the dictionary with the
config_name as the key. config_name should be unique between different plugins.
:param ... | [
"def",
"load_plugins",
"(",
"self",
",",
"plugin_path",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Loading plugins from {0}'",
".",
"format",
"(",
"plugin_path",
")",
")",
"plugins",
"=",
"{",
"}",
"plugin_dir",
"=",
"os",
".",
"path",
".",
"r... | Loads plugins from modules in plugin_path. Looks for the config_name property
in each object that's found. If so, adds that to the dictionary with the
config_name as the key. config_name should be unique between different plugins.
:param plugin_path: Path to load plugins from
:return: d... | [
"Loads",
"plugins",
"from",
"modules",
"in",
"plugin_path",
".",
"Looks",
"for",
"the",
"config_name",
"property",
"in",
"each",
"object",
"that",
"s",
"found",
".",
"If",
"so",
"adds",
"that",
"to",
"the",
"dictionary",
"with",
"the",
"config_name",
"as",
... | 77faf09e5a737da93e16e71a64707366b8307910 | https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/smartfilesorter.py#L132-L178 |
242,158 | klmitch/appathy | appathy/actions.py | ActionDescriptor.deserialize_request | def deserialize_request(self, req):
"""
Uses the deserializers declared on the action method and its
extensions to deserialize the request. Returns the result of
the deserialization. Raises `webob.HTTPUnsupportedMediaType`
if the media type of the request is unsupported.
... | python | def deserialize_request(self, req):
"""
Uses the deserializers declared on the action method and its
extensions to deserialize the request. Returns the result of
the deserialization. Raises `webob.HTTPUnsupportedMediaType`
if the media type of the request is unsupported.
... | [
"def",
"deserialize_request",
"(",
"self",
",",
"req",
")",
":",
"# See if we have a body",
"if",
"req",
".",
"content_length",
"==",
"0",
":",
"return",
"None",
"# Get the primary deserializer",
"try",
":",
"deserializer",
"=",
"self",
".",
"method",
".",
"dese... | Uses the deserializers declared on the action method and its
extensions to deserialize the request. Returns the result of
the deserialization. Raises `webob.HTTPUnsupportedMediaType`
if the media type of the request is unsupported. | [
"Uses",
"the",
"deserializers",
"declared",
"on",
"the",
"action",
"method",
"and",
"its",
"extensions",
"to",
"deserialize",
"the",
"request",
".",
"Returns",
"the",
"result",
"of",
"the",
"deserialization",
".",
"Raises",
"webob",
".",
"HTTPUnsupportedMediaType"... | a10aa7d21d38622e984a8fe106ab37114af90dc2 | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/actions.py#L99-L127 |
242,159 | klmitch/appathy | appathy/actions.py | ActionDescriptor.serializer | def serializer(self, req):
"""
Selects and returns the serializer to use, based on the
serializers declared on the action method and its extensions.
The returned content type is selected based on the types
available and the best match generated from the HTTP `Accept`
head... | python | def serializer(self, req):
"""
Selects and returns the serializer to use, based on the
serializers declared on the action method and its extensions.
The returned content type is selected based on the types
available and the best match generated from the HTTP `Accept`
head... | [
"def",
"serializer",
"(",
"self",
",",
"req",
")",
":",
"# Select the best match serializer",
"content_types",
"=",
"self",
".",
"method",
".",
"serializers",
".",
"get_types",
"(",
")",
"content_type",
"=",
"req",
".",
"accept",
".",
"best_match",
"(",
"conte... | Selects and returns the serializer to use, based on the
serializers declared on the action method and its extensions.
The returned content type is selected based on the types
available and the best match generated from the HTTP `Accept`
header. Raises `HTTPNotAcceptable` if the request ... | [
"Selects",
"and",
"returns",
"the",
"serializer",
"to",
"use",
"based",
"on",
"the",
"serializers",
"declared",
"on",
"the",
"action",
"method",
"and",
"its",
"extensions",
".",
"The",
"returned",
"content",
"type",
"is",
"selected",
"based",
"on",
"the",
"t... | a10aa7d21d38622e984a8fe106ab37114af90dc2 | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/actions.py#L129-L162 |
242,160 | klmitch/appathy | appathy/actions.py | ActionDescriptor.wrap | def wrap(self, req, result):
"""
Wrap method return results. The return value of the action
method and of the action extensions is passed through this
method before being returned to the caller. Instances of
`webob.Response` are thrown, to abort the rest of action and
e... | python | def wrap(self, req, result):
"""
Wrap method return results. The return value of the action
method and of the action extensions is passed through this
method before being returned to the caller. Instances of
`webob.Response` are thrown, to abort the rest of action and
e... | [
"def",
"wrap",
"(",
"self",
",",
"req",
",",
"result",
")",
":",
"if",
"isinstance",
"(",
"result",
",",
"webob",
".",
"exc",
".",
"HTTPException",
")",
":",
"# It's a webob HTTP exception; use raise to bail out",
"# immediately and pass it upstream",
"raise",
"resu... | Wrap method return results. The return value of the action
method and of the action extensions is passed through this
method before being returned to the caller. Instances of
`webob.Response` are thrown, to abort the rest of action and
extension processing; otherwise, objects which are... | [
"Wrap",
"method",
"return",
"results",
".",
"The",
"return",
"value",
"of",
"the",
"action",
"method",
"and",
"of",
"the",
"action",
"extensions",
"is",
"passed",
"through",
"this",
"method",
"before",
"being",
"returned",
"to",
"the",
"caller",
".",
"Instan... | a10aa7d21d38622e984a8fe106ab37114af90dc2 | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/actions.py#L231-L255 |
242,161 | bitlabstudio/django-outlets | outlets/models.py | OutletManager.active | def active(self):
"""Returns all outlets that are currently active and have sales."""
qs = self.get_queryset()
return qs.filter(
models.Q(
models.Q(start_date__isnull=True) |
models.Q(start_date__lte=now().date())
) &
models.Q(
... | python | def active(self):
"""Returns all outlets that are currently active and have sales."""
qs = self.get_queryset()
return qs.filter(
models.Q(
models.Q(start_date__isnull=True) |
models.Q(start_date__lte=now().date())
) &
models.Q(
... | [
"def",
"active",
"(",
"self",
")",
":",
"qs",
"=",
"self",
".",
"get_queryset",
"(",
")",
"return",
"qs",
".",
"filter",
"(",
"models",
".",
"Q",
"(",
"models",
".",
"Q",
"(",
"start_date__isnull",
"=",
"True",
")",
"|",
"models",
".",
"Q",
"(",
... | Returns all outlets that are currently active and have sales. | [
"Returns",
"all",
"outlets",
"that",
"are",
"currently",
"active",
"and",
"have",
"sales",
"."
] | eaecc1e8ef8fb48d6dc5886b321d9e3b0359b228 | https://github.com/bitlabstudio/django-outlets/blob/eaecc1e8ef8fb48d6dc5886b321d9e3b0359b228/outlets/models.py#L14-L26 |
242,162 | bitlabstudio/django-outlets | outlets/models.py | OutletManager.future | def future(self):
"""Returns all outlets that are or will be active."""
qs = self.get_queryset()
return qs.filter(
models.Q(end_date__isnull=True) |
models.Q(end_date__gte=now().date())
) | python | def future(self):
"""Returns all outlets that are or will be active."""
qs = self.get_queryset()
return qs.filter(
models.Q(end_date__isnull=True) |
models.Q(end_date__gte=now().date())
) | [
"def",
"future",
"(",
"self",
")",
":",
"qs",
"=",
"self",
".",
"get_queryset",
"(",
")",
"return",
"qs",
".",
"filter",
"(",
"models",
".",
"Q",
"(",
"end_date__isnull",
"=",
"True",
")",
"|",
"models",
".",
"Q",
"(",
"end_date__gte",
"=",
"now",
... | Returns all outlets that are or will be active. | [
"Returns",
"all",
"outlets",
"that",
"are",
"or",
"will",
"be",
"active",
"."
] | eaecc1e8ef8fb48d6dc5886b321d9e3b0359b228 | https://github.com/bitlabstudio/django-outlets/blob/eaecc1e8ef8fb48d6dc5886b321d9e3b0359b228/outlets/models.py#L28-L34 |
242,163 | political-memory/django-representatives | representatives/contrib/francedata/import_representatives.py | ensure_chambers | def ensure_chambers():
"""
Ensures chambers are created
"""
france = Country.objects.get(name="France")
for key in ('AN', 'SEN'):
variant = FranceDataVariants[key]
Chamber.objects.get_or_create(name=variant['chamber'],
abbreviation=variant['abbre... | python | def ensure_chambers():
"""
Ensures chambers are created
"""
france = Country.objects.get(name="France")
for key in ('AN', 'SEN'):
variant = FranceDataVariants[key]
Chamber.objects.get_or_create(name=variant['chamber'],
abbreviation=variant['abbre... | [
"def",
"ensure_chambers",
"(",
")",
":",
"france",
"=",
"Country",
".",
"objects",
".",
"get",
"(",
"name",
"=",
"\"France\"",
")",
"for",
"key",
"in",
"(",
"'AN'",
",",
"'SEN'",
")",
":",
"variant",
"=",
"FranceDataVariants",
"[",
"key",
"]",
"Chamber... | Ensures chambers are created | [
"Ensures",
"chambers",
"are",
"created"
] | 811c90d0250149e913e6196f0ab11c97d396be39 | https://github.com/political-memory/django-representatives/blob/811c90d0250149e913e6196f0ab11c97d396be39/representatives/contrib/francedata/import_representatives.py#L95-L104 |
242,164 | political-memory/django-representatives | representatives/contrib/francedata/import_representatives.py | GenericImporter.touch_model | def touch_model(self, model, **data):
'''
This method create or look up a model with the given data
it saves the given model if it exists, updating its
updated field
'''
instance, created = model.objects.get_or_create(**data)
if not created:
if insta... | python | def touch_model(self, model, **data):
'''
This method create or look up a model with the given data
it saves the given model if it exists, updating its
updated field
'''
instance, created = model.objects.get_or_create(**data)
if not created:
if insta... | [
"def",
"touch_model",
"(",
"self",
",",
"model",
",",
"*",
"*",
"data",
")",
":",
"instance",
",",
"created",
"=",
"model",
".",
"objects",
".",
"get_or_create",
"(",
"*",
"*",
"data",
")",
"if",
"not",
"created",
":",
"if",
"instance",
".",
"updated... | This method create or look up a model with the given data
it saves the given model if it exists, updating its
updated field | [
"This",
"method",
"create",
"or",
"look",
"up",
"a",
"model",
"with",
"the",
"given",
"data",
"it",
"saves",
"the",
"given",
"model",
"if",
"it",
"exists",
"updating",
"its",
"updated",
"field"
] | 811c90d0250149e913e6196f0ab11c97d396be39 | https://github.com/political-memory/django-representatives/blob/811c90d0250149e913e6196f0ab11c97d396be39/representatives/contrib/francedata/import_representatives.py#L79-L92 |
242,165 | political-memory/django-representatives | representatives/contrib/francedata/import_representatives.py | FranceDataImporter.add_mandates | def add_mandates(self, representative, rep_json):
'''
Create mandates from rep data based on variant configuration
'''
# Mandate in country group for party constituency
if rep_json.get('parti_ratt_financier'):
constituency, _ = Constituency.objects.get_or_create(
... | python | def add_mandates(self, representative, rep_json):
'''
Create mandates from rep data based on variant configuration
'''
# Mandate in country group for party constituency
if rep_json.get('parti_ratt_financier'):
constituency, _ = Constituency.objects.get_or_create(
... | [
"def",
"add_mandates",
"(",
"self",
",",
"representative",
",",
"rep_json",
")",
":",
"# Mandate in country group for party constituency",
"if",
"rep_json",
".",
"get",
"(",
"'parti_ratt_financier'",
")",
":",
"constituency",
",",
"_",
"=",
"Constituency",
".",
"obj... | Create mandates from rep data based on variant configuration | [
"Create",
"mandates",
"from",
"rep",
"data",
"based",
"on",
"variant",
"configuration"
] | 811c90d0250149e913e6196f0ab11c97d396be39 | https://github.com/political-memory/django-representatives/blob/811c90d0250149e913e6196f0ab11c97d396be39/representatives/contrib/francedata/import_representatives.py#L218-L270 |
242,166 | hobson/pug-dj | pug/dj/crawlnmine/crawlnmine/settings/master_common.py | env | def env(var_name, default=False):
""" Get the environment variable. If not found use a default or False, but print to stderr a warning about the missing env variable."""
try:
value = os.environ[var_name]
if str(value).strip().lower() in ['false', 'f', 'no', 'off' '0', 'none', 'null', '', ]:
... | python | def env(var_name, default=False):
""" Get the environment variable. If not found use a default or False, but print to stderr a warning about the missing env variable."""
try:
value = os.environ[var_name]
if str(value).strip().lower() in ['false', 'f', 'no', 'off' '0', 'none', 'null', '', ]:
... | [
"def",
"env",
"(",
"var_name",
",",
"default",
"=",
"False",
")",
":",
"try",
":",
"value",
"=",
"os",
".",
"environ",
"[",
"var_name",
"]",
"if",
"str",
"(",
"value",
")",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"in",
"[",
"'false'",
"... | Get the environment variable. If not found use a default or False, but print to stderr a warning about the missing env variable. | [
"Get",
"the",
"environment",
"variable",
".",
"If",
"not",
"found",
"use",
"a",
"default",
"or",
"False",
"but",
"print",
"to",
"stderr",
"a",
"warning",
"about",
"the",
"missing",
"env",
"variable",
"."
] | 55678b08755a55366ce18e7d3b8ea8fa4491ab04 | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawlnmine/crawlnmine/settings/master_common.py#L21-L33 |
242,167 | esterhui/pypu | scripts/build_json_from_gps.py | lookupfile | def lookupfile(filename):
"""Returns dictionary of file content as well
as google reverse GEO data"""
logger.info('Looking up %s'%(filename))
# First open cache file to see if we already looked up this stuff
dirname=os.path.dirname(filename)
basefilename=os.path.basename(filename)
CACHE_F... | python | def lookupfile(filename):
"""Returns dictionary of file content as well
as google reverse GEO data"""
logger.info('Looking up %s'%(filename))
# First open cache file to see if we already looked up this stuff
dirname=os.path.dirname(filename)
basefilename=os.path.basename(filename)
CACHE_F... | [
"def",
"lookupfile",
"(",
"filename",
")",
":",
"logger",
".",
"info",
"(",
"'Looking up %s'",
"%",
"(",
"filename",
")",
")",
"# First open cache file to see if we already looked up this stuff",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
... | Returns dictionary of file content as well
as google reverse GEO data | [
"Returns",
"dictionary",
"of",
"file",
"content",
"as",
"well",
"as",
"google",
"reverse",
"GEO",
"data"
] | cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec | https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/scripts/build_json_from_gps.py#L75-L101 |
242,168 | esterhui/pypu | scripts/build_json_from_gps.py | parsePositionFile | def parsePositionFile(filename):
"""
Parses Android GPS logger csv file and returns list of dictionaries
"""
l=[]
with open( filename, "rb" ) as theFile:
reader = csv.DictReader( theFile )
for line in reader:
# Convert the time string to something
# a bit more... | python | def parsePositionFile(filename):
"""
Parses Android GPS logger csv file and returns list of dictionaries
"""
l=[]
with open( filename, "rb" ) as theFile:
reader = csv.DictReader( theFile )
for line in reader:
# Convert the time string to something
# a bit more... | [
"def",
"parsePositionFile",
"(",
"filename",
")",
":",
"l",
"=",
"[",
"]",
"with",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"theFile",
":",
"reader",
"=",
"csv",
".",
"DictReader",
"(",
"theFile",
")",
"for",
"line",
"in",
"reader",
":",
"#... | Parses Android GPS logger csv file and returns list of dictionaries | [
"Parses",
"Android",
"GPS",
"logger",
"csv",
"file",
"and",
"returns",
"list",
"of",
"dictionaries"
] | cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec | https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/scripts/build_json_from_gps.py#L154-L167 |
242,169 | datakortet/dkfileutils | dkfileutils/changed.py | changed | def changed(dirname, filename='.md5', args=None, glob=None):
"""Has `glob` changed in `dirname`
Args:
dirname: directory to measure
filename: filename to store checksum
"""
root = Path(dirname)
if not root.exists():
# if dirname doesn't exist it is changed (by definition)
... | python | def changed(dirname, filename='.md5', args=None, glob=None):
"""Has `glob` changed in `dirname`
Args:
dirname: directory to measure
filename: filename to store checksum
"""
root = Path(dirname)
if not root.exists():
# if dirname doesn't exist it is changed (by definition)
... | [
"def",
"changed",
"(",
"dirname",
",",
"filename",
"=",
"'.md5'",
",",
"args",
"=",
"None",
",",
"glob",
"=",
"None",
")",
":",
"root",
"=",
"Path",
"(",
"dirname",
")",
"if",
"not",
"root",
".",
"exists",
"(",
")",
":",
"# if dirname doesn't exist it ... | Has `glob` changed in `dirname`
Args:
dirname: directory to measure
filename: filename to store checksum | [
"Has",
"glob",
"changed",
"in",
"dirname"
] | 924098d6e2edf88ad9b3ffdec9c74530f80a7d77 | https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/changed.py#L28-L52 |
242,170 | datakortet/dkfileutils | dkfileutils/changed.py | main | def main(): # pragma: nocover
"""Return exit code of zero iff directory is not changed.
"""
p = argparse.ArgumentParser()
p.add_argument(
'directory',
help="Directory to check"
)
p.add_argument(
'--verbose', '-v', action='store_true',
help="increase verbosity"
... | python | def main(): # pragma: nocover
"""Return exit code of zero iff directory is not changed.
"""
p = argparse.ArgumentParser()
p.add_argument(
'directory',
help="Directory to check"
)
p.add_argument(
'--verbose', '-v', action='store_true',
help="increase verbosity"
... | [
"def",
"main",
"(",
")",
":",
"# pragma: nocover",
"p",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"p",
".",
"add_argument",
"(",
"'directory'",
",",
"help",
"=",
"\"Directory to check\"",
")",
"p",
".",
"add_argument",
"(",
"'--verbose'",
",",
"'-v'"... | Return exit code of zero iff directory is not changed. | [
"Return",
"exit",
"code",
"of",
"zero",
"iff",
"directory",
"is",
"not",
"changed",
"."
] | 924098d6e2edf88ad9b3ffdec9c74530f80a7d77 | https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/changed.py#L67-L83 |
242,171 | datakortet/dkfileutils | dkfileutils/changed.py | Directory.changed | def changed(self, filename='.md5', glob=None):
"""Are any of the files matched by ``glob`` changed?
"""
if glob is not None:
filename += '.glob-' + ''.join(ch.lower()
for ch in glob if ch.isalpha())
return changed(self, filename, glo... | python | def changed(self, filename='.md5', glob=None):
"""Are any of the files matched by ``glob`` changed?
"""
if glob is not None:
filename += '.glob-' + ''.join(ch.lower()
for ch in glob if ch.isalpha())
return changed(self, filename, glo... | [
"def",
"changed",
"(",
"self",
",",
"filename",
"=",
"'.md5'",
",",
"glob",
"=",
"None",
")",
":",
"if",
"glob",
"is",
"not",
"None",
":",
"filename",
"+=",
"'.glob-'",
"+",
"''",
".",
"join",
"(",
"ch",
".",
"lower",
"(",
")",
"for",
"ch",
"in",... | Are any of the files matched by ``glob`` changed? | [
"Are",
"any",
"of",
"the",
"files",
"matched",
"by",
"glob",
"changed?"
] | 924098d6e2edf88ad9b3ffdec9c74530f80a7d77 | https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/changed.py#L58-L64 |
242,172 | mikkeljans/pyconomic | pyconomic/client.py | EconomicsFacade.create_order | def create_order(self, debtor, is_vat_included=True, due_date=None,
heading='', text_line1='', text_line2='',
debtor_data=None, delivery_data=None, products=None,
project=None, other_reference='', model=models.Order, **extra
):
... | python | def create_order(self, debtor, is_vat_included=True, due_date=None,
heading='', text_line1='', text_line2='',
debtor_data=None, delivery_data=None, products=None,
project=None, other_reference='', model=models.Order, **extra
):
... | [
"def",
"create_order",
"(",
"self",
",",
"debtor",
",",
"is_vat_included",
"=",
"True",
",",
"due_date",
"=",
"None",
",",
"heading",
"=",
"''",
",",
"text_line1",
"=",
"''",
",",
"text_line2",
"=",
"''",
",",
"debtor_data",
"=",
"None",
",",
"delivery_d... | Create a new Order.
Args:
debtor (Debtor): the debtor of the order
debtor_data (mapping): map of debtor data {'postal_code: .., 'city': .., 'ean': ..}
defaults to values on debitor instance for missing values
delivery_data (mapping): map of... | [
"Create",
"a",
"new",
"Order",
"."
] | 845b8148a364cf5be9065f8a70133d4f16ab645d | https://github.com/mikkeljans/pyconomic/blob/845b8148a364cf5be9065f8a70133d4f16ab645d/pyconomic/client.py#L61-L130 |
242,173 | bwesterb/py-joyce | src/comet.py | CometJoyceServerRelay.__flush | def __flush(self, async=True):
""" Flushes messages through current HttpRequest and closes it.
It assumes a current requesthandler and requires a lock
on self.lock """
rh = self.rh
messages = list(self.messages)
stream_notices = list(self.stream_notices)
s... | python | def __flush(self, async=True):
""" Flushes messages through current HttpRequest and closes it.
It assumes a current requesthandler and requires a lock
on self.lock """
rh = self.rh
messages = list(self.messages)
stream_notices = list(self.stream_notices)
s... | [
"def",
"__flush",
"(",
"self",
",",
"async",
"=",
"True",
")",
":",
"rh",
"=",
"self",
".",
"rh",
"messages",
"=",
"list",
"(",
"self",
".",
"messages",
")",
"stream_notices",
"=",
"list",
"(",
"self",
".",
"stream_notices",
")",
"self",
".",
"stream... | Flushes messages through current HttpRequest and closes it.
It assumes a current requesthandler and requires a lock
on self.lock | [
"Flushes",
"messages",
"through",
"current",
"HttpRequest",
"and",
"closes",
"it",
".",
"It",
"assumes",
"a",
"current",
"requesthandler",
"and",
"requires",
"a",
"lock",
"on",
"self",
".",
"lock"
] | ad1c99ad3939e70b247a18a1a0ef537b037979a0 | https://github.com/bwesterb/py-joyce/blob/ad1c99ad3939e70b247a18a1a0ef537b037979a0/src/comet.py#L280-L296 |
242,174 | maceoutliner/django-fiction-outlines | fiction_outlines/views.py | OutlineExport.return_opml_response | def return_opml_response(self, context, **response_kwargs):
'''
Returns export data as an opml file.
'''
self.template_name = 'fiction_outlines/outline.opml'
response = super().render_to_response(context, content_type='text/xml', **response_kwargs)
response['Content-Dispo... | python | def return_opml_response(self, context, **response_kwargs):
'''
Returns export data as an opml file.
'''
self.template_name = 'fiction_outlines/outline.opml'
response = super().render_to_response(context, content_type='text/xml', **response_kwargs)
response['Content-Dispo... | [
"def",
"return_opml_response",
"(",
"self",
",",
"context",
",",
"*",
"*",
"response_kwargs",
")",
":",
"self",
".",
"template_name",
"=",
"'fiction_outlines/outline.opml'",
"response",
"=",
"super",
"(",
")",
".",
"render_to_response",
"(",
"context",
",",
"con... | Returns export data as an opml file. | [
"Returns",
"export",
"data",
"as",
"an",
"opml",
"file",
"."
] | 6c58e356af3fbe7b23557643ba27e46eaef9d4e3 | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/views.py#L1261-L1268 |
242,175 | maceoutliner/django-fiction-outlines | fiction_outlines/views.py | OutlineExport.render_to_response | def render_to_response(self, context, **response_kwargs):
'''
Compares requested format to supported formats and routes the response.
:attribute switcher: A dictionary of format types and their respective response methods.
'''
switcher = {
'json': self.return_json_re... | python | def render_to_response(self, context, **response_kwargs):
'''
Compares requested format to supported formats and routes the response.
:attribute switcher: A dictionary of format types and their respective response methods.
'''
switcher = {
'json': self.return_json_re... | [
"def",
"render_to_response",
"(",
"self",
",",
"context",
",",
"*",
"*",
"response_kwargs",
")",
":",
"switcher",
"=",
"{",
"'json'",
":",
"self",
".",
"return_json_response",
",",
"'opml'",
":",
"self",
".",
"return_opml_response",
",",
"'md'",
":",
"self",... | Compares requested format to supported formats and routes the response.
:attribute switcher: A dictionary of format types and their respective response methods. | [
"Compares",
"requested",
"format",
"to",
"supported",
"formats",
"and",
"routes",
"the",
"response",
"."
] | 6c58e356af3fbe7b23557643ba27e46eaef9d4e3 | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/views.py#L1340-L1355 |
242,176 | anjos/rrbob | rr/analysis.py | CER | def CER(prediction, true_labels):
"""
Calculates the classification error rate for an N-class classification problem
Parameters:
prediction (numpy.ndarray): A 1D :py:class:`numpy.ndarray` containing your
prediction
true_labels (numpy.ndarray): A 1D :py:class:`numpy.ndarray`
containing the ground t... | python | def CER(prediction, true_labels):
"""
Calculates the classification error rate for an N-class classification problem
Parameters:
prediction (numpy.ndarray): A 1D :py:class:`numpy.ndarray` containing your
prediction
true_labels (numpy.ndarray): A 1D :py:class:`numpy.ndarray`
containing the ground t... | [
"def",
"CER",
"(",
"prediction",
",",
"true_labels",
")",
":",
"errors",
"=",
"(",
"prediction",
"!=",
"true_labels",
")",
".",
"sum",
"(",
")",
"return",
"float",
"(",
"errors",
")",
"/",
"len",
"(",
"prediction",
")"
] | Calculates the classification error rate for an N-class classification problem
Parameters:
prediction (numpy.ndarray): A 1D :py:class:`numpy.ndarray` containing your
prediction
true_labels (numpy.ndarray): A 1D :py:class:`numpy.ndarray`
containing the ground truth labels for the input array, organized... | [
"Calculates",
"the",
"classification",
"error",
"rate",
"for",
"an",
"N",
"-",
"class",
"classification",
"problem"
] | d32d35bab2aa2698d3caa923fd02afb6d67f3235 | https://github.com/anjos/rrbob/blob/d32d35bab2aa2698d3caa923fd02afb6d67f3235/rr/analysis.py#L6-L23 |
242,177 | lvh/axiombench | axiombench/query.py | benchmark | def benchmark(store, n=10000):
"""
Iterates over all of the referreds, and then iterates over all of the
referrers that refer to each one.
Fairly item instantiation heavy.
"""
R = Referrer
for referred in store.query(Referred):
for _reference in store.query(R, R.reference == referr... | python | def benchmark(store, n=10000):
"""
Iterates over all of the referreds, and then iterates over all of the
referrers that refer to each one.
Fairly item instantiation heavy.
"""
R = Referrer
for referred in store.query(Referred):
for _reference in store.query(R, R.reference == referr... | [
"def",
"benchmark",
"(",
"store",
",",
"n",
"=",
"10000",
")",
":",
"R",
"=",
"Referrer",
"for",
"referred",
"in",
"store",
".",
"query",
"(",
"Referred",
")",
":",
"for",
"_reference",
"in",
"store",
".",
"query",
"(",
"R",
",",
"R",
".",
"referen... | Iterates over all of the referreds, and then iterates over all of the
referrers that refer to each one.
Fairly item instantiation heavy. | [
"Iterates",
"over",
"all",
"of",
"the",
"referreds",
"and",
"then",
"iterates",
"over",
"all",
"of",
"the",
"referrers",
"that",
"refer",
"to",
"each",
"one",
"."
] | dd783abfde23b0c67d7a74152d372c4c51e112aa | https://github.com/lvh/axiombench/blob/dd783abfde23b0c67d7a74152d372c4c51e112aa/axiombench/query.py#L21-L32 |
242,178 | deviantony/valigator | valigator/utils.py | generate_uuid | def generate_uuid():
"""Generate a UUID."""
r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)
return r_uuid.decode().replace('=', '') | python | def generate_uuid():
"""Generate a UUID."""
r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)
return r_uuid.decode().replace('=', '') | [
"def",
"generate_uuid",
"(",
")",
":",
"r_uuid",
"=",
"base64",
".",
"urlsafe_b64encode",
"(",
"uuid",
".",
"uuid4",
"(",
")",
".",
"bytes",
")",
"return",
"r_uuid",
".",
"decode",
"(",
")",
".",
"replace",
"(",
"'='",
",",
"''",
")"
] | Generate a UUID. | [
"Generate",
"a",
"UUID",
"."
] | 0557029bc58ea1270e358c14ca382d3807ed5b6f | https://github.com/deviantony/valigator/blob/0557029bc58ea1270e358c14ca382d3807ed5b6f/valigator/utils.py#L9-L12 |
242,179 | deviantony/valigator | valigator/utils.py | extract_archive | def extract_archive(archive_path, destination_path):
"""Extracts an archive somewhere on the filesystem."""
tar = tarfile.open(archive_path)
tar.errorlevel = 1
tar.extractall(destination_path) | python | def extract_archive(archive_path, destination_path):
"""Extracts an archive somewhere on the filesystem."""
tar = tarfile.open(archive_path)
tar.errorlevel = 1
tar.extractall(destination_path) | [
"def",
"extract_archive",
"(",
"archive_path",
",",
"destination_path",
")",
":",
"tar",
"=",
"tarfile",
".",
"open",
"(",
"archive_path",
")",
"tar",
".",
"errorlevel",
"=",
"1",
"tar",
".",
"extractall",
"(",
"destination_path",
")"
] | Extracts an archive somewhere on the filesystem. | [
"Extracts",
"an",
"archive",
"somewhere",
"on",
"the",
"filesystem",
"."
] | 0557029bc58ea1270e358c14ca382d3807ed5b6f | https://github.com/deviantony/valigator/blob/0557029bc58ea1270e358c14ca382d3807ed5b6f/valigator/utils.py#L22-L26 |
242,180 | deviantony/valigator | valigator/utils.py | remove_file | def remove_file(file_path):
"""Remove a file from the filesystem."""
if path.exists(file_path):
try:
rmtree(file_path)
except Exception:
print('Unable to remove temporary workdir {}'.format(file_path)) | python | def remove_file(file_path):
"""Remove a file from the filesystem."""
if path.exists(file_path):
try:
rmtree(file_path)
except Exception:
print('Unable to remove temporary workdir {}'.format(file_path)) | [
"def",
"remove_file",
"(",
"file_path",
")",
":",
"if",
"path",
".",
"exists",
"(",
"file_path",
")",
":",
"try",
":",
"rmtree",
"(",
"file_path",
")",
"except",
"Exception",
":",
"print",
"(",
"'Unable to remove temporary workdir {}'",
".",
"format",
"(",
"... | Remove a file from the filesystem. | [
"Remove",
"a",
"file",
"from",
"the",
"filesystem",
"."
] | 0557029bc58ea1270e358c14ca382d3807ed5b6f | https://github.com/deviantony/valigator/blob/0557029bc58ea1270e358c14ca382d3807ed5b6f/valigator/utils.py#L29-L35 |
242,181 | shaypal5/pdutil | pdutil/iter/iter.py | sub_dfs_by_size | def sub_dfs_by_size(df, size):
"""Get a generator yielding consecutive sub-dataframes of the given size.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
size : int
The size of each sub-dataframe.
Returns
-------
generator
... | python | def sub_dfs_by_size(df, size):
"""Get a generator yielding consecutive sub-dataframes of the given size.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
size : int
The size of each sub-dataframe.
Returns
-------
generator
... | [
"def",
"sub_dfs_by_size",
"(",
"df",
",",
"size",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"df",
")",
",",
"size",
")",
":",
"yield",
"(",
"df",
".",
"iloc",
"[",
"i",
":",
"i",
"+",
"size",
"]",
")"
] | Get a generator yielding consecutive sub-dataframes of the given size.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
size : int
The size of each sub-dataframe.
Returns
-------
generator
A generator yielding consecutive sub-... | [
"Get",
"a",
"generator",
"yielding",
"consecutive",
"sub",
"-",
"dataframes",
"of",
"the",
"given",
"size",
"."
] | 231059634643af2558d22070f89767410978cf56 | https://github.com/shaypal5/pdutil/blob/231059634643af2558d22070f89767410978cf56/pdutil/iter/iter.py#L4-L32 |
242,182 | shaypal5/pdutil | pdutil/iter/iter.py | sub_dfs_by_num | def sub_dfs_by_num(df, num):
"""Get a generator yielding num consecutive sub-dataframes of the given df.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
num : int
The number of sub-dataframe to divide the given dataframe into.
Returns
... | python | def sub_dfs_by_num(df, num):
"""Get a generator yielding num consecutive sub-dataframes of the given df.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
num : int
The number of sub-dataframe to divide the given dataframe into.
Returns
... | [
"def",
"sub_dfs_by_num",
"(",
"df",
",",
"num",
")",
":",
"size",
"=",
"len",
"(",
"df",
")",
"/",
"float",
"(",
"num",
")",
"for",
"i",
"in",
"range",
"(",
"num",
")",
":",
"yield",
"df",
".",
"iloc",
"[",
"int",
"(",
"round",
"(",
"size",
"... | Get a generator yielding num consecutive sub-dataframes of the given df.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
num : int
The number of sub-dataframe to divide the given dataframe into.
Returns
-------
generator
A ge... | [
"Get",
"a",
"generator",
"yielding",
"num",
"consecutive",
"sub",
"-",
"dataframes",
"of",
"the",
"given",
"df",
"."
] | 231059634643af2558d22070f89767410978cf56 | https://github.com/shaypal5/pdutil/blob/231059634643af2558d22070f89767410978cf56/pdutil/iter/iter.py#L35-L64 |
242,183 | ryanjdillon/pylleo | pylleo/utils.py | predict_encoding | def predict_encoding(file_path, n_lines=20):
'''Get file encoding of a text file'''
import chardet
# Open the file as binary data
with open(file_path, 'rb') as f:
# Join binary lines for specified number of lines
rawdata = b''.join([f.readline() for _ in range(n_lines)])
return cha... | python | def predict_encoding(file_path, n_lines=20):
'''Get file encoding of a text file'''
import chardet
# Open the file as binary data
with open(file_path, 'rb') as f:
# Join binary lines for specified number of lines
rawdata = b''.join([f.readline() for _ in range(n_lines)])
return cha... | [
"def",
"predict_encoding",
"(",
"file_path",
",",
"n_lines",
"=",
"20",
")",
":",
"import",
"chardet",
"# Open the file as binary data",
"with",
"open",
"(",
"file_path",
",",
"'rb'",
")",
"as",
"f",
":",
"# Join binary lines for specified number of lines",
"rawdata",... | Get file encoding of a text file | [
"Get",
"file",
"encoding",
"of",
"a",
"text",
"file"
] | b9b999fef19eaeccce4f207ab1b6198287c1bfec | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/utils.py#L15-L24 |
242,184 | ryanjdillon/pylleo | pylleo/utils.py | get_n_header | def get_n_header(f, header_char='"'):
'''Get the nummber of header rows in a Little Leonardo data file
Args
----
f : file stream
File handle for the file from which header rows will be read
header_char: str
Character array at beginning of each header line
Returns
-------
... | python | def get_n_header(f, header_char='"'):
'''Get the nummber of header rows in a Little Leonardo data file
Args
----
f : file stream
File handle for the file from which header rows will be read
header_char: str
Character array at beginning of each header line
Returns
-------
... | [
"def",
"get_n_header",
"(",
"f",
",",
"header_char",
"=",
"'\"'",
")",
":",
"n_header",
"=",
"0",
"reading_headers",
"=",
"True",
"while",
"reading_headers",
":",
"line",
"=",
"f",
".",
"readline",
"(",
")",
"if",
"line",
".",
"startswith",
"(",
"header_... | Get the nummber of header rows in a Little Leonardo data file
Args
----
f : file stream
File handle for the file from which header rows will be read
header_char: str
Character array at beginning of each header line
Returns
-------
n_header: int
Number of header rows... | [
"Get",
"the",
"nummber",
"of",
"header",
"rows",
"in",
"a",
"Little",
"Leonardo",
"data",
"file"
] | b9b999fef19eaeccce4f207ab1b6198287c1bfec | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/utils.py#L27-L52 |
242,185 | ryanjdillon/pylleo | pylleo/utils.py | get_tag_params | def get_tag_params(tag_model):
'''Load param strs and n_header based on model of tag model'''
tag_model = tag_model.replace('-', '')
tags = dict()
tags['W190PD3GT'] = ['Acceleration-X', 'Acceleration-Y', 'Acceleration-Z',
'Depth', 'Propeller', 'Temperature']
# Return tag p... | python | def get_tag_params(tag_model):
'''Load param strs and n_header based on model of tag model'''
tag_model = tag_model.replace('-', '')
tags = dict()
tags['W190PD3GT'] = ['Acceleration-X', 'Acceleration-Y', 'Acceleration-Z',
'Depth', 'Propeller', 'Temperature']
# Return tag p... | [
"def",
"get_tag_params",
"(",
"tag_model",
")",
":",
"tag_model",
"=",
"tag_model",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"tags",
"=",
"dict",
"(",
")",
"tags",
"[",
"'W190PD3GT'",
"]",
"=",
"[",
"'Acceleration-X'",
",",
"'Acceleration-Y'",
",",
"'... | Load param strs and n_header based on model of tag model | [
"Load",
"param",
"strs",
"and",
"n_header",
"based",
"on",
"model",
"of",
"tag",
"model"
] | b9b999fef19eaeccce4f207ab1b6198287c1bfec | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/utils.py#L55-L67 |
242,186 | ryanjdillon/pylleo | pylleo/utils.py | find_file | def find_file(path_dir, search_str, file_ext):
'''Find path of file in directory containing the search string'''
import os
file_path = None
for file_name in os.listdir(path_dir):
if (search_str in file_name) and (file_name.endswith(file_ext)):
file_path = os.path.join(path_dir, fil... | python | def find_file(path_dir, search_str, file_ext):
'''Find path of file in directory containing the search string'''
import os
file_path = None
for file_name in os.listdir(path_dir):
if (search_str in file_name) and (file_name.endswith(file_ext)):
file_path = os.path.join(path_dir, fil... | [
"def",
"find_file",
"(",
"path_dir",
",",
"search_str",
",",
"file_ext",
")",
":",
"import",
"os",
"file_path",
"=",
"None",
"for",
"file_name",
"in",
"os",
".",
"listdir",
"(",
"path_dir",
")",
":",
"if",
"(",
"search_str",
"in",
"file_name",
")",
"and"... | Find path of file in directory containing the search string | [
"Find",
"path",
"of",
"file",
"in",
"directory",
"containing",
"the",
"search",
"string"
] | b9b999fef19eaeccce4f207ab1b6198287c1bfec | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/utils.py#L70-L85 |
242,187 | ryanjdillon/pylleo | pylleo/utils.py | nearest | def nearest(items, pivot):
'''Find nearest value in array, including datetimes
Args
----
items: iterable
List of values from which to find nearest value to `pivot`
pivot: int or float
Value to find nearest of in `items`
Returns
-------
nearest: int or float
Valu... | python | def nearest(items, pivot):
'''Find nearest value in array, including datetimes
Args
----
items: iterable
List of values from which to find nearest value to `pivot`
pivot: int or float
Value to find nearest of in `items`
Returns
-------
nearest: int or float
Valu... | [
"def",
"nearest",
"(",
"items",
",",
"pivot",
")",
":",
"return",
"min",
"(",
"items",
",",
"key",
"=",
"lambda",
"x",
":",
"abs",
"(",
"x",
"-",
"pivot",
")",
")"
] | Find nearest value in array, including datetimes
Args
----
items: iterable
List of values from which to find nearest value to `pivot`
pivot: int or float
Value to find nearest of in `items`
Returns
-------
nearest: int or float
Value in items nearest to `pivot` | [
"Find",
"nearest",
"value",
"in",
"array",
"including",
"datetimes"
] | b9b999fef19eaeccce4f207ab1b6198287c1bfec | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/utils.py#L104-L119 |
242,188 | ryanjdillon/pylleo | pylleo/utils.py | parse_experiment_params | def parse_experiment_params(name_exp):
'''Parse experiment parameters from the data directory name
Args
----
name_exp: str
Name of data directory with experiment parameters
Returns
-------
tag_params: dict of str
Dictionary of parsed experiment parameters
'''
if ('/... | python | def parse_experiment_params(name_exp):
'''Parse experiment parameters from the data directory name
Args
----
name_exp: str
Name of data directory with experiment parameters
Returns
-------
tag_params: dict of str
Dictionary of parsed experiment parameters
'''
if ('/... | [
"def",
"parse_experiment_params",
"(",
"name_exp",
")",
":",
"if",
"(",
"'/'",
"in",
"name_exp",
")",
"or",
"(",
"'\\\\'",
"in",
"name_exp",
")",
":",
"raise",
"ValueError",
"(",
"\"The path {} appears to be a path. Please pass \"",
"\"only the data directory's name (i.... | Parse experiment parameters from the data directory name
Args
----
name_exp: str
Name of data directory with experiment parameters
Returns
-------
tag_params: dict of str
Dictionary of parsed experiment parameters | [
"Parse",
"experiment",
"parameters",
"from",
"the",
"data",
"directory",
"name"
] | b9b999fef19eaeccce4f207ab1b6198287c1bfec | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/utils.py#L122-L147 |
242,189 | sprockets/sprockets.clients.cassandra | sprockets/clients/cassandra/__init__.py | CassandraConnection._get_cassandra_config | def _get_cassandra_config(self):
"""Retrieve a dict containing Cassandra client config params."""
parts = urlsplit(os.environ.get('CASSANDRA_URI', DEFAULT_URI))
if parts.scheme != 'cassandra':
raise RuntimeError(
'CASSANDRA_URI scheme is not "cassandra://"!')
... | python | def _get_cassandra_config(self):
"""Retrieve a dict containing Cassandra client config params."""
parts = urlsplit(os.environ.get('CASSANDRA_URI', DEFAULT_URI))
if parts.scheme != 'cassandra':
raise RuntimeError(
'CASSANDRA_URI scheme is not "cassandra://"!')
... | [
"def",
"_get_cassandra_config",
"(",
"self",
")",
":",
"parts",
"=",
"urlsplit",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'CASSANDRA_URI'",
",",
"DEFAULT_URI",
")",
")",
"if",
"parts",
".",
"scheme",
"!=",
"'cassandra'",
":",
"raise",
"RuntimeError",
"... | Retrieve a dict containing Cassandra client config params. | [
"Retrieve",
"a",
"dict",
"containing",
"Cassandra",
"client",
"config",
"params",
"."
] | c0a3ffe550ceb89b23a59959a0645d29d257e624 | https://github.com/sprockets/sprockets.clients.cassandra/blob/c0a3ffe550ceb89b23a59959a0645d29d257e624/sprockets/clients/cassandra/__init__.py#L59-L73 |
242,190 | sprockets/sprockets.clients.cassandra | sprockets/clients/cassandra/__init__.py | CassandraConnection.prepare | def prepare(self, query, name=None):
"""Create and cache a prepared statement using the provided query.
This function will take a ``query`` and optional ``name`` parameter
and will create a new prepared statement for the provided ``query``.
The resulting statement object will be cached ... | python | def prepare(self, query, name=None):
"""Create and cache a prepared statement using the provided query.
This function will take a ``query`` and optional ``name`` parameter
and will create a new prepared statement for the provided ``query``.
The resulting statement object will be cached ... | [
"def",
"prepare",
"(",
"self",
",",
"query",
",",
"name",
"=",
"None",
")",
":",
"key",
"=",
"name",
"or",
"query",
"stmt",
"=",
"CassandraConnection",
".",
"_prepared_statement_cache",
".",
"get",
"(",
"key",
",",
"None",
")",
"if",
"stmt",
"is",
"not... | Create and cache a prepared statement using the provided query.
This function will take a ``query`` and optional ``name`` parameter
and will create a new prepared statement for the provided ``query``.
The resulting statement object will be cached so future invocations
of this function w... | [
"Create",
"and",
"cache",
"a",
"prepared",
"statement",
"using",
"the",
"provided",
"query",
"."
] | c0a3ffe550ceb89b23a59959a0645d29d257e624 | https://github.com/sprockets/sprockets.clients.cassandra/blob/c0a3ffe550ceb89b23a59959a0645d29d257e624/sprockets/clients/cassandra/__init__.py#L85-L106 |
242,191 | sprockets/sprockets.clients.cassandra | sprockets/clients/cassandra/__init__.py | CassandraConnection.execute | def execute(self, query, *args, **kwargs):
"""Asynchronously execute the specified CQL query.
The execute command also takes optional parameters and trace
keyword arguments. See cassandra-python documentation for
definition of those parameters.
"""
tornado_future = Futur... | python | def execute(self, query, *args, **kwargs):
"""Asynchronously execute the specified CQL query.
The execute command also takes optional parameters and trace
keyword arguments. See cassandra-python documentation for
definition of those parameters.
"""
tornado_future = Futur... | [
"def",
"execute",
"(",
"self",
",",
"query",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tornado_future",
"=",
"Future",
"(",
")",
"cassandra_future",
"=",
"self",
".",
"_session",
".",
"execute_async",
"(",
"query",
",",
"*",
"args",
",",
... | Asynchronously execute the specified CQL query.
The execute command also takes optional parameters and trace
keyword arguments. See cassandra-python documentation for
definition of those parameters. | [
"Asynchronously",
"execute",
"the",
"specified",
"CQL",
"query",
"."
] | c0a3ffe550ceb89b23a59959a0645d29d257e624 | https://github.com/sprockets/sprockets.clients.cassandra/blob/c0a3ffe550ceb89b23a59959a0645d29d257e624/sprockets/clients/cassandra/__init__.py#L108-L119 |
242,192 | cdeboever3/cdpybio | cdpybio/plink.py | read_linear2 | def read_linear2(fn, header=True):
"""Read a plink 2 output file of type glm.linear into a pandas DataFrame.
Parameters
----------
fn : str
Path to the plink file. The file can be gzipped or not.
header : str
True if the file has a header (this is generally the case unless the
... | python | def read_linear2(fn, header=True):
"""Read a plink 2 output file of type glm.linear into a pandas DataFrame.
Parameters
----------
fn : str
Path to the plink file. The file can be gzipped or not.
header : str
True if the file has a header (this is generally the case unless the
... | [
"def",
"read_linear2",
"(",
"fn",
",",
"header",
"=",
"True",
")",
":",
"dtypes",
"=",
"{",
"'#CHROM'",
":",
"str",
",",
"'POS'",
":",
"int",
",",
"'ID'",
":",
"str",
",",
"'REF'",
":",
"str",
",",
"'ALT1'",
":",
"str",
",",
"'TEST'",
":",
"str",... | Read a plink 2 output file of type glm.linear into a pandas DataFrame.
Parameters
----------
fn : str
Path to the plink file. The file can be gzipped or not.
header : str
True if the file has a header (this is generally the case unless the
file has been processed after it was ... | [
"Read",
"a",
"plink",
"2",
"output",
"file",
"of",
"type",
"glm",
".",
"linear",
"into",
"a",
"pandas",
"DataFrame",
"."
] | 38efdf0e11d01bc00a135921cb91a19c03db5d5c | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/plink.py#L6-L45 |
242,193 | cdeboever3/cdpybio | cdpybio/plink.py | parse_log2 | def parse_log2(fn):
"""Parse out some information from a plink 2 log. This function currently
only supports log files from linear or logistic regression.
Parameters
----------
fn : str
Path to the plink log file.
Returns
-------
res : pandas.DataFrame
Dataframe with lo... | python | def parse_log2(fn):
"""Parse out some information from a plink 2 log. This function currently
only supports log files from linear or logistic regression.
Parameters
----------
fn : str
Path to the plink log file.
Returns
-------
res : pandas.DataFrame
Dataframe with lo... | [
"def",
"parse_log2",
"(",
"fn",
")",
":",
"with",
"open",
"(",
"fn",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"if",
"len",
"(",
"lines",
")",
"==",
"0",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Empty log file: {}... | Parse out some information from a plink 2 log. This function currently
only supports log files from linear or logistic regression.
Parameters
----------
fn : str
Path to the plink log file.
Returns
-------
res : pandas.DataFrame
Dataframe with log file information. | [
"Parse",
"out",
"some",
"information",
"from",
"a",
"plink",
"2",
"log",
".",
"This",
"function",
"currently",
"only",
"supports",
"log",
"files",
"from",
"linear",
"or",
"logistic",
"regression",
"."
] | 38efdf0e11d01bc00a135921cb91a19c03db5d5c | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/plink.py#L99-L151 |
242,194 | shaypal5/pdutil | pdutil/transform/transform.py | x_y_by_col_lbl | def x_y_by_col_lbl(df, y_col_lbl):
"""Returns an X dataframe and a y series by the given column name.
Parameters
----------
df : pandas.DataFrame
The dataframe to split.
y_col_lbl : object
The label of the y column.
Returns
-------
X, y : pandas.DataFrame, pandas.Series... | python | def x_y_by_col_lbl(df, y_col_lbl):
"""Returns an X dataframe and a y series by the given column name.
Parameters
----------
df : pandas.DataFrame
The dataframe to split.
y_col_lbl : object
The label of the y column.
Returns
-------
X, y : pandas.DataFrame, pandas.Series... | [
"def",
"x_y_by_col_lbl",
"(",
"df",
",",
"y_col_lbl",
")",
":",
"x_cols",
"=",
"[",
"col",
"for",
"col",
"in",
"df",
".",
"columns",
"if",
"col",
"!=",
"y_col_lbl",
"]",
"return",
"df",
"[",
"x_cols",
"]",
",",
"df",
"[",
"y_col_lbl",
"]"
] | Returns an X dataframe and a y series by the given column name.
Parameters
----------
df : pandas.DataFrame
The dataframe to split.
y_col_lbl : object
The label of the y column.
Returns
-------
X, y : pandas.DataFrame, pandas.Series
A dataframe made up of all column... | [
"Returns",
"an",
"X",
"dataframe",
"and",
"a",
"y",
"series",
"by",
"the",
"given",
"column",
"name",
"."
] | 231059634643af2558d22070f89767410978cf56 | https://github.com/shaypal5/pdutil/blob/231059634643af2558d22070f89767410978cf56/pdutil/transform/transform.py#L4-L36 |
242,195 | shaypal5/pdutil | pdutil/transform/transform.py | x_y_by_col_lbl_inplace | def x_y_by_col_lbl_inplace(df, y_col_lbl):
"""Breaks the given dataframe into an X frame and a y series by the given
column name.
The original frame is returned, without the y series column, as the X
frame, so no new dataframes are created.
Parameters
----------
df : pandas.DataFrame
... | python | def x_y_by_col_lbl_inplace(df, y_col_lbl):
"""Breaks the given dataframe into an X frame and a y series by the given
column name.
The original frame is returned, without the y series column, as the X
frame, so no new dataframes are created.
Parameters
----------
df : pandas.DataFrame
... | [
"def",
"x_y_by_col_lbl_inplace",
"(",
"df",
",",
"y_col_lbl",
")",
":",
"y",
"=",
"df",
"[",
"y_col_lbl",
"]",
"df",
".",
"drop",
"(",
"labels",
"=",
"y_col_lbl",
",",
"axis",
"=",
"1",
",",
"inplace",
"=",
"True",
",",
")",
"return",
"df",
",",
"y... | Breaks the given dataframe into an X frame and a y series by the given
column name.
The original frame is returned, without the y series column, as the X
frame, so no new dataframes are created.
Parameters
----------
df : pandas.DataFrame
The dataframe to split.
y_col_lbl : object... | [
"Breaks",
"the",
"given",
"dataframe",
"into",
"an",
"X",
"frame",
"and",
"a",
"y",
"series",
"by",
"the",
"given",
"column",
"name",
"."
] | 231059634643af2558d22070f89767410978cf56 | https://github.com/shaypal5/pdutil/blob/231059634643af2558d22070f89767410978cf56/pdutil/transform/transform.py#L39-L80 |
242,196 | shaypal5/pdutil | pdutil/transform/transform.py | or_by_masks | def or_by_masks(df, masks):
"""Returns a sub-dataframe by the logical or over the given masks.
Parameters
----------
df : pandas.DataFrame
The dataframe to take a subframe of.
masks : list
A list of pandas.Series of dtype bool, indexed identically to the given
dataframe.
... | python | def or_by_masks(df, masks):
"""Returns a sub-dataframe by the logical or over the given masks.
Parameters
----------
df : pandas.DataFrame
The dataframe to take a subframe of.
masks : list
A list of pandas.Series of dtype bool, indexed identically to the given
dataframe.
... | [
"def",
"or_by_masks",
"(",
"df",
",",
"masks",
")",
":",
"if",
"len",
"(",
"masks",
")",
"<",
"1",
":",
"return",
"df",
"if",
"len",
"(",
"masks",
")",
"==",
"1",
":",
"return",
"df",
"[",
"masks",
"[",
"0",
"]",
"]",
"overall_mask",
"=",
"mask... | Returns a sub-dataframe by the logical or over the given masks.
Parameters
----------
df : pandas.DataFrame
The dataframe to take a subframe of.
masks : list
A list of pandas.Series of dtype bool, indexed identically to the given
dataframe.
Returns
-------
pandas.Da... | [
"Returns",
"a",
"sub",
"-",
"dataframe",
"by",
"the",
"logical",
"or",
"over",
"the",
"given",
"masks",
"."
] | 231059634643af2558d22070f89767410978cf56 | https://github.com/shaypal5/pdutil/blob/231059634643af2558d22070f89767410978cf56/pdutil/transform/transform.py#L83-L118 |
242,197 | MacHu-GWU/angora-project | angora/visual/timeseries.py | visualize | def visualize(x, y, xlabel=None, ylabel=None, title=None, ylim=None):
"""A universal function plot arbitrary time series data.
"""
total_seconds = (x[-1] - x[0]).total_seconds()
if total_seconds <= 86400 * 1 * 3:
return plot_one_day(x, y, xlabel, ylabel, title, ylim)
elif total_seconds ... | python | def visualize(x, y, xlabel=None, ylabel=None, title=None, ylim=None):
"""A universal function plot arbitrary time series data.
"""
total_seconds = (x[-1] - x[0]).total_seconds()
if total_seconds <= 86400 * 1 * 3:
return plot_one_day(x, y, xlabel, ylabel, title, ylim)
elif total_seconds ... | [
"def",
"visualize",
"(",
"x",
",",
"y",
",",
"xlabel",
"=",
"None",
",",
"ylabel",
"=",
"None",
",",
"title",
"=",
"None",
",",
"ylim",
"=",
"None",
")",
":",
"total_seconds",
"=",
"(",
"x",
"[",
"-",
"1",
"]",
"-",
"x",
"[",
"0",
"]",
")",
... | A universal function plot arbitrary time series data. | [
"A",
"universal",
"function",
"plot",
"arbitrary",
"time",
"series",
"data",
"."
] | 689a60da51cd88680ddbe26e28dbe81e6b01d275 | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/visual/timeseries.py#L281-L298 |
242,198 | andy-esch/sqterritory | sqterritory/territory.py | MinCostFlow._get_demand_graph | def _get_demand_graph(self):
"""create demand graph"""
# The number of clusters
K = self.origins.shape[0]
# Set the number of accounts in each cluster to be the same
# as for the nearest neighbor solution
demand = self.nearest_targets.groupby('origin_id')['geometry'].cou... | python | def _get_demand_graph(self):
"""create demand graph"""
# The number of clusters
K = self.origins.shape[0]
# Set the number of accounts in each cluster to be the same
# as for the nearest neighbor solution
demand = self.nearest_targets.groupby('origin_id')['geometry'].cou... | [
"def",
"_get_demand_graph",
"(",
"self",
")",
":",
"# The number of clusters",
"K",
"=",
"self",
".",
"origins",
".",
"shape",
"[",
"0",
"]",
"# Set the number of accounts in each cluster to be the same",
"# as for the nearest neighbor solution",
"demand",
"=",
"self",
".... | create demand graph | [
"create",
"demand",
"graph"
] | 53bcf7c8946f5d216d1ceccf55f9f339125b8205 | https://github.com/andy-esch/sqterritory/blob/53bcf7c8946f5d216d1ceccf55f9f339125b8205/sqterritory/territory.py#L104-L137 |
242,199 | andy-esch/sqterritory | sqterritory/territory.py | MinCostFlow.results_to_table | def results_to_table(self):
"""Process self.results and send to carto table"""
# Get Labels
baseline_labels = self.nearest_targets['origin_id'].values
mcf_labels = self.results['model_labels']['labels'].values
# Create the outcomes
outcome = pd.DataFrame({
... | python | def results_to_table(self):
"""Process self.results and send to carto table"""
# Get Labels
baseline_labels = self.nearest_targets['origin_id'].values
mcf_labels = self.results['model_labels']['labels'].values
# Create the outcomes
outcome = pd.DataFrame({
... | [
"def",
"results_to_table",
"(",
"self",
")",
":",
"# Get Labels",
"baseline_labels",
"=",
"self",
".",
"nearest_targets",
"[",
"'origin_id'",
"]",
".",
"values",
"mcf_labels",
"=",
"self",
".",
"results",
"[",
"'model_labels'",
"]",
"[",
"'labels'",
"]",
".",
... | Process self.results and send to carto table | [
"Process",
"self",
".",
"results",
"and",
"send",
"to",
"carto",
"table"
] | 53bcf7c8946f5d216d1ceccf55f9f339125b8205 | https://github.com/andy-esch/sqterritory/blob/53bcf7c8946f5d216d1ceccf55f9f339125b8205/sqterritory/territory.py#L280-L324 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.