repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 3
values | summary stringlengths 4 350 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
tjcsl/cslbot | cslbot/commands/channels.py | cmd | def cmd(send, _, args):
"""Returns a listing of the current channels.
Syntax: {command}
"""
with args['handler'].data_lock:
channels = ", ".join(sorted(args['handler'].channels))
send(channels) | python | def cmd(send, _, args):
"""Returns a listing of the current channels.
Syntax: {command}
"""
with args['handler'].data_lock:
channels = ", ".join(sorted(args['handler'].channels))
send(channels) | [
"def",
"cmd",
"(",
"send",
",",
"_",
",",
"args",
")",
":",
"with",
"args",
"[",
"'handler'",
"]",
".",
"data_lock",
":",
"channels",
"=",
"\", \"",
".",
"join",
"(",
"sorted",
"(",
"args",
"[",
"'handler'",
"]",
".",
"channels",
")",
")",
"send",
... | Returns a listing of the current channels.
Syntax: {command} | [
"Returns",
"a",
"listing",
"of",
"the",
"current",
"channels",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/channels.py#L22-L30 | train | Returns a listing of the current channels. |
tjcsl/cslbot | cslbot/commands/stock.py | cmd | def cmd(send, msg, args):
"""Gets a stock quote.
Syntax: {command} [symbol]
Powered by markit on demand (http://dev.markitondemand.com)
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('stock', nargs='?', default=random_stock())
try:
cmdargs = parser.parse_args(... | python | def cmd(send, msg, args):
"""Gets a stock quote.
Syntax: {command} [symbol]
Powered by markit on demand (http://dev.markitondemand.com)
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('stock', nargs='?', default=random_stock())
try:
cmdargs = parser.parse_args(... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'stock'",
",",
"nargs",
"=",
"'?'",
",",
"default",
"=",
"random_... | Gets a stock quote.
Syntax: {command} [symbol]
Powered by markit on demand (http://dev.markitondemand.com) | [
"Gets",
"a",
"stock",
"quote",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/stock.py#L48-L62 | train | Gets a stock quote. |
The-Politico/politico-civic-election-night | electionnight/serializers/state.py | StateSerializer.get_division | def get_division(self, obj):
"""Division."""
if obj.level.name == DivisionLevel.DISTRICT:
return DivisionSerializer(obj.parent).data
return DivisionSerializer(obj).data | python | def get_division(self, obj):
"""Division."""
if obj.level.name == DivisionLevel.DISTRICT:
return DivisionSerializer(obj.parent).data
return DivisionSerializer(obj).data | [
"def",
"get_division",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
".",
"level",
".",
"name",
"==",
"DivisionLevel",
".",
"DISTRICT",
":",
"return",
"DivisionSerializer",
"(",
"obj",
".",
"parent",
")",
".",
"data",
"return",
"DivisionSerializer",
"(",... | Division. | [
"Division",
"."
] | a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/state.py#L41-L46 | train | Returns the data for a Division. |
The-Politico/politico-civic-election-night | electionnight/serializers/state.py | StateSerializer.get_elections | def get_elections(self, obj):
"""All elections in division."""
election_day = ElectionDay.objects.get(
date=self.context['election_date'])
elections = list(obj.elections.filter(election_day=election_day))
district = DivisionLevel.objects.get(name=DivisionLevel.DISTRICT)
... | python | def get_elections(self, obj):
"""All elections in division."""
election_day = ElectionDay.objects.get(
date=self.context['election_date'])
elections = list(obj.elections.filter(election_day=election_day))
district = DivisionLevel.objects.get(name=DivisionLevel.DISTRICT)
... | [
"def",
"get_elections",
"(",
"self",
",",
"obj",
")",
":",
"election_day",
"=",
"ElectionDay",
".",
"objects",
".",
"get",
"(",
"date",
"=",
"self",
".",
"context",
"[",
"'election_date'",
"]",
")",
"elections",
"=",
"list",
"(",
"obj",
".",
"elections",... | All elections in division. | [
"All",
"elections",
"in",
"division",
"."
] | a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/state.py#L52-L67 | train | All elections in division. |
The-Politico/politico-civic-election-night | electionnight/serializers/state.py | StateSerializer.get_content | def get_content(self, obj):
"""All content for a state's page on an election day."""
election_day = ElectionDay.objects.get(
date=self.context['election_date'])
division = obj
# In case of house special election,
# use parent division.
if obj.level.name == Div... | python | def get_content(self, obj):
"""All content for a state's page on an election day."""
election_day = ElectionDay.objects.get(
date=self.context['election_date'])
division = obj
# In case of house special election,
# use parent division.
if obj.level.name == Div... | [
"def",
"get_content",
"(",
"self",
",",
"obj",
")",
":",
"election_day",
"=",
"ElectionDay",
".",
"objects",
".",
"get",
"(",
"date",
"=",
"self",
".",
"context",
"[",
"'election_date'",
"]",
")",
"division",
"=",
"obj",
"# In case of house special election,",... | All content for a state's page on an election day. | [
"All",
"content",
"for",
"a",
"state",
"s",
"page",
"on",
"an",
"election",
"day",
"."
] | a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/state.py#L69-L85 | train | All content for a state s page on an election day. |
The-Politico/politico-civic-election-night | electionnight/management/commands/methods/bootstrap/executive_office.py | ExecutiveOffice.bootstrap_executive_office | def bootstrap_executive_office(self, election):
"""
For executive offices, create page content for the office.
For the president, create pages for each state result.
"""
division = election.race.office.jurisdiction.division
content_type = ContentType.objects.get_for_mode... | python | def bootstrap_executive_office(self, election):
"""
For executive offices, create page content for the office.
For the president, create pages for each state result.
"""
division = election.race.office.jurisdiction.division
content_type = ContentType.objects.get_for_mode... | [
"def",
"bootstrap_executive_office",
"(",
"self",
",",
"election",
")",
":",
"division",
"=",
"election",
".",
"race",
".",
"office",
".",
"jurisdiction",
".",
"division",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"election",... | For executive offices, create page content for the office.
For the president, create pages for each state result. | [
"For",
"executive",
"offices",
"create",
"page",
"content",
"for",
"the",
"office",
"."
] | a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/management/commands/methods/bootstrap/executive_office.py#L10-L63 | train | Create page content for executive offices. |
tjcsl/cslbot | cslbot/commands/imdb.py | cmd | def cmd(send, msg, args):
"""Gets a random movie.
Syntax: {command}
"""
req = get('http://www.imdb.com/random/title')
html = fromstring(req.text)
name = html.find('head/title').text.split('-')[0].strip()
key = args['config']['api']['bitlykey']
send("%s -- %s" % (name, get_short(req.ur... | python | def cmd(send, msg, args):
"""Gets a random movie.
Syntax: {command}
"""
req = get('http://www.imdb.com/random/title')
html = fromstring(req.text)
name = html.find('head/title').text.split('-')[0].strip()
key = args['config']['api']['bitlykey']
send("%s -- %s" % (name, get_short(req.ur... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"req",
"=",
"get",
"(",
"'http://www.imdb.com/random/title'",
")",
"html",
"=",
"fromstring",
"(",
"req",
".",
"text",
")",
"name",
"=",
"html",
".",
"find",
"(",
"'head/title'",
")",
".",
... | Gets a random movie.
Syntax: {command} | [
"Gets",
"a",
"random",
"movie",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/imdb.py#L27-L38 | train | Gets a random movie.
|
adamziel/python_translate | python_translate/selector.py | select_message | def select_message(message, number, locale):
"""
Given a message with different plural translations separated by a
pipe (|), this method returns the correct portion of the message based
on the given number, locale and the pluralization rules in the message
itself.
The message supports two diffe... | python | def select_message(message, number, locale):
"""
Given a message with different plural translations separated by a
pipe (|), this method returns the correct portion of the message based
on the given number, locale and the pluralization rules in the message
itself.
The message supports two diffe... | [
"def",
"select_message",
"(",
"message",
",",
"number",
",",
"locale",
")",
":",
"parts",
"=",
"message",
".",
"split",
"(",
"\"|\"",
")",
"explicit_rules",
"=",
"OrderedDict",
"(",
")",
"standard_rules",
"=",
"[",
"]",
"for",
"part",
"in",
"parts",
":",... | Given a message with different plural translations separated by a
pipe (|), this method returns the correct portion of the message based
on the given number, locale and the pluralization rules in the message
itself.
The message supports two different types of pluralization rules:
interval: {0} The... | [
"Given",
"a",
"message",
"with",
"different",
"plural",
"translations",
"separated",
"by",
"a",
"pipe",
"(",
"|",
")",
"this",
"method",
"returns",
"the",
"correct",
"portion",
"of",
"the",
"message",
"based",
"on",
"the",
"given",
"number",
"locale",
"and",... | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/selector.py#L67-L128 | train | This method returns the correct portion of the message based on the given number and locale. |
adamziel/python_translate | python_translate/selector.py | PluralizationRules.get | def get(number, locale):
"""
Returns the plural position to use for the given locale and number.
@type number: int
@param number: The number
@type locale: str
@param locale: The locale
@rtype: int
@return: The plural position
"""
if loca... | python | def get(number, locale):
"""
Returns the plural position to use for the given locale and number.
@type number: int
@param number: The number
@type locale: str
@param locale: The locale
@rtype: int
@return: The plural position
"""
if loca... | [
"def",
"get",
"(",
"number",
",",
"locale",
")",
":",
"if",
"locale",
"==",
"'pt_BR'",
":",
"# temporary set a locale for brazilian",
"locale",
"=",
"'xbr'",
"if",
"len",
"(",
"locale",
")",
">",
"3",
":",
"locale",
"=",
"locale",
".",
"split",
"(",
"\"_... | Returns the plural position to use for the given locale and number.
@type number: int
@param number: The number
@type locale: str
@param locale: The locale
@rtype: int
@return: The plural position | [
"Returns",
"the",
"plural",
"position",
"to",
"use",
"for",
"the",
"given",
"locale",
"and",
"number",
"."
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/selector.py#L242-L266 | train | Returns the plural position to use for the given locale and number. |
adamziel/python_translate | python_translate/selector.py | PluralizationRules.set | def set(rule, locale):
"""
Overrides the default plural rule for a given locale.
@type rule: str
@param rule: Callable
@type locale: str
@param locale: The locale
@raises: ValueError
"""
if locale == 'pt_BR':
# temporary set a local... | python | def set(rule, locale):
"""
Overrides the default plural rule for a given locale.
@type rule: str
@param rule: Callable
@type locale: str
@param locale: The locale
@raises: ValueError
"""
if locale == 'pt_BR':
# temporary set a local... | [
"def",
"set",
"(",
"rule",
",",
"locale",
")",
":",
"if",
"locale",
"==",
"'pt_BR'",
":",
"# temporary set a locale for brazilian",
"locale",
"=",
"'xbr'",
"if",
"len",
"(",
"locale",
")",
">",
"3",
":",
"locale",
"=",
"locale",
".",
"split",
"(",
"\"_\"... | Overrides the default plural rule for a given locale.
@type rule: str
@param rule: Callable
@type locale: str
@param locale: The locale
@raises: ValueError | [
"Overrides",
"the",
"default",
"plural",
"rule",
"for",
"a",
"given",
"locale",
"."
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/selector.py#L269-L292 | train | Sets the given plural rule for a given locale. |
tjcsl/cslbot | cslbot/commands/acronym.py | cmd | def cmd(send, msg, _):
"""Generates a meaning for the specified acronym.
Syntax: {command} <acronym>
"""
if not msg:
send("What acronym?")
return
words = get_list()
letters = [c for c in msg.lower() if c in string.ascii_lowercase]
output = " ".join([choice(words[c]) for c i... | python | def cmd(send, msg, _):
"""Generates a meaning for the specified acronym.
Syntax: {command} <acronym>
"""
if not msg:
send("What acronym?")
return
words = get_list()
letters = [c for c in msg.lower() if c in string.ascii_lowercase]
output = " ".join([choice(words[c]) for c i... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"_",
")",
":",
"if",
"not",
"msg",
":",
"send",
"(",
"\"What acronym?\"",
")",
"return",
"words",
"=",
"get_list",
"(",
")",
"letters",
"=",
"[",
"c",
"for",
"c",
"in",
"msg",
".",
"lower",
"(",
")",
... | Generates a meaning for the specified acronym.
Syntax: {command} <acronym> | [
"Generates",
"a",
"meaning",
"for",
"the",
"specified",
"acronym",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/acronym.py#L36-L51 | train | Generates a meaning for the specified acronym. |
brandjon/simplestruct | simplestruct/struct.py | MetaStruct.get_boundargs | def get_boundargs(cls, *args, **kargs):
"""Return an inspect.BoundArguments object for the application
of this Struct's signature to its arguments. Add missing values
for default fields as keyword arguments.
"""
boundargs = cls._signature.bind(*args, **kargs)
# Include de... | python | def get_boundargs(cls, *args, **kargs):
"""Return an inspect.BoundArguments object for the application
of this Struct's signature to its arguments. Add missing values
for default fields as keyword arguments.
"""
boundargs = cls._signature.bind(*args, **kargs)
# Include de... | [
"def",
"get_boundargs",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"boundargs",
"=",
"cls",
".",
"_signature",
".",
"bind",
"(",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
"# Include default arguments.",
"for",
"param",
"in",
"cls",... | Return an inspect.BoundArguments object for the application
of this Struct's signature to its arguments. Add missing values
for default fields as keyword arguments. | [
"Return",
"an",
"inspect",
".",
"BoundArguments",
"object",
"for",
"the",
"application",
"of",
"this",
"Struct",
"s",
"signature",
"to",
"its",
"arguments",
".",
"Add",
"missing",
"values",
"for",
"default",
"fields",
"as",
"keyword",
"arguments",
"."
] | f2bba77278838b5904fd72b35741da162f337c37 | https://github.com/brandjon/simplestruct/blob/f2bba77278838b5904fd72b35741da162f337c37/simplestruct/struct.py#L148-L159 | train | Return an inspect. BoundArguments object for the application
of this Struct s signature to its arguments. |
brandjon/simplestruct | simplestruct/struct.py | Struct._asdict | def _asdict(self):
"""Return an OrderedDict of the fields."""
return OrderedDict((f.name, getattr(self, f.name))
for f in self._struct) | python | def _asdict(self):
"""Return an OrderedDict of the fields."""
return OrderedDict((f.name, getattr(self, f.name))
for f in self._struct) | [
"def",
"_asdict",
"(",
"self",
")",
":",
"return",
"OrderedDict",
"(",
"(",
"f",
".",
"name",
",",
"getattr",
"(",
"self",
",",
"f",
".",
"name",
")",
")",
"for",
"f",
"in",
"self",
".",
"_struct",
")"
] | Return an OrderedDict of the fields. | [
"Return",
"an",
"OrderedDict",
"of",
"the",
"fields",
"."
] | f2bba77278838b5904fd72b35741da162f337c37 | https://github.com/brandjon/simplestruct/blob/f2bba77278838b5904fd72b35741da162f337c37/simplestruct/struct.py#L305-L308 | train | Return an OrderedDict of the fields. |
brandjon/simplestruct | simplestruct/struct.py | Struct._replace | def _replace(self, **kargs):
"""Return a copy of this Struct with the same fields except
with the changes specified by kargs.
"""
fields = {f.name: getattr(self, f.name)
for f in self._struct}
fields.update(kargs)
return type(self)(**fields) | python | def _replace(self, **kargs):
"""Return a copy of this Struct with the same fields except
with the changes specified by kargs.
"""
fields = {f.name: getattr(self, f.name)
for f in self._struct}
fields.update(kargs)
return type(self)(**fields) | [
"def",
"_replace",
"(",
"self",
",",
"*",
"*",
"kargs",
")",
":",
"fields",
"=",
"{",
"f",
".",
"name",
":",
"getattr",
"(",
"self",
",",
"f",
".",
"name",
")",
"for",
"f",
"in",
"self",
".",
"_struct",
"}",
"fields",
".",
"update",
"(",
"kargs... | Return a copy of this Struct with the same fields except
with the changes specified by kargs. | [
"Return",
"a",
"copy",
"of",
"this",
"Struct",
"with",
"the",
"same",
"fields",
"except",
"with",
"the",
"changes",
"specified",
"by",
"kargs",
"."
] | f2bba77278838b5904fd72b35741da162f337c37 | https://github.com/brandjon/simplestruct/blob/f2bba77278838b5904fd72b35741da162f337c37/simplestruct/struct.py#L310-L317 | train | Return a copy of this Struct with the same fields except
with the changes specified by kargs. |
comparnion/mysqldbhelper | mysqldbhelper/__init__.py | DatabaseConnection.get_one | def get_one(self, qry, tpl):
''' get a single from from a query
limit 1 is automatically added '''
self.cur.execute(qry + ' LIMIT 1', tpl)
result = self.cur.fetchone()
# unpack tuple if it has only
# one element
# TODO unpack results
if type(result) is tup... | python | def get_one(self, qry, tpl):
''' get a single from from a query
limit 1 is automatically added '''
self.cur.execute(qry + ' LIMIT 1', tpl)
result = self.cur.fetchone()
# unpack tuple if it has only
# one element
# TODO unpack results
if type(result) is tup... | [
"def",
"get_one",
"(",
"self",
",",
"qry",
",",
"tpl",
")",
":",
"self",
".",
"cur",
".",
"execute",
"(",
"qry",
"+",
"' LIMIT 1'",
",",
"tpl",
")",
"result",
"=",
"self",
".",
"cur",
".",
"fetchone",
"(",
")",
"# unpack tuple if it has only",
"# one e... | get a single from from a query
limit 1 is automatically added | [
"get",
"a",
"single",
"from",
"from",
"a",
"query",
"limit",
"1",
"is",
"automatically",
"added"
] | 9320df20b77b181fde277b33730954611d41846f | https://github.com/comparnion/mysqldbhelper/blob/9320df20b77b181fde277b33730954611d41846f/mysqldbhelper/__init__.py#L68-L78 | train | get a single from a query
|
comparnion/mysqldbhelper | mysqldbhelper/__init__.py | DatabaseConnection.get_all | def get_all(self, qry, tpl):
''' get all rows for a query '''
self.cur.execute(qry, tpl)
result = self.cur.fetchall()
return result | python | def get_all(self, qry, tpl):
''' get all rows for a query '''
self.cur.execute(qry, tpl)
result = self.cur.fetchall()
return result | [
"def",
"get_all",
"(",
"self",
",",
"qry",
",",
"tpl",
")",
":",
"self",
".",
"cur",
".",
"execute",
"(",
"qry",
",",
"tpl",
")",
"result",
"=",
"self",
".",
"cur",
".",
"fetchall",
"(",
")",
"return",
"result"
] | get all rows for a query | [
"get",
"all",
"rows",
"for",
"a",
"query"
] | 9320df20b77b181fde277b33730954611d41846f | https://github.com/comparnion/mysqldbhelper/blob/9320df20b77b181fde277b33730954611d41846f/mysqldbhelper/__init__.py#L81-L85 | train | get all rows for a query |
Genida/archan | src/archan/logging.py | Logger.set_level | def set_level(level):
"""
Set level of logging for all loggers.
Args:
level (int): level of logging.
"""
Logger.level = level
for logger in Logger.loggers.values():
logger.setLevel(level) | python | def set_level(level):
"""
Set level of logging for all loggers.
Args:
level (int): level of logging.
"""
Logger.level = level
for logger in Logger.loggers.values():
logger.setLevel(level) | [
"def",
"set_level",
"(",
"level",
")",
":",
"Logger",
".",
"level",
"=",
"level",
"for",
"logger",
"in",
"Logger",
".",
"loggers",
".",
"values",
"(",
")",
":",
"logger",
".",
"setLevel",
"(",
"level",
")"
] | Set level of logging for all loggers.
Args:
level (int): level of logging. | [
"Set",
"level",
"of",
"logging",
"for",
"all",
"loggers",
"."
] | a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/logging.py#L19-L28 | train | Sets the level of logging for all loggers. |
Genida/archan | src/archan/logging.py | Logger.get_logger | def get_logger(name, level=None, fmt=':%(lineno)d: %(message)s'):
"""
Return a logger.
Args:
name (str): name to pass to the logging module.
level (int): level of logging.
fmt (str): format string.
Returns:
logging.Logger: logger from ``l... | python | def get_logger(name, level=None, fmt=':%(lineno)d: %(message)s'):
"""
Return a logger.
Args:
name (str): name to pass to the logging module.
level (int): level of logging.
fmt (str): format string.
Returns:
logging.Logger: logger from ``l... | [
"def",
"get_logger",
"(",
"name",
",",
"level",
"=",
"None",
",",
"fmt",
"=",
"':%(lineno)d: %(message)s'",
")",
":",
"if",
"name",
"not",
"in",
"Logger",
".",
"loggers",
":",
"if",
"Logger",
".",
"level",
"is",
"None",
"and",
"level",
"is",
"None",
":... | Return a logger.
Args:
name (str): name to pass to the logging module.
level (int): level of logging.
fmt (str): format string.
Returns:
logging.Logger: logger from ``logging.getLogger``. | [
"Return",
"a",
"logger",
"."
] | a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/logging.py#L31-L56 | train | Returns a logger object. |
Genida/archan | src/archan/logging.py | LoggingFormatter.format | def format(self, record):
"""Override default format method."""
if record.levelno == logging.DEBUG:
string = Back.WHITE + Fore.BLACK + ' debug '
elif record.levelno == logging.INFO:
string = Back.BLUE + Fore.WHITE + ' info '
elif record.levelno == logging.WARNING:... | python | def format(self, record):
"""Override default format method."""
if record.levelno == logging.DEBUG:
string = Back.WHITE + Fore.BLACK + ' debug '
elif record.levelno == logging.INFO:
string = Back.BLUE + Fore.WHITE + ' info '
elif record.levelno == logging.WARNING:... | [
"def",
"format",
"(",
"self",
",",
"record",
")",
":",
"if",
"record",
".",
"levelno",
"==",
"logging",
".",
"DEBUG",
":",
"string",
"=",
"Back",
".",
"WHITE",
"+",
"Fore",
".",
"BLACK",
"+",
"' debug '",
"elif",
"record",
".",
"levelno",
"==",
"logg... | Override default format method. | [
"Override",
"default",
"format",
"method",
"."
] | a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/logging.py#L62-L77 | train | Override default format method. |
tjcsl/cslbot | cslbot/helpers/sql.py | Sql.session_scope | def session_scope(self):
"""Provide a transactional scope around a series of operations."""
session = self.session()
try:
yield session
session.commit()
except Exception as e:
session.rollback()
raise e
finally:
session.... | python | def session_scope(self):
"""Provide a transactional scope around a series of operations."""
session = self.session()
try:
yield session
session.commit()
except Exception as e:
session.rollback()
raise e
finally:
session.... | [
"def",
"session_scope",
"(",
"self",
")",
":",
"session",
"=",
"self",
".",
"session",
"(",
")",
"try",
":",
"yield",
"session",
"session",
".",
"commit",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"session",
".",
"rollback",
"(",
")",
"raise",
... | Provide a transactional scope around a series of operations. | [
"Provide",
"a",
"transactional",
"scope",
"around",
"a",
"series",
"of",
"operations",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/sql.py#L50-L60 | train | Provide a transactional scope around a series of operations. |
tjcsl/cslbot | cslbot/helpers/sql.py | Sql.log | def log(self, source: str, target: str, flags: int, msg: str, mtype: str) -> None:
"""Logs a message to the database.
| source: The source of the message.
| target: The target of the message.
| flags: Is the user a operator or voiced?
| msg: The text of the message.
| ms... | python | def log(self, source: str, target: str, flags: int, msg: str, mtype: str) -> None:
"""Logs a message to the database.
| source: The source of the message.
| target: The target of the message.
| flags: Is the user a operator or voiced?
| msg: The text of the message.
| ms... | [
"def",
"log",
"(",
"self",
",",
"source",
":",
"str",
",",
"target",
":",
"str",
",",
"flags",
":",
"int",
",",
"msg",
":",
"str",
",",
"mtype",
":",
"str",
")",
"->",
"None",
":",
"entry",
"=",
"Log",
"(",
"source",
"=",
"str",
"(",
"source",
... | Logs a message to the database.
| source: The source of the message.
| target: The target of the message.
| flags: Is the user a operator or voiced?
| msg: The text of the message.
| msg: The type of message.
| time: The current time (Unix Epoch). | [
"Logs",
"a",
"message",
"to",
"the",
"database",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/sql.py#L62-L76 | train | Logs a message to the database. |
CI-WATER/mapkit | mapkit/GeometryConverter.py | GeometryConverter.getPointAsKmlCircle | def getPointAsKmlCircle(self, tableName, radius, slices=25, extrude=0, zScaleFactor=1.0, geometryId=1,
geometryIdFieldName='id', geometryFieldName='geometry'):
"""
Return a string representing a circular polygon in KML format with center at the coordinates of the point
... | python | def getPointAsKmlCircle(self, tableName, radius, slices=25, extrude=0, zScaleFactor=1.0, geometryId=1,
geometryIdFieldName='id', geometryFieldName='geometry'):
"""
Return a string representing a circular polygon in KML format with center at the coordinates of the point
... | [
"def",
"getPointAsKmlCircle",
"(",
"self",
",",
"tableName",
",",
"radius",
",",
"slices",
"=",
"25",
",",
"extrude",
"=",
"0",
",",
"zScaleFactor",
"=",
"1.0",
",",
"geometryId",
"=",
"1",
",",
"geometryIdFieldName",
"=",
"'id'",
",",
"geometryFieldName",
... | Return a string representing a circular polygon in KML format with center at the coordinates of the point
and radius as specified. | [
"Return",
"a",
"string",
"representing",
"a",
"circular",
"polygon",
"in",
"KML",
"format",
"with",
"center",
"at",
"the",
"coordinates",
"of",
"the",
"point",
"and",
"radius",
"as",
"specified",
"."
] | ce5fbded6af7adabdf1eec85631c6811ef8ecc34 | https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/GeometryConverter.py#L37-L104 | train | Get a point in KML format with center at the coordinates of the point and radius as specified. |
adamziel/python_translate | python_translate/operations.py | AbstractOperation.get_domains | def get_domains(self):
"""
Returns domains affected by operation.
@rtype: list
"""
if self.domains is None:
self.domains = list(
set(self.source.get_domains() + self.target.get_domains()))
return self.domains | python | def get_domains(self):
"""
Returns domains affected by operation.
@rtype: list
"""
if self.domains is None:
self.domains = list(
set(self.source.get_domains() + self.target.get_domains()))
return self.domains | [
"def",
"get_domains",
"(",
"self",
")",
":",
"if",
"self",
".",
"domains",
"is",
"None",
":",
"self",
".",
"domains",
"=",
"list",
"(",
"set",
"(",
"self",
".",
"source",
".",
"get_domains",
"(",
")",
"+",
"self",
".",
"target",
".",
"get_domains",
... | Returns domains affected by operation.
@rtype: list | [
"Returns",
"domains",
"affected",
"by",
"operation",
"."
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/operations.py#L46-L54 | train | Returns a list of all domains affected by operation. |
adamziel/python_translate | python_translate/operations.py | AbstractOperation.get_messages | def get_messages(self, domain):
"""
Returns all valid messages after operation.
@type domain: str
@rtype: dict
"""
if domain not in self.domains:
raise ValueError('Invalid domain: {0}'.format(domain))
if domain not in self.messages or 'all' not in sel... | python | def get_messages(self, domain):
"""
Returns all valid messages after operation.
@type domain: str
@rtype: dict
"""
if domain not in self.domains:
raise ValueError('Invalid domain: {0}'.format(domain))
if domain not in self.messages or 'all' not in sel... | [
"def",
"get_messages",
"(",
"self",
",",
"domain",
")",
":",
"if",
"domain",
"not",
"in",
"self",
".",
"domains",
":",
"raise",
"ValueError",
"(",
"'Invalid domain: {0}'",
".",
"format",
"(",
"domain",
")",
")",
"if",
"domain",
"not",
"in",
"self",
".",
... | Returns all valid messages after operation.
@type domain: str
@rtype: dict | [
"Returns",
"all",
"valid",
"messages",
"after",
"operation",
"."
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/operations.py#L56-L68 | train | Returns all valid messages after operation. |
adamziel/python_translate | python_translate/operations.py | AbstractOperation.get_new_messages | def get_new_messages(self, domain):
"""
Returns new valid messages after operation.
@type domain: str
@rtype: dict
"""
if domain not in self.domains:
raise ValueError('Invalid domain: {0}'.format(domain))
if domain not in self.messages or 'new' not in... | python | def get_new_messages(self, domain):
"""
Returns new valid messages after operation.
@type domain: str
@rtype: dict
"""
if domain not in self.domains:
raise ValueError('Invalid domain: {0}'.format(domain))
if domain not in self.messages or 'new' not in... | [
"def",
"get_new_messages",
"(",
"self",
",",
"domain",
")",
":",
"if",
"domain",
"not",
"in",
"self",
".",
"domains",
":",
"raise",
"ValueError",
"(",
"'Invalid domain: {0}'",
".",
"format",
"(",
"domain",
")",
")",
"if",
"domain",
"not",
"in",
"self",
"... | Returns new valid messages after operation.
@type domain: str
@rtype: dict | [
"Returns",
"new",
"valid",
"messages",
"after",
"operation",
"."
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/operations.py#L70-L82 | train | Returns new valid messages after operation. |
adamziel/python_translate | python_translate/operations.py | AbstractOperation.get_obsolete_messages | def get_obsolete_messages(self, domain):
"""
Returns obsolete valid messages after operation.
@type domain: str
@rtype: dict
"""
if domain not in self.domains:
raise ValueError('Invalid domain: {0}'.format(domain))
if domain not in self.messages or \
... | python | def get_obsolete_messages(self, domain):
"""
Returns obsolete valid messages after operation.
@type domain: str
@rtype: dict
"""
if domain not in self.domains:
raise ValueError('Invalid domain: {0}'.format(domain))
if domain not in self.messages or \
... | [
"def",
"get_obsolete_messages",
"(",
"self",
",",
"domain",
")",
":",
"if",
"domain",
"not",
"in",
"self",
".",
"domains",
":",
"raise",
"ValueError",
"(",
"'Invalid domain: {0}'",
".",
"format",
"(",
"domain",
")",
")",
"if",
"domain",
"not",
"in",
"self"... | Returns obsolete valid messages after operation.
@type domain: str
@rtype: dict | [
"Returns",
"obsolete",
"valid",
"messages",
"after",
"operation",
"."
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/operations.py#L84-L97 | train | Returns obsolete valid messages after operation. |
adamziel/python_translate | python_translate/operations.py | AbstractOperation.get_result | def get_result(self):
"""
Returns resulting catalogue
@rtype: MessageCatalogue
"""
for domain in self.domains:
if domain not in self.messages:
self._process_domain(domain)
return self.result | python | def get_result(self):
"""
Returns resulting catalogue
@rtype: MessageCatalogue
"""
for domain in self.domains:
if domain not in self.messages:
self._process_domain(domain)
return self.result | [
"def",
"get_result",
"(",
"self",
")",
":",
"for",
"domain",
"in",
"self",
".",
"domains",
":",
"if",
"domain",
"not",
"in",
"self",
".",
"messages",
":",
"self",
".",
"_process_domain",
"(",
"domain",
")",
"return",
"self",
".",
"result"
] | Returns resulting catalogue
@rtype: MessageCatalogue | [
"Returns",
"resulting",
"catalogue"
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/operations.py#L99-L108 | train | Returns resulting catalogue
|
tjcsl/cslbot | cslbot/helpers/orm.py | setup_db | def setup_db(session, botconfig, confdir):
"""Sets up the database."""
Base.metadata.create_all(session.connection())
# If we're creating a fresh db, we don't need to worry about migrations.
if not session.get_bind().has_table('alembic_version'):
conf_obj = config.Config()
conf_obj.set_m... | python | def setup_db(session, botconfig, confdir):
"""Sets up the database."""
Base.metadata.create_all(session.connection())
# If we're creating a fresh db, we don't need to worry about migrations.
if not session.get_bind().has_table('alembic_version'):
conf_obj = config.Config()
conf_obj.set_m... | [
"def",
"setup_db",
"(",
"session",
",",
"botconfig",
",",
"confdir",
")",
":",
"Base",
".",
"metadata",
".",
"create_all",
"(",
"session",
".",
"connection",
"(",
")",
")",
"# If we're creating a fresh db, we don't need to worry about migrations.",
"if",
"not",
"ses... | Sets up the database. | [
"Sets",
"up",
"the",
"database",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/orm.py#L36-L50 | train | Setup the database. |
rchatterjee/pwmodels | src/pwmodel/readpw.py | sample_following_dist | def sample_following_dist(handle_iter, n, totalf):
"""Samples n passwords following the distribution from the handle
@handle_iter is an iterator that gives (pw,f) @n is the total
number of samle asked for @totalf is the total number of users,
which is euqal to sum(f for pw,f in handle_iter)
As, hand... | python | def sample_following_dist(handle_iter, n, totalf):
"""Samples n passwords following the distribution from the handle
@handle_iter is an iterator that gives (pw,f) @n is the total
number of samle asked for @totalf is the total number of users,
which is euqal to sum(f for pw,f in handle_iter)
As, hand... | [
"def",
"sample_following_dist",
"(",
"handle_iter",
",",
"n",
",",
"totalf",
")",
":",
"multiplier",
"=",
"1.0",
"if",
"totalf",
"==",
"1.0",
":",
"multiplier",
"=",
"1e8",
"# print \"WARNING!! I don't except probabilities\"",
"totalf",
"=",
"totalf",
"*",
"multip... | Samples n passwords following the distribution from the handle
@handle_iter is an iterator that gives (pw,f) @n is the total
number of samle asked for @totalf is the total number of users,
which is euqal to sum(f for pw,f in handle_iter)
As, handle_iterator is an iterator and can only traverse once, @to... | [
"Samples",
"n",
"passwords",
"following",
"the",
"distribution",
"from",
"the",
"handle",
"@handle_iter",
"is",
"an",
"iterator",
"that",
"gives",
"(",
"pw",
"f",
")",
"@n",
"is",
"the",
"total",
"number",
"of",
"samle",
"asked",
"for",
"@totalf",
"is",
"t... | e277411f8ebaf4ad1c208d2b035b4b68f7471517 | https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/readpw.py#L31-L77 | train | Generates n passwords following the distribution from the handle_iter and yields n random numbers. |
rchatterjee/pwmodels | src/pwmodel/readpw.py | Passwords.sample_pws | def sample_pws(self, n, asperdist=True):
"""Returns n passwords sampled from this password dataset. if
asperdist is True, then returns the password sampled according
the password histogram distribution (with
replacement). Passwords are always sampled with replacement.
TODO: The... | python | def sample_pws(self, n, asperdist=True):
"""Returns n passwords sampled from this password dataset. if
asperdist is True, then returns the password sampled according
the password histogram distribution (with
replacement). Passwords are always sampled with replacement.
TODO: The... | [
"def",
"sample_pws",
"(",
"self",
",",
"n",
",",
"asperdist",
"=",
"True",
")",
":",
"if",
"asperdist",
":",
"sample",
"=",
"np",
".",
"random",
".",
"choice",
"(",
"self",
".",
"_freq_list",
".",
"shape",
"[",
"0",
"]",
",",
"size",
"=",
"n",
",... | Returns n passwords sampled from this password dataset. if
asperdist is True, then returns the password sampled according
the password histogram distribution (with
replacement). Passwords are always sampled with replacement.
TODO: The sample users, instead of passwords perse. | [
"Returns",
"n",
"passwords",
"sampled",
"from",
"this",
"password",
"dataset",
".",
"if",
"asperdist",
"is",
"True",
"then",
"returns",
"the",
"password",
"sampled",
"according",
"the",
"password",
"histogram",
"distribution",
"(",
"with",
"replacement",
")",
".... | e277411f8ebaf4ad1c208d2b035b4b68f7471517 | https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/readpw.py#L198-L212 | train | Returns n passwords sampled from this password dataset. |
rchatterjee/pwmodels | src/pwmodel/readpw.py | Passwords.sumvalues | def sumvalues(self, q=0):
"""Sum of top q passowrd frequencies
"""
if q == 0:
return self._totalf
else:
return -np.partition(-self._freq_list, q)[:q].sum() | python | def sumvalues(self, q=0):
"""Sum of top q passowrd frequencies
"""
if q == 0:
return self._totalf
else:
return -np.partition(-self._freq_list, q)[:q].sum() | [
"def",
"sumvalues",
"(",
"self",
",",
"q",
"=",
"0",
")",
":",
"if",
"q",
"==",
"0",
":",
"return",
"self",
".",
"_totalf",
"else",
":",
"return",
"-",
"np",
".",
"partition",
"(",
"-",
"self",
".",
"_freq_list",
",",
"q",
")",
"[",
":",
"q",
... | Sum of top q passowrd frequencies | [
"Sum",
"of",
"top",
"q",
"passowrd",
"frequencies"
] | e277411f8ebaf4ad1c208d2b035b4b68f7471517 | https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/readpw.py#L255-L261 | train | Sum of top q passowrd frequencies
|
rchatterjee/pwmodels | src/pwmodel/readpw.py | Passwords.iterpws | def iterpws(self, n):
"""
Returns passwords in order of their frequencies.
@n: The numebr of passwords to return
Return: pwid, password, frequency
Every password is assigned an uniq id, for efficient access.
"""
for _id in np.argsort(self._freq_list)[::-1][:n]:
... | python | def iterpws(self, n):
"""
Returns passwords in order of their frequencies.
@n: The numebr of passwords to return
Return: pwid, password, frequency
Every password is assigned an uniq id, for efficient access.
"""
for _id in np.argsort(self._freq_list)[::-1][:n]:
... | [
"def",
"iterpws",
"(",
"self",
",",
"n",
")",
":",
"for",
"_id",
"in",
"np",
".",
"argsort",
"(",
"self",
".",
"_freq_list",
")",
"[",
":",
":",
"-",
"1",
"]",
"[",
":",
"n",
"]",
":",
"pw",
"=",
"self",
".",
"_T",
".",
"restore_key",
"(",
... | Returns passwords in order of their frequencies.
@n: The numebr of passwords to return
Return: pwid, password, frequency
Every password is assigned an uniq id, for efficient access. | [
"Returns",
"passwords",
"in",
"order",
"of",
"their",
"frequencies",
"."
] | e277411f8ebaf4ad1c208d2b035b4b68f7471517 | https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/readpw.py#L263-L273 | train | Iterate over the passwords in order of their frequencies. |
VIVelev/PyDojoML | dojo/split/cross_validate.py | cross_validate | def cross_validate(model, X, y, k_folds=5, metric="auto", shuffle=True):
"""Cross Validation
Evaluates the given model using the given data
repetitively fitting and predicting on different
chunks (folds) from the data.
Parameters:
-----------
model : dojo-model, the model to be evaluat... | python | def cross_validate(model, X, y, k_folds=5, metric="auto", shuffle=True):
"""Cross Validation
Evaluates the given model using the given data
repetitively fitting and predicting on different
chunks (folds) from the data.
Parameters:
-----------
model : dojo-model, the model to be evaluat... | [
"def",
"cross_validate",
"(",
"model",
",",
"X",
",",
"y",
",",
"k_folds",
"=",
"5",
",",
"metric",
"=",
"\"auto\"",
",",
"shuffle",
"=",
"True",
")",
":",
"train_scores",
"=",
"[",
"]",
"test_scores",
"=",
"[",
"]",
"folds",
"=",
"KFolds",
"(",
"X... | Cross Validation
Evaluates the given model using the given data
repetitively fitting and predicting on different
chunks (folds) from the data.
Parameters:
-----------
model : dojo-model, the model to be evaluated
X : matrix, shape (n_samples, n_features), the data used for evaluation
... | [
"Cross",
"Validation"
] | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/split/cross_validate.py#L11-L55 | train | Evaluates the given model on the given data and returns a dictionary with train scores and test scores. |
tjcsl/cslbot | cslbot/commands/cidr.py | cmd | def cmd(send, msg, args):
"""Gets a CIDR range.
Syntax: {command} <range>
"""
if not msg:
send("Need a CIDR range.")
return
try:
ipn = ip_network(msg)
except ValueError:
send("Not a valid CIDR range.")
return
send("%s - %s" % (ipn[0], ipn[-1])) | python | def cmd(send, msg, args):
"""Gets a CIDR range.
Syntax: {command} <range>
"""
if not msg:
send("Need a CIDR range.")
return
try:
ipn = ip_network(msg)
except ValueError:
send("Not a valid CIDR range.")
return
send("%s - %s" % (ipn[0], ipn[-1])) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"not",
"msg",
":",
"send",
"(",
"\"Need a CIDR range.\"",
")",
"return",
"try",
":",
"ipn",
"=",
"ip_network",
"(",
"msg",
")",
"except",
"ValueError",
":",
"send",
"(",
"\"Not a valid... | Gets a CIDR range.
Syntax: {command} <range> | [
"Gets",
"a",
"CIDR",
"range",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/cidr.py#L24-L38 | train | Gets a CIDR range. |
nezhar/updatable | updatable/__init__.py | get_environment_requirements_list | def get_environment_requirements_list():
"""
Take the requirements list from the current running environment
:return: string
"""
requirement_list = []
requirements = check_output([sys.executable, '-m', 'pip', 'freeze'])
for requirement in requirements.split():
requirement_list.appe... | python | def get_environment_requirements_list():
"""
Take the requirements list from the current running environment
:return: string
"""
requirement_list = []
requirements = check_output([sys.executable, '-m', 'pip', 'freeze'])
for requirement in requirements.split():
requirement_list.appe... | [
"def",
"get_environment_requirements_list",
"(",
")",
":",
"requirement_list",
"=",
"[",
"]",
"requirements",
"=",
"check_output",
"(",
"[",
"sys",
".",
"executable",
",",
"'-m'",
",",
"'pip'",
",",
"'freeze'",
"]",
")",
"for",
"requirement",
"in",
"requiremen... | Take the requirements list from the current running environment
:return: string | [
"Take",
"the",
"requirements",
"list",
"from",
"the",
"current",
"running",
"environment"
] | 654c70a40d9cabcfdd762acf82b49f66057438af | https://github.com/nezhar/updatable/blob/654c70a40d9cabcfdd762acf82b49f66057438af/updatable/__init__.py#L24-L36 | train | Take the requirements list from the current running environment |
nezhar/updatable | updatable/__init__.py | parse_requirements_list | def parse_requirements_list(requirements_list):
"""
Take a list and return a list of dicts with {package, versions) based on the requirements specs
:param requirements_list: string
:return: string
"""
req_list = []
for requirement in requirements_list:
requirement_no_comments = req... | python | def parse_requirements_list(requirements_list):
"""
Take a list and return a list of dicts with {package, versions) based on the requirements specs
:param requirements_list: string
:return: string
"""
req_list = []
for requirement in requirements_list:
requirement_no_comments = req... | [
"def",
"parse_requirements_list",
"(",
"requirements_list",
")",
":",
"req_list",
"=",
"[",
"]",
"for",
"requirement",
"in",
"requirements_list",
":",
"requirement_no_comments",
"=",
"requirement",
".",
"split",
"(",
"'#'",
")",
"[",
"0",
"]",
".",
"strip",
"(... | Take a list and return a list of dicts with {package, versions) based on the requirements specs
:param requirements_list: string
:return: string | [
"Take",
"a",
"list",
"and",
"return",
"a",
"list",
"of",
"dicts",
"with",
"{",
"package",
"versions",
")",
"based",
"on",
"the",
"requirements",
"specs"
] | 654c70a40d9cabcfdd762acf82b49f66057438af | https://github.com/nezhar/updatable/blob/654c70a40d9cabcfdd762acf82b49f66057438af/updatable/__init__.py#L39-L62 | train | Takes a list and returns a list of dicts with package versions |
nezhar/updatable | updatable/__init__.py | get_pypi_package_data | def get_pypi_package_data(package_name, version=None):
"""
Get package data from pypi by the package name
https://wiki.python.org/moin/PyPIJSON
:param package_name: string
:param version: string
:return: dict
"""
pypi_url = 'https://pypi.org/pypi'
if version:
package_url =... | python | def get_pypi_package_data(package_name, version=None):
"""
Get package data from pypi by the package name
https://wiki.python.org/moin/PyPIJSON
:param package_name: string
:param version: string
:return: dict
"""
pypi_url = 'https://pypi.org/pypi'
if version:
package_url =... | [
"def",
"get_pypi_package_data",
"(",
"package_name",
",",
"version",
"=",
"None",
")",
":",
"pypi_url",
"=",
"'https://pypi.org/pypi'",
"if",
"version",
":",
"package_url",
"=",
"'%s/%s/%s/json'",
"%",
"(",
"pypi_url",
",",
"package_name",
",",
"version",
",",
"... | Get package data from pypi by the package name
https://wiki.python.org/moin/PyPIJSON
:param package_name: string
:param version: string
:return: dict | [
"Get",
"package",
"data",
"from",
"pypi",
"by",
"the",
"package",
"name"
] | 654c70a40d9cabcfdd762acf82b49f66057438af | https://github.com/nezhar/updatable/blob/654c70a40d9cabcfdd762acf82b49f66057438af/updatable/__init__.py#L65-L91 | train | Get package data from pypi by the package name |
nezhar/updatable | updatable/__init__.py | get_package_update_list | def get_package_update_list(package_name, version):
"""
Return update information of a package from a given version
:param package_name: string
:param version: string
:return: dict
"""
package_version = semantic_version.Version.coerce(version)
# Get package and version data from pypi
... | python | def get_package_update_list(package_name, version):
"""
Return update information of a package from a given version
:param package_name: string
:param version: string
:return: dict
"""
package_version = semantic_version.Version.coerce(version)
# Get package and version data from pypi
... | [
"def",
"get_package_update_list",
"(",
"package_name",
",",
"version",
")",
":",
"package_version",
"=",
"semantic_version",
".",
"Version",
".",
"coerce",
"(",
"version",
")",
"# Get package and version data from pypi",
"package_data",
"=",
"get_pypi_package_data",
"(",
... | Return update information of a package from a given version
:param package_name: string
:param version: string
:return: dict | [
"Return",
"update",
"information",
"of",
"a",
"package",
"from",
"a",
"given",
"version"
] | 654c70a40d9cabcfdd762acf82b49f66057438af | https://github.com/nezhar/updatable/blob/654c70a40d9cabcfdd762acf82b49f66057438af/updatable/__init__.py#L94-L183 | train | Get update information of a package from a given version |
nezhar/updatable | updatable/__init__.py | __list_package_updates | def __list_package_updates(package_name, version):
"""
Function used to list all package updates in console
:param package_name: string
:param version: string
"""
updates = get_package_update_list(package_name, version)
if updates['newer_releases'] or updates['pre_releases']:
prin... | python | def __list_package_updates(package_name, version):
"""
Function used to list all package updates in console
:param package_name: string
:param version: string
"""
updates = get_package_update_list(package_name, version)
if updates['newer_releases'] or updates['pre_releases']:
prin... | [
"def",
"__list_package_updates",
"(",
"package_name",
",",
"version",
")",
":",
"updates",
"=",
"get_package_update_list",
"(",
"package_name",
",",
"version",
")",
"if",
"updates",
"[",
"'newer_releases'",
"]",
"or",
"updates",
"[",
"'pre_releases'",
"]",
":",
... | Function used to list all package updates in console
:param package_name: string
:param version: string | [
"Function",
"used",
"to",
"list",
"all",
"package",
"updates",
"in",
"console"
] | 654c70a40d9cabcfdd762acf82b49f66057438af | https://github.com/nezhar/updatable/blob/654c70a40d9cabcfdd762acf82b49f66057438af/updatable/__init__.py#L186-L203 | train | Function used to list all package updates in console |
nezhar/updatable | updatable/__init__.py | __list_updates | def __list_updates(update_type, update_list):
"""
Function used to list package updates by update type in console
:param update_type: string
:param update_list: list
"""
if len(update_list):
print(" %s:" % update_type)
for update_item in update_list:
print(" -- %(v... | python | def __list_updates(update_type, update_list):
"""
Function used to list package updates by update type in console
:param update_type: string
:param update_list: list
"""
if len(update_list):
print(" %s:" % update_type)
for update_item in update_list:
print(" -- %(v... | [
"def",
"__list_updates",
"(",
"update_type",
",",
"update_list",
")",
":",
"if",
"len",
"(",
"update_list",
")",
":",
"print",
"(",
"\" %s:\"",
"%",
"update_type",
")",
"for",
"update_item",
"in",
"update_list",
":",
"print",
"(",
"\" -- %(version)s on %(uploa... | Function used to list package updates by update type in console
:param update_type: string
:param update_list: list | [
"Function",
"used",
"to",
"list",
"package",
"updates",
"by",
"update",
"type",
"in",
"console"
] | 654c70a40d9cabcfdd762acf82b49f66057438af | https://github.com/nezhar/updatable/blob/654c70a40d9cabcfdd762acf82b49f66057438af/updatable/__init__.py#L206-L216 | train | Function used to list package updates by update type in console |
nezhar/updatable | updatable/__init__.py | __updatable | def __updatable():
"""
Function used to output packages update information in the console
"""
# Add argument for console
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?', type=argparse.FileType(), default=None, help='Requirements file')
args = parser.parse_args()
... | python | def __updatable():
"""
Function used to output packages update information in the console
"""
# Add argument for console
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?', type=argparse.FileType(), default=None, help='Requirements file')
args = parser.parse_args()
... | [
"def",
"__updatable",
"(",
")",
":",
"# Add argument for console",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'file'",
",",
"nargs",
"=",
"'?'",
",",
"type",
"=",
"argparse",
".",
"FileType",
"(",
")",
... | Function used to output packages update information in the console | [
"Function",
"used",
"to",
"output",
"packages",
"update",
"information",
"in",
"the",
"console"
] | 654c70a40d9cabcfdd762acf82b49f66057438af | https://github.com/nezhar/updatable/blob/654c70a40d9cabcfdd762acf82b49f66057438af/updatable/__init__.py#L219-L236 | train | Function used to output packages update information in the console
|
tjcsl/cslbot | cslbot/hooks/url.py | handle | def handle(send, msg, args):
"""Get titles for urls.
Generate a short url. Get the page title.
"""
worker = args["handler"].workers
result = worker.run_pool(get_urls, [msg])
try:
urls = result.get(5)
except multiprocessing.TimeoutError:
worker.restart_pool()
send("U... | python | def handle(send, msg, args):
"""Get titles for urls.
Generate a short url. Get the page title.
"""
worker = args["handler"].workers
result = worker.run_pool(get_urls, [msg])
try:
urls = result.get(5)
except multiprocessing.TimeoutError:
worker.restart_pool()
send("U... | [
"def",
"handle",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"worker",
"=",
"args",
"[",
"\"handler\"",
"]",
".",
"workers",
"result",
"=",
"worker",
".",
"run_pool",
"(",
"get_urls",
",",
"[",
"msg",
"]",
")",
"try",
":",
"urls",
"=",
"result"... | Get titles for urls.
Generate a short url. Get the page title. | [
"Get",
"titles",
"for",
"urls",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/hooks/url.py#L37-L77 | train | Generate a short url. |
The-Politico/politico-civic-election-night | electionnight/models/page_type.py | PageType.page_location_template | def page_location_template(self):
"""
Returns the published URL template for a page type.
"""
cycle = self.election_day.cycle.name
model_class = self.model_type.model_class()
if model_class == ElectionDay:
return "/{}/".format(cycle)
if model_class == ... | python | def page_location_template(self):
"""
Returns the published URL template for a page type.
"""
cycle = self.election_day.cycle.name
model_class = self.model_type.model_class()
if model_class == ElectionDay:
return "/{}/".format(cycle)
if model_class == ... | [
"def",
"page_location_template",
"(",
"self",
")",
":",
"cycle",
"=",
"self",
".",
"election_day",
".",
"cycle",
".",
"name",
"model_class",
"=",
"self",
".",
"model_type",
".",
"model_class",
"(",
")",
"if",
"model_class",
"==",
"ElectionDay",
":",
"return"... | Returns the published URL template for a page type. | [
"Returns",
"the",
"published",
"URL",
"template",
"for",
"a",
"page",
"type",
"."
] | a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/models/page_type.py#L69-L109 | train | Returns the published URL template for a page type. |
tjcsl/cslbot | cslbot/alembic/env.py | run_migrations_offline | def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the g... | python | def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the g... | [
"def",
"run_migrations_offline",
"(",
")",
":",
"botconfig",
"=",
"configparser",
".",
"ConfigParser",
"(",
"interpolation",
"=",
"configparser",
".",
"ExtendedInterpolation",
"(",
")",
")",
"config_path",
"=",
"config",
".",
"get_main_option",
"(",
"'bot_config_pat... | Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output. | [
"Run",
"migrations",
"in",
"offline",
"mode",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/alembic/env.py#L47-L68 | train | Run migrations in offline mode. |
tjcsl/cslbot | cslbot/alembic/env.py | run_migrations_online | def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine and associate a
connection with the context.
"""
botconfig = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
config_path = config.get_main_option('bot_con... | python | def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine and associate a
connection with the context.
"""
botconfig = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
config_path = config.get_main_option('bot_con... | [
"def",
"run_migrations_online",
"(",
")",
":",
"botconfig",
"=",
"configparser",
".",
"ConfigParser",
"(",
"interpolation",
"=",
"configparser",
".",
"ExtendedInterpolation",
"(",
")",
")",
"config_path",
"=",
"config",
".",
"get_main_option",
"(",
"'bot_config_path... | Run migrations in 'online' mode.
In this scenario we need to create an Engine and associate a
connection with the context. | [
"Run",
"migrations",
"in",
"online",
"mode",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/alembic/env.py#L71-L89 | train | Run migrations in online mode. |
tjcsl/cslbot | cslbot/commands/tjbash.py | cmd | def cmd(send, msg, _):
"""Finds a random quote from tjbash.org given search criteria.
Syntax: {command} [searchstring]
"""
if not msg:
url = 'http://tjbash.org/random1.html'
params = {}
else:
targs = msg.split()
if len(targs) == 1 and targs[0].isnumeric():
... | python | def cmd(send, msg, _):
"""Finds a random quote from tjbash.org given search criteria.
Syntax: {command} [searchstring]
"""
if not msg:
url = 'http://tjbash.org/random1.html'
params = {}
else:
targs = msg.split()
if len(targs) == 1 and targs[0].isnumeric():
... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"_",
")",
":",
"if",
"not",
"msg",
":",
"url",
"=",
"'http://tjbash.org/random1.html'",
"params",
"=",
"{",
"}",
"else",
":",
"targs",
"=",
"msg",
".",
"split",
"(",
")",
"if",
"len",
"(",
"targs",
")",
... | Finds a random quote from tjbash.org given search criteria.
Syntax: {command} [searchstring] | [
"Finds",
"a",
"random",
"quote",
"from",
"tjbash",
".",
"org",
"given",
"search",
"criteria",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/tjbash.py#L29-L63 | train | Finds a random quote from tjbash. org given search criteria. |
klahnakoski/mo-json | mo_json/typed_encoder.py | typed_encode | def typed_encode(value, sub_schema, path, net_new_properties, buffer):
"""
:param value: THE DATA STRUCTURE TO ENCODE
:param sub_schema: dict FROM PATH TO Column DESCRIBING THE TYPE
:param path: list OF CURRENT PATH
:param net_new_properties: list FOR ADDING NEW PROPERTIES NOT FOUND IN sub_schema
... | python | def typed_encode(value, sub_schema, path, net_new_properties, buffer):
"""
:param value: THE DATA STRUCTURE TO ENCODE
:param sub_schema: dict FROM PATH TO Column DESCRIBING THE TYPE
:param path: list OF CURRENT PATH
:param net_new_properties: list FOR ADDING NEW PROPERTIES NOT FOUND IN sub_schema
... | [
"def",
"typed_encode",
"(",
"value",
",",
"sub_schema",
",",
"path",
",",
"net_new_properties",
",",
"buffer",
")",
":",
"try",
":",
"# from jx_base import Column",
"if",
"sub_schema",
".",
"__class__",
".",
"__name__",
"==",
"'Column'",
":",
"value_json_type",
... | :param value: THE DATA STRUCTURE TO ENCODE
:param sub_schema: dict FROM PATH TO Column DESCRIBING THE TYPE
:param path: list OF CURRENT PATH
:param net_new_properties: list FOR ADDING NEW PROPERTIES NOT FOUND IN sub_schema
:param buffer: UnicodeBuilder OBJECT
:return: | [
":",
"param",
"value",
":",
"THE",
"DATA",
"STRUCTURE",
"TO",
"ENCODE",
":",
"param",
"sub_schema",
":",
"dict",
"FROM",
"PATH",
"TO",
"Column",
"DESCRIBING",
"THE",
"TYPE",
":",
"param",
"path",
":",
"list",
"OF",
"CURRENT",
"PATH",
":",
"param",
"net_n... | 0d44d6a7e37f0ea50e583c30c2cbc42488d5de7f | https://github.com/klahnakoski/mo-json/blob/0d44d6a7e37f0ea50e583c30c2cbc42488d5de7f/mo_json/typed_encoder.py#L132-L362 | train | Encodes the value in the given sub_schema to the given buffer. |
The-Politico/politico-civic-election-night | electionnight/viewsets/body.py | BodyMixin.get_queryset | def get_queryset(self):
"""
Returns a queryset of all bodies holding an election on a date.
"""
try:
date = ElectionDay.objects.get(date=self.kwargs['date'])
except Exception:
raise APIException(
'No elections on {}.'.format(self.kwargs['da... | python | def get_queryset(self):
"""
Returns a queryset of all bodies holding an election on a date.
"""
try:
date = ElectionDay.objects.get(date=self.kwargs['date'])
except Exception:
raise APIException(
'No elections on {}.'.format(self.kwargs['da... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"try",
":",
"date",
"=",
"ElectionDay",
".",
"objects",
".",
"get",
"(",
"date",
"=",
"self",
".",
"kwargs",
"[",
"'date'",
"]",
")",
"except",
"Exception",
":",
"raise",
"APIException",
"(",
"'No elections o... | Returns a queryset of all bodies holding an election on a date. | [
"Returns",
"a",
"queryset",
"of",
"all",
"bodies",
"holding",
"an",
"election",
"on",
"a",
"date",
"."
] | a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/viewsets/body.py#L9-L24 | train | Returns a queryset of all bodies holding an election on a date. |
The-Politico/politico-civic-election-night | electionnight/viewsets/body.py | BodyMixin.get_serializer_context | def get_serializer_context(self):
"""Adds ``election_day`` to serializer context."""
context = super(BodyMixin, self).get_serializer_context()
context['election_date'] = self.kwargs['date']
return context | python | def get_serializer_context(self):
"""Adds ``election_day`` to serializer context."""
context = super(BodyMixin, self).get_serializer_context()
context['election_date'] = self.kwargs['date']
return context | [
"def",
"get_serializer_context",
"(",
"self",
")",
":",
"context",
"=",
"super",
"(",
"BodyMixin",
",",
"self",
")",
".",
"get_serializer_context",
"(",
")",
"context",
"[",
"'election_date'",
"]",
"=",
"self",
".",
"kwargs",
"[",
"'date'",
"]",
"return",
... | Adds ``election_day`` to serializer context. | [
"Adds",
"election_day",
"to",
"serializer",
"context",
"."
] | a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/viewsets/body.py#L26-L30 | train | Adds election_day to serializer context. |
asphalt-framework/asphalt-sqlalchemy | asphalt/sqlalchemy/component.py | SQLAlchemyComponent.configure_engine | def configure_engine(cls, url: Union[str, URL, Dict[str, Any]] = None,
bind: Union[Connection, Engine] = None, session: Dict[str, Any] = None,
ready_callback: Union[Callable[[Engine, sessionmaker], Any], str] = None,
poolclass: Union[str, Pool] ... | python | def configure_engine(cls, url: Union[str, URL, Dict[str, Any]] = None,
bind: Union[Connection, Engine] = None, session: Dict[str, Any] = None,
ready_callback: Union[Callable[[Engine, sessionmaker], Any], str] = None,
poolclass: Union[str, Pool] ... | [
"def",
"configure_engine",
"(",
"cls",
",",
"url",
":",
"Union",
"[",
"str",
",",
"URL",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
"=",
"None",
",",
"bind",
":",
"Union",
"[",
"Connection",
",",
"Engine",
"]",
"=",
"None",
",",
"session",
":... | Create an engine and selectively apply certain hacks to make it Asphalt friendly.
:param url: the connection url passed to :func:`~sqlalchemy.create_engine`
(can also be a dictionary of :class:`~sqlalchemy.engine.url.URL` keyword arguments)
:param bind: a connection or engine to use instead... | [
"Create",
"an",
"engine",
"and",
"selectively",
"apply",
"certain",
"hacks",
"to",
"make",
"it",
"Asphalt",
"friendly",
"."
] | 5abb7d9977ee92299359b76496ff34624421de05 | https://github.com/asphalt-framework/asphalt-sqlalchemy/blob/5abb7d9977ee92299359b76496ff34624421de05/asphalt/sqlalchemy/component.py#L70-L113 | train | Create an engine and selectively apply certain hacks to make it Asphalt friendly. |
intuition-io/insights | insights/plugins/database/influx.py | InfluxdbBackend.save_portfolio | def save_portfolio(self, datetime, portfolio):
'''
Store in Rethinkdb a zipline.Portfolio object
'''
log.debug('Saving portfolio in database')
pf = dbutils.portfolio_to_dict(portfolio)
pf.pop('positions')
data = [{
"name": self.name,
"time"... | python | def save_portfolio(self, datetime, portfolio):
'''
Store in Rethinkdb a zipline.Portfolio object
'''
log.debug('Saving portfolio in database')
pf = dbutils.portfolio_to_dict(portfolio)
pf.pop('positions')
data = [{
"name": self.name,
"time"... | [
"def",
"save_portfolio",
"(",
"self",
",",
"datetime",
",",
"portfolio",
")",
":",
"log",
".",
"debug",
"(",
"'Saving portfolio in database'",
")",
"pf",
"=",
"dbutils",
".",
"portfolio_to_dict",
"(",
"portfolio",
")",
"pf",
".",
"pop",
"(",
"'positions'",
"... | Store in Rethinkdb a zipline.Portfolio object | [
"Store",
"in",
"Rethinkdb",
"a",
"zipline",
".",
"Portfolio",
"object"
] | a4eae53a1886164db96751d2b0964aa2acb7c2d7 | https://github.com/intuition-io/insights/blob/a4eae53a1886164db96751d2b0964aa2acb7c2d7/insights/plugins/database/influx.py#L36-L51 | train | Save a portfolio in the database. |
Genida/archan | src/archan/cli.py | valid_file | def valid_file(value):
"""
Check if given file exists and is a regular file.
Args:
value (str): path to the file.
Raises:
argparse.ArgumentTypeError: if not valid.
Returns:
str: original value argument.
"""
if not value:
raise argparse.ArgumentTypeError("''... | python | def valid_file(value):
"""
Check if given file exists and is a regular file.
Args:
value (str): path to the file.
Raises:
argparse.ArgumentTypeError: if not valid.
Returns:
str: original value argument.
"""
if not value:
raise argparse.ArgumentTypeError("''... | [
"def",
"valid_file",
"(",
"value",
")",
":",
"if",
"not",
"value",
":",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"\"'' is not a valid file path\"",
")",
"elif",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"value",
")",
":",
"raise",
"argparse",
... | Check if given file exists and is a regular file.
Args:
value (str): path to the file.
Raises:
argparse.ArgumentTypeError: if not valid.
Returns:
str: original value argument. | [
"Check",
"if",
"given",
"file",
"exists",
"and",
"is",
"a",
"regular",
"file",
"."
] | a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/cli.py#L35-L56 | train | Check if given file exists and is a regular file. |
Genida/archan | src/archan/cli.py | valid_level | def valid_level(value):
"""Validation function for parser, logging level argument."""
value = value.upper()
if getattr(logging, value, None) is None:
raise argparse.ArgumentTypeError("%s is not a valid level" % value)
return value | python | def valid_level(value):
"""Validation function for parser, logging level argument."""
value = value.upper()
if getattr(logging, value, None) is None:
raise argparse.ArgumentTypeError("%s is not a valid level" % value)
return value | [
"def",
"valid_level",
"(",
"value",
")",
":",
"value",
"=",
"value",
".",
"upper",
"(",
")",
"if",
"getattr",
"(",
"logging",
",",
"value",
",",
"None",
")",
"is",
"None",
":",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"\"%s is not a valid level\... | Validation function for parser, logging level argument. | [
"Validation",
"function",
"for",
"parser",
"logging",
"level",
"argument",
"."
] | a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/cli.py#L59-L64 | train | Validation function for parser logging level argument. |
Genida/archan | src/archan/cli.py | get_parser | def get_parser():
"""Return a parser for the command-line arguments."""
parser = argparse.ArgumentParser(
add_help=False,
description='Analysis of your architecture strength based on DSM data')
parser.add_argument(
'-c', '--config', action='store', type=valid_file, dest='config_file'... | python | def get_parser():
"""Return a parser for the command-line arguments."""
parser = argparse.ArgumentParser(
add_help=False,
description='Analysis of your architecture strength based on DSM data')
parser.add_argument(
'-c', '--config', action='store', type=valid_file, dest='config_file'... | [
"def",
"get_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"add_help",
"=",
"False",
",",
"description",
"=",
"'Analysis of your architecture strength based on DSM data'",
")",
"parser",
".",
"add_argument",
"(",
"'-c'",
",",
"'--conf... | Return a parser for the command-line arguments. | [
"Return",
"a",
"parser",
"for",
"the",
"command",
"-",
"line",
"arguments",
"."
] | a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/cli.py#L67-L96 | train | Return a parser for the command - line arguments. |
Genida/archan | src/archan/cli.py | main | def main(args=None):
"""Main function."""
parser = get_parser()
args = parser.parse_args(args=args)
Logger.set_level(args.level)
colorama_args = {'autoreset': True}
if args.no_color:
colorama_args['strip'] = True
colorama.init(**colorama_args)
config = None
if args.no_confi... | python | def main(args=None):
"""Main function."""
parser = get_parser()
args = parser.parse_args(args=args)
Logger.set_level(args.level)
colorama_args = {'autoreset': True}
if args.no_color:
colorama_args['strip'] = True
colorama.init(**colorama_args)
config = None
if args.no_confi... | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"parser",
"=",
"get_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"args",
"=",
"args",
")",
"Logger",
".",
"set_level",
"(",
"args",
".",
"level",
")",
"colorama_args",
"=",
"{",
... | Main function. | [
"Main",
"function",
"."
] | a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/cli.py#L99-L152 | train | Main function. |
MosesSymeonidis/aggregation_builder | aggregation_builder/operators/array.py | RANGE | def RANGE(start, end, step=None):
"""
Generates the sequence from the specified starting number by successively
incrementing the starting number by the specified step value up to but not including the end point.
See https://docs.mongodb.com/manual/reference/operator/aggregation/range/
for more detai... | python | def RANGE(start, end, step=None):
"""
Generates the sequence from the specified starting number by successively
incrementing the starting number by the specified step value up to but not including the end point.
See https://docs.mongodb.com/manual/reference/operator/aggregation/range/
for more detai... | [
"def",
"RANGE",
"(",
"start",
",",
"end",
",",
"step",
"=",
"None",
")",
":",
"return",
"{",
"'$range'",
":",
"[",
"start",
",",
"end",
",",
"step",
"]",
"}",
"if",
"step",
"is",
"not",
"None",
"else",
"{",
"'$range'",
":",
"[",
"start",
",",
"... | Generates the sequence from the specified starting number by successively
incrementing the starting number by the specified step value up to but not including the end point.
See https://docs.mongodb.com/manual/reference/operator/aggregation/range/
for more details
:param start: An integer (or valid expr... | [
"Generates",
"the",
"sequence",
"from",
"the",
"specified",
"starting",
"number",
"by",
"successively",
"incrementing",
"the",
"starting",
"number",
"by",
"the",
"specified",
"step",
"value",
"up",
"to",
"but",
"not",
"including",
"the",
"end",
"point",
".",
"... | a1f4b580401d400c53206e9c020e413166254274 | https://github.com/MosesSymeonidis/aggregation_builder/blob/a1f4b580401d400c53206e9c020e413166254274/aggregation_builder/operators/array.py#L97-L108 | train | Returns a sequence that is aggregated by the specified start and end point. |
MosesSymeonidis/aggregation_builder | aggregation_builder/operators/array.py | SLICE | def SLICE(array, n, position=None):
"""
Returns a subset of an array.
See https://docs.mongodb.com/manual/reference/operator/aggregation/slice/
for more details
:param array: Any valid expression as long as it resolves to an array.
:param n: Any valid expression as long as it resolves to an inte... | python | def SLICE(array, n, position=None):
"""
Returns a subset of an array.
See https://docs.mongodb.com/manual/reference/operator/aggregation/slice/
for more details
:param array: Any valid expression as long as it resolves to an array.
:param n: Any valid expression as long as it resolves to an inte... | [
"def",
"SLICE",
"(",
"array",
",",
"n",
",",
"position",
"=",
"None",
")",
":",
"return",
"{",
"'$slice'",
":",
"[",
"array",
",",
"position",
",",
"n",
"]",
"}",
"if",
"position",
"is",
"not",
"None",
"else",
"{",
"'$slice'",
":",
"[",
"array",
... | Returns a subset of an array.
See https://docs.mongodb.com/manual/reference/operator/aggregation/slice/
for more details
:param array: Any valid expression as long as it resolves to an array.
:param n: Any valid expression as long as it resolves to an integer.
:param position: Optional. Any valid ex... | [
"Returns",
"a",
"subset",
"of",
"an",
"array",
".",
"See",
"https",
":",
"//",
"docs",
".",
"mongodb",
".",
"com",
"/",
"manual",
"/",
"reference",
"/",
"operator",
"/",
"aggregation",
"/",
"slice",
"/",
"for",
"more",
"details",
":",
"param",
"array",... | a1f4b580401d400c53206e9c020e413166254274 | https://github.com/MosesSymeonidis/aggregation_builder/blob/a1f4b580401d400c53206e9c020e413166254274/aggregation_builder/operators/array.py#L146-L156 | train | Returns a subset of an array. |
MosesSymeonidis/aggregation_builder | aggregation_builder/operators/array.py | ZIP | def ZIP(inputs, use_longest_length=None, defaults=None):
"""
Transposes an array of input arrays so that the first element of the output array would be an array containing,
the first element of the first input array,
the first element of the second input array, etc.
See https://docs.mongodb.com/manu... | python | def ZIP(inputs, use_longest_length=None, defaults=None):
"""
Transposes an array of input arrays so that the first element of the output array would be an array containing,
the first element of the first input array,
the first element of the second input array, etc.
See https://docs.mongodb.com/manu... | [
"def",
"ZIP",
"(",
"inputs",
",",
"use_longest_length",
"=",
"None",
",",
"defaults",
"=",
"None",
")",
":",
"res",
"=",
"{",
"'inputs'",
":",
"inputs",
"}",
"if",
"use_longest_length",
"in",
"[",
"True",
",",
"False",
"]",
":",
"res",
"[",
"'useLonges... | Transposes an array of input arrays so that the first element of the output array would be an array containing,
the first element of the first input array,
the first element of the second input array, etc.
See https://docs.mongodb.com/manual/reference/operator/aggregation/zip/
for more details
:para... | [
"Transposes",
"an",
"array",
"of",
"input",
"arrays",
"so",
"that",
"the",
"first",
"element",
"of",
"the",
"output",
"array",
"would",
"be",
"an",
"array",
"containing",
"the",
"first",
"element",
"of",
"the",
"first",
"input",
"array",
"the",
"first",
"e... | a1f4b580401d400c53206e9c020e413166254274 | https://github.com/MosesSymeonidis/aggregation_builder/blob/a1f4b580401d400c53206e9c020e413166254274/aggregation_builder/operators/array.py#L159-L176 | train | This function returns an aggregation operator that takes an array of input expressions that resolve to arrays and returns a dictionary of the output arrays. |
MosesSymeonidis/aggregation_builder | aggregation_builder/operators/array.py | INDEX_OF_ARRAY | def INDEX_OF_ARRAY(string_expression, substring_expression, start=None, end=None):
"""
Searches an array for an occurence of a specified value and returns the array index of the first occurence.
See https://docs.mongodb.com/manual/reference/operator/aggregation/zip/
for more details
:param string_ex... | python | def INDEX_OF_ARRAY(string_expression, substring_expression, start=None, end=None):
"""
Searches an array for an occurence of a specified value and returns the array index of the first occurence.
See https://docs.mongodb.com/manual/reference/operator/aggregation/zip/
for more details
:param string_ex... | [
"def",
"INDEX_OF_ARRAY",
"(",
"string_expression",
",",
"substring_expression",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"res",
"=",
"[",
"string_expression",
",",
"substring_expression",
"]",
"if",
"start",
"is",
"not",
"None",
":",
"re... | Searches an array for an occurence of a specified value and returns the array index of the first occurence.
See https://docs.mongodb.com/manual/reference/operator/aggregation/zip/
for more details
:param string_expression: Any valid expression as long as it resolves to an array.
:param substring_express... | [
"Searches",
"an",
"array",
"for",
"an",
"occurence",
"of",
"a",
"specified",
"value",
"and",
"returns",
"the",
"array",
"index",
"of",
"the",
"first",
"occurence",
".",
"See",
"https",
":",
"//",
"docs",
".",
"mongodb",
".",
"com",
"/",
"manual",
"/",
... | a1f4b580401d400c53206e9c020e413166254274 | https://github.com/MosesSymeonidis/aggregation_builder/blob/a1f4b580401d400c53206e9c020e413166254274/aggregation_builder/operators/array.py#L179-L195 | train | Searches an array for an occurence of a specified value and returns the index of the first occurence. |
tylerbutler/engineer | engineer/plugins/core.py | PluginMixin.get_logger | def get_logger(cls, custom_name=None):
"""Returns a logger for the plugin."""
name = custom_name or cls.get_name()
return logging.getLogger(name) | python | def get_logger(cls, custom_name=None):
"""Returns a logger for the plugin."""
name = custom_name or cls.get_name()
return logging.getLogger(name) | [
"def",
"get_logger",
"(",
"cls",
",",
"custom_name",
"=",
"None",
")",
":",
"name",
"=",
"custom_name",
"or",
"cls",
".",
"get_name",
"(",
")",
"return",
"logging",
".",
"getLogger",
"(",
"name",
")"
] | Returns a logger for the plugin. | [
"Returns",
"a",
"logger",
"for",
"the",
"plugin",
"."
] | 8884f587297f37646c40e5553174852b444a4024 | https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/plugins/core.py#L80-L83 | train | Returns a logger for the plugin. |
adamziel/python_translate | python_translate/translations.py | MessageCatalogue.all | def all(self, domain=None):
"""
Gets the messages within a given domain.
If domain is None, it returns all messages.
@type id: The
@param id: message id
@rtype: dict
@return: A dict of messages
"""
if domain is None:
return {k: dict(... | python | def all(self, domain=None):
"""
Gets the messages within a given domain.
If domain is None, it returns all messages.
@type id: The
@param id: message id
@rtype: dict
@return: A dict of messages
"""
if domain is None:
return {k: dict(... | [
"def",
"all",
"(",
"self",
",",
"domain",
"=",
"None",
")",
":",
"if",
"domain",
"is",
"None",
":",
"return",
"{",
"k",
":",
"dict",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"self",
".",
"messages",
".",
"items",
"(",
")",
")",... | Gets the messages within a given domain.
If domain is None, it returns all messages.
@type id: The
@param id: message id
@rtype: dict
@return: A dict of messages | [
"Gets",
"the",
"messages",
"within",
"a",
"given",
"domain",
"."
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L56-L71 | train | Returns the messages within a given domain. |
adamziel/python_translate | python_translate/translations.py | MessageCatalogue.set | def set(self, id, translation, domain='messages'):
"""
Sets a message translation.
"""
assert isinstance(id, (str, unicode))
assert isinstance(translation, (str, unicode))
assert isinstance(domain, (str, unicode))
self.add({id: translation}, domain) | python | def set(self, id, translation, domain='messages'):
"""
Sets a message translation.
"""
assert isinstance(id, (str, unicode))
assert isinstance(translation, (str, unicode))
assert isinstance(domain, (str, unicode))
self.add({id: translation}, domain) | [
"def",
"set",
"(",
"self",
",",
"id",
",",
"translation",
",",
"domain",
"=",
"'messages'",
")",
":",
"assert",
"isinstance",
"(",
"id",
",",
"(",
"str",
",",
"unicode",
")",
")",
"assert",
"isinstance",
"(",
"translation",
",",
"(",
"str",
",",
"uni... | Sets a message translation. | [
"Sets",
"a",
"message",
"translation",
"."
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L73-L81 | train | Sets a message translation. |
adamziel/python_translate | python_translate/translations.py | MessageCatalogue.has | def has(self, id, domain):
"""
Checks if a message has a translation.
@rtype: bool
@return: true if the message has a translation, false otherwise
"""
assert isinstance(id, (str, unicode))
assert isinstance(domain, (str, unicode))
if self.defines(id, dom... | python | def has(self, id, domain):
"""
Checks if a message has a translation.
@rtype: bool
@return: true if the message has a translation, false otherwise
"""
assert isinstance(id, (str, unicode))
assert isinstance(domain, (str, unicode))
if self.defines(id, dom... | [
"def",
"has",
"(",
"self",
",",
"id",
",",
"domain",
")",
":",
"assert",
"isinstance",
"(",
"id",
",",
"(",
"str",
",",
"unicode",
")",
")",
"assert",
"isinstance",
"(",
"domain",
",",
"(",
"str",
",",
"unicode",
")",
")",
"if",
"self",
".",
"def... | Checks if a message has a translation.
@rtype: bool
@return: true if the message has a translation, false otherwise | [
"Checks",
"if",
"a",
"message",
"has",
"a",
"translation",
"."
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L83-L99 | train | Checks if a message has a translation. |
adamziel/python_translate | python_translate/translations.py | MessageCatalogue.defines | def defines(self, id, domain='messages'):
"""
Checks if a message has a translation (it does not take into account
the fallback mechanism).
@rtype: bool
@return: true if the message has a translation, false otherwise
"""
assert isinstance(id, (str, unicode))
... | python | def defines(self, id, domain='messages'):
"""
Checks if a message has a translation (it does not take into account
the fallback mechanism).
@rtype: bool
@return: true if the message has a translation, false otherwise
"""
assert isinstance(id, (str, unicode))
... | [
"def",
"defines",
"(",
"self",
",",
"id",
",",
"domain",
"=",
"'messages'",
")",
":",
"assert",
"isinstance",
"(",
"id",
",",
"(",
"str",
",",
"unicode",
")",
")",
"assert",
"isinstance",
"(",
"domain",
",",
"(",
"str",
",",
"unicode",
")",
")",
"r... | Checks if a message has a translation (it does not take into account
the fallback mechanism).
@rtype: bool
@return: true if the message has a translation, false otherwise | [
"Checks",
"if",
"a",
"message",
"has",
"a",
"translation",
"(",
"it",
"does",
"not",
"take",
"into",
"account",
"the",
"fallback",
"mechanism",
")",
"."
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L101-L112 | train | Checks if a message has a translation. |
adamziel/python_translate | python_translate/translations.py | MessageCatalogue.get | def get(self, id, domain='messages'):
"""
Gets a message translation.
@rtype: str
@return: The message translation
"""
assert isinstance(id, (str, unicode))
assert isinstance(domain, (str, unicode))
if self.defines(id, domain):
return self.me... | python | def get(self, id, domain='messages'):
"""
Gets a message translation.
@rtype: str
@return: The message translation
"""
assert isinstance(id, (str, unicode))
assert isinstance(domain, (str, unicode))
if self.defines(id, domain):
return self.me... | [
"def",
"get",
"(",
"self",
",",
"id",
",",
"domain",
"=",
"'messages'",
")",
":",
"assert",
"isinstance",
"(",
"id",
",",
"(",
"str",
",",
"unicode",
")",
")",
"assert",
"isinstance",
"(",
"domain",
",",
"(",
"str",
",",
"unicode",
")",
")",
"if",
... | Gets a message translation.
@rtype: str
@return: The message translation | [
"Gets",
"a",
"message",
"translation",
"."
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L114-L130 | train | Gets a message translation. |
adamziel/python_translate | python_translate/translations.py | MessageCatalogue.replace | def replace(self, messages, domain='messages'):
"""
Sets translations for a given domain.
"""
assert isinstance(messages, (dict, CaseInsensitiveDict))
assert isinstance(domain, (str, unicode))
self.messages[domain] = CaseInsensitiveDict({})
self.add(messages, dom... | python | def replace(self, messages, domain='messages'):
"""
Sets translations for a given domain.
"""
assert isinstance(messages, (dict, CaseInsensitiveDict))
assert isinstance(domain, (str, unicode))
self.messages[domain] = CaseInsensitiveDict({})
self.add(messages, dom... | [
"def",
"replace",
"(",
"self",
",",
"messages",
",",
"domain",
"=",
"'messages'",
")",
":",
"assert",
"isinstance",
"(",
"messages",
",",
"(",
"dict",
",",
"CaseInsensitiveDict",
")",
")",
"assert",
"isinstance",
"(",
"domain",
",",
"(",
"str",
",",
"uni... | Sets translations for a given domain. | [
"Sets",
"translations",
"for",
"a",
"given",
"domain",
"."
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L132-L140 | train | Sets translations for a given domain. |
adamziel/python_translate | python_translate/translations.py | MessageCatalogue.add_catalogue | def add_catalogue(self, catalogue):
"""
Merges translations from the given Catalogue into the current one.
The two catalogues must have the same locale.
@type id: The
@param id: message id
"""
assert isinstance(catalogue, MessageCatalogue)
if catalogue.... | python | def add_catalogue(self, catalogue):
"""
Merges translations from the given Catalogue into the current one.
The two catalogues must have the same locale.
@type id: The
@param id: message id
"""
assert isinstance(catalogue, MessageCatalogue)
if catalogue.... | [
"def",
"add_catalogue",
"(",
"self",
",",
"catalogue",
")",
":",
"assert",
"isinstance",
"(",
"catalogue",
",",
"MessageCatalogue",
")",
"if",
"catalogue",
".",
"locale",
"!=",
"self",
".",
"locale",
":",
"raise",
"ValueError",
"(",
"'Cannot add a catalogue for ... | Merges translations from the given Catalogue into the current one.
The two catalogues must have the same locale.
@type id: The
@param id: message id | [
"Merges",
"translations",
"from",
"the",
"given",
"Catalogue",
"into",
"the",
"current",
"one",
".",
"The",
"two",
"catalogues",
"must",
"have",
"the",
"same",
"locale",
"."
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L154-L175 | train | Adds a new MessageCatalogue into the current MessageCatalogue. |
adamziel/python_translate | python_translate/translations.py | MessageCatalogue.add_fallback_catalogue | def add_fallback_catalogue(self, catalogue):
"""
Merges translations from the given Catalogue into the current one
only when the translation does not exist.
This is used to provide default translations when they do not exist
for the current locale.
@type id: The
... | python | def add_fallback_catalogue(self, catalogue):
"""
Merges translations from the given Catalogue into the current one
only when the translation does not exist.
This is used to provide default translations when they do not exist
for the current locale.
@type id: The
... | [
"def",
"add_fallback_catalogue",
"(",
"self",
",",
"catalogue",
")",
":",
"assert",
"isinstance",
"(",
"catalogue",
",",
"MessageCatalogue",
")",
"# detect circular references",
"c",
"=",
"self",
"while",
"True",
":",
"if",
"c",
".",
"locale",
"==",
"catalogue",... | Merges translations from the given Catalogue into the current one
only when the translation does not exist.
This is used to provide default translations when they do not exist
for the current locale.
@type id: The
@param id: message id | [
"Merges",
"translations",
"from",
"the",
"given",
"Catalogue",
"into",
"the",
"current",
"one",
"only",
"when",
"the",
"translation",
"does",
"not",
"exist",
"."
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L177-L207 | train | Adds the given one
to the current one
only when the translation does not exist. |
adamziel/python_translate | python_translate/translations.py | Translator.trans | def trans(self, id, parameters=None, domain=None, locale=None):
"""
Translates the given message.
@type id: str
@param id: The message id
@type parameters: dict
@param parameters: A dict of parameters for the message
@type domain: str
@param domain: The... | python | def trans(self, id, parameters=None, domain=None, locale=None):
"""
Translates the given message.
@type id: str
@param id: The message id
@type parameters: dict
@param parameters: A dict of parameters for the message
@type domain: str
@param domain: The... | [
"def",
"trans",
"(",
"self",
",",
"id",
",",
"parameters",
"=",
"None",
",",
"domain",
"=",
"None",
",",
"locale",
"=",
"None",
")",
":",
"if",
"parameters",
"is",
"None",
":",
"parameters",
"=",
"{",
"}",
"assert",
"isinstance",
"(",
"parameters",
"... | Translates the given message.
@type id: str
@param id: The message id
@type parameters: dict
@param parameters: A dict of parameters for the message
@type domain: str
@param domain: The domain for the message or null to use the default
@type locale: str
... | [
"Translates",
"the",
"given",
"message",
"."
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L266-L298 | train | Returns the translated message with the given id. |
adamziel/python_translate | python_translate/translations.py | Translator.set_fallback_locales | def set_fallback_locales(self, locales):
"""
Sets the fallback locales.
@type locales: list[str]
@param locales: The falback locales
@raises: ValueError: If a locale contains invalid characters
"""
# needed as the fallback locales are linked to the already loade... | python | def set_fallback_locales(self, locales):
"""
Sets the fallback locales.
@type locales: list[str]
@param locales: The falback locales
@raises: ValueError: If a locale contains invalid characters
"""
# needed as the fallback locales are linked to the already loade... | [
"def",
"set_fallback_locales",
"(",
"self",
",",
"locales",
")",
":",
"# needed as the fallback locales are linked to the already loaded",
"# catalogues",
"self",
".",
"catalogues",
"=",
"{",
"}",
"for",
"locale",
"in",
"locales",
":",
"self",
".",
"_assert_valid_locale... | Sets the fallback locales.
@type locales: list[str]
@param locales: The falback locales
@raises: ValueError: If a locale contains invalid characters | [
"Sets",
"the",
"fallback",
"locales",
"."
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L366-L382 | train | Sets the fallback locales. |
adamziel/python_translate | python_translate/translations.py | Translator.add_resource | def add_resource(self, format, resource, locale, domain=None):
"""
Adds a resource
@type format: str
@param format: Name of the loader (@see add_loader)
@type resource: str
@param resource: The resource name
@type locale: str
@type domain: str
@... | python | def add_resource(self, format, resource, locale, domain=None):
"""
Adds a resource
@type format: str
@param format: Name of the loader (@see add_loader)
@type resource: str
@param resource: The resource name
@type locale: str
@type domain: str
@... | [
"def",
"add_resource",
"(",
"self",
",",
"format",
",",
"resource",
",",
"locale",
",",
"domain",
"=",
"None",
")",
":",
"if",
"domain",
"is",
"None",
":",
"domain",
"=",
"'messages'",
"self",
".",
"_assert_valid_locale",
"(",
"locale",
")",
"self",
".",... | Adds a resource
@type format: str
@param format: Name of the loader (@see add_loader)
@type resource: str
@param resource: The resource name
@type locale: str
@type domain: str
@raises: ValueError If the locale contains invalid characters
@return: | [
"Adds",
"a",
"resource",
"@type",
"format",
":",
"str",
"@param",
"format",
":",
"Name",
"of",
"the",
"loader",
"(",
"@see",
"add_loader",
")"
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L387-L410 | train | Adds a resource to the set of available resources. |
adamziel/python_translate | python_translate/translations.py | Translator.get_messages | def get_messages(self, locale=None):
"""
Collects all messages for the given locale.
@type locale: str|one
@param locale: Locale of translations, by default is current locale
@rtype: dict:
@return: dict indexed by catalog name
"""
if locale is None:
... | python | def get_messages(self, locale=None):
"""
Collects all messages for the given locale.
@type locale: str|one
@param locale: Locale of translations, by default is current locale
@rtype: dict:
@return: dict indexed by catalog name
"""
if locale is None:
... | [
"def",
"get_messages",
"(",
"self",
",",
"locale",
"=",
"None",
")",
":",
"if",
"locale",
"is",
"None",
":",
"locale",
"=",
"self",
".",
"locale",
"if",
"locale",
"not",
"in",
"self",
".",
"catalogues",
":",
"self",
".",
"_load_catalogue",
"(",
"locale... | Collects all messages for the given locale.
@type locale: str|one
@param locale: Locale of translations, by default is current locale
@rtype: dict:
@return: dict indexed by catalog name | [
"Collects",
"all",
"messages",
"for",
"the",
"given",
"locale",
"."
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L425-L453 | train | Returns all messages for the given locale. |
adamziel/python_translate | python_translate/translations.py | DebugTranslator.trans | def trans(self, id, parameters=None, domain=None, locale=None):
"""
Throws RuntimeError whenever a message is missing
"""
if parameters is None:
parameters = {}
if locale is None:
locale = self.locale
else:
self._assert_valid_locale(lo... | python | def trans(self, id, parameters=None, domain=None, locale=None):
"""
Throws RuntimeError whenever a message is missing
"""
if parameters is None:
parameters = {}
if locale is None:
locale = self.locale
else:
self._assert_valid_locale(lo... | [
"def",
"trans",
"(",
"self",
",",
"id",
",",
"parameters",
"=",
"None",
",",
"domain",
"=",
"None",
",",
"locale",
"=",
"None",
")",
":",
"if",
"parameters",
"is",
"None",
":",
"parameters",
"=",
"{",
"}",
"if",
"locale",
"is",
"None",
":",
"locale... | Throws RuntimeError whenever a message is missing | [
"Throws",
"RuntimeError",
"whenever",
"a",
"message",
"is",
"missing"
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L528-L553 | train | Returns a string representation of the message with the given parameters. |
adamziel/python_translate | python_translate/translations.py | DebugTranslator.transchoice | def transchoice(self, id, number, parameters=None, domain=None, locale=None):
"""
Raises a RuntimeError whenever a message is missing
@raises: RuntimeError
"""
if parameters is None:
parameters = {}
if locale is None:
locale = self.locale
... | python | def transchoice(self, id, number, parameters=None, domain=None, locale=None):
"""
Raises a RuntimeError whenever a message is missing
@raises: RuntimeError
"""
if parameters is None:
parameters = {}
if locale is None:
locale = self.locale
... | [
"def",
"transchoice",
"(",
"self",
",",
"id",
",",
"number",
",",
"parameters",
"=",
"None",
",",
"domain",
"=",
"None",
",",
"locale",
"=",
"None",
")",
":",
"if",
"parameters",
"is",
"None",
":",
"parameters",
"=",
"{",
"}",
"if",
"locale",
"is",
... | Raises a RuntimeError whenever a message is missing
@raises: RuntimeError | [
"Raises",
"a",
"RuntimeError",
"whenever",
"a",
"message",
"is",
"missing"
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L555-L597 | train | Returns a string that can be used to transchoice a message in a specific locale. |
adamziel/python_translate | python_translate/translations.py | DebugTranslator.get_catalogue | def get_catalogue(self, locale):
"""
Reloads messages catalogue if requested after more than one second
since last reload
"""
if locale is None:
locale = self.locale
if locale not in self.catalogues or datetime.now() - self.last_reload > timedelta(seconds=1):... | python | def get_catalogue(self, locale):
"""
Reloads messages catalogue if requested after more than one second
since last reload
"""
if locale is None:
locale = self.locale
if locale not in self.catalogues or datetime.now() - self.last_reload > timedelta(seconds=1):... | [
"def",
"get_catalogue",
"(",
"self",
",",
"locale",
")",
":",
"if",
"locale",
"is",
"None",
":",
"locale",
"=",
"self",
".",
"locale",
"if",
"locale",
"not",
"in",
"self",
".",
"catalogues",
"or",
"datetime",
".",
"now",
"(",
")",
"-",
"self",
".",
... | Reloads messages catalogue if requested after more than one second
since last reload | [
"Reloads",
"messages",
"catalogue",
"if",
"requested",
"after",
"more",
"than",
"one",
"second",
"since",
"last",
"reload"
] | 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L599-L611 | train | Gets the message catalogue for the given locale. |
rraadd88/rohan | rohan/dandage/db/go.py | get_go_info | def get_go_info(goterm,result='name'):
"""
quickgo
result: 'name','definition','synonyms'
{'numberOfHits': 1,
'results': [{'id': 'GO:0000006',
'isObsolete': False,
'name': 'high-affinity zinc transmembrane transporter activity',
'definition': {'text': 'Enables the transfer of zinc ions (Z... | python | def get_go_info(goterm,result='name'):
"""
quickgo
result: 'name','definition','synonyms'
{'numberOfHits': 1,
'results': [{'id': 'GO:0000006',
'isObsolete': False,
'name': 'high-affinity zinc transmembrane transporter activity',
'definition': {'text': 'Enables the transfer of zinc ions (Z... | [
"def",
"get_go_info",
"(",
"goterm",
",",
"result",
"=",
"'name'",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"f'https://www.ebi.ac.uk/QuickGO/services/ontology/go/terms/{goterm}'",
")",
"try",
":",
"return",
"response",
".",
"json",
"(",
")",
"[",
... | quickgo
result: 'name','definition','synonyms'
{'numberOfHits': 1,
'results': [{'id': 'GO:0000006',
'isObsolete': False,
'name': 'high-affinity zinc transmembrane transporter activity',
'definition': {'text': 'Enables the transfer of zinc ions (Zn2+) from one side of a membrane to the other, prob... | [
"quickgo",
"result",
":",
"name",
"definition",
"synonyms",
"{",
"numberOfHits",
":",
"1",
"results",
":",
"[",
"{",
"id",
":",
"GO",
":",
"0000006",
"isObsolete",
":",
"False",
"name",
":",
"high",
"-",
"affinity",
"zinc",
"transmembrane",
"transporter",
... | b0643a3582a2fffc0165ace69fb80880d92bfb10 | https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/db/go.py#L2-L25 | train | Get info about a particular GO term. |
The-Politico/politico-civic-election-night | electionnight/viewsets/special.py | SpecialMixin.get_serializer_context | def get_serializer_context(self):
"""Adds ``election_day`` to serializer context."""
context = super(SpecialMixin, self).get_serializer_context()
context['election_date'] = self.kwargs['date']
return context | python | def get_serializer_context(self):
"""Adds ``election_day`` to serializer context."""
context = super(SpecialMixin, self).get_serializer_context()
context['election_date'] = self.kwargs['date']
return context | [
"def",
"get_serializer_context",
"(",
"self",
")",
":",
"context",
"=",
"super",
"(",
"SpecialMixin",
",",
"self",
")",
".",
"get_serializer_context",
"(",
")",
"context",
"[",
"'election_date'",
"]",
"=",
"self",
".",
"kwargs",
"[",
"'date'",
"]",
"return",... | Adds ``election_day`` to serializer context. | [
"Adds",
"election_day",
"to",
"serializer",
"context",
"."
] | a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/viewsets/special.py#L30-L34 | train | Adds election_day to serializer context. |
Xion/taipan | taipan/objective/methods.py | is_method | def is_method(arg):
"""Checks whether given object is a method."""
if inspect.ismethod(arg):
return True
if isinstance(arg, NonInstanceMethod):
return True
# Unfortunately, there is no disctinction between instance methods
# that are yet to become part of a class, and regular functi... | python | def is_method(arg):
"""Checks whether given object is a method."""
if inspect.ismethod(arg):
return True
if isinstance(arg, NonInstanceMethod):
return True
# Unfortunately, there is no disctinction between instance methods
# that are yet to become part of a class, and regular functi... | [
"def",
"is_method",
"(",
"arg",
")",
":",
"if",
"inspect",
".",
"ismethod",
"(",
"arg",
")",
":",
"return",
"True",
"if",
"isinstance",
"(",
"arg",
",",
"NonInstanceMethod",
")",
":",
"return",
"True",
"# Unfortunately, there is no disctinction between instance me... | Checks whether given object is a method. | [
"Checks",
"whether",
"given",
"object",
"is",
"a",
"method",
"."
] | f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/objective/methods.py#L20-L35 | train | Checks whether given object is a method. |
UMIACS/qav | qav/questions.py | Question._ask | def _ask(self, answers):
""" Really ask the question.
We may need to populate multiple validators with answers here.
Then ask the question and insert the default value if
appropriate. Finally call the validate function to check all
validators for this question a... | python | def _ask(self, answers):
""" Really ask the question.
We may need to populate multiple validators with answers here.
Then ask the question and insert the default value if
appropriate. Finally call the validate function to check all
validators for this question a... | [
"def",
"_ask",
"(",
"self",
",",
"answers",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"validator",
",",
"list",
")",
":",
"for",
"v",
"in",
"self",
".",
"validator",
":",
"v",
".",
"answers",
"=",
"answers",
"else",
":",
"self",
".",
"validat... | Really ask the question.
We may need to populate multiple validators with answers here.
Then ask the question and insert the default value if
appropriate. Finally call the validate function to check all
validators for this question and returning the answer. | [
"Really",
"ask",
"the",
"question",
"."
] | f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b | https://github.com/UMIACS/qav/blob/f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b/qav/questions.py#L107-L146 | train | Really ask the question. |
UMIACS/qav | qav/questions.py | Question.ask | def ask(self, answers=None):
""" Ask the question, then ask any sub-questions.
This returns a dict with the {value: answer} pairs for the current
question plus all descendant questions.
"""
if answers is None:
answers = {}
_answers = {}
if sel... | python | def ask(self, answers=None):
""" Ask the question, then ask any sub-questions.
This returns a dict with the {value: answer} pairs for the current
question plus all descendant questions.
"""
if answers is None:
answers = {}
_answers = {}
if sel... | [
"def",
"ask",
"(",
"self",
",",
"answers",
"=",
"None",
")",
":",
"if",
"answers",
"is",
"None",
":",
"answers",
"=",
"{",
"}",
"_answers",
"=",
"{",
"}",
"if",
"self",
".",
"multiple",
":",
"print",
"(",
"(",
"bold",
"(",
"'Multiple answers are supp... | Ask the question, then ask any sub-questions.
This returns a dict with the {value: answer} pairs for the current
question plus all descendant questions. | [
"Ask",
"the",
"question",
"then",
"ask",
"any",
"sub",
"-",
"questions",
"."
] | f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b | https://github.com/UMIACS/qav/blob/f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b/qav/questions.py#L148-L175 | train | Ask the question then ask any sub - questions. This returns a dict with the value and answer pairs for the current
question plus all descendant questions. |
UMIACS/qav | qav/questions.py | Question.validate | def validate(self, answer):
""" Validate the answer with our Validator(s)
This will support one or more validator classes being applied to
this question. If there are multiple, all validators must return
True for the answer to be valid.
"""
if answer is None... | python | def validate(self, answer):
""" Validate the answer with our Validator(s)
This will support one or more validator classes being applied to
this question. If there are multiple, all validators must return
True for the answer to be valid.
"""
if answer is None... | [
"def",
"validate",
"(",
"self",
",",
"answer",
")",
":",
"if",
"answer",
"is",
"None",
":",
"return",
"False",
"else",
":",
"if",
"isinstance",
"(",
"self",
".",
"validator",
",",
"list",
")",
":",
"for",
"v",
"in",
"self",
".",
"validator",
":",
"... | Validate the answer with our Validator(s)
This will support one or more validator classes being applied to
this question. If there are multiple, all validators must return
True for the answer to be valid. | [
"Validate",
"the",
"answer",
"with",
"our",
"Validator",
"(",
"s",
")"
] | f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b | https://github.com/UMIACS/qav/blob/f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b/qav/questions.py#L177-L193 | train | Validate the answer with our Validator class |
UMIACS/qav | qav/questions.py | Question.answer | def answer(self):
""" Return the answer for the question from the validator.
This will ultimately only be called on the first validator if
multiple validators have been added.
"""
if isinstance(self.validator, list):
return self.validator[0].choice()
... | python | def answer(self):
""" Return the answer for the question from the validator.
This will ultimately only be called on the first validator if
multiple validators have been added.
"""
if isinstance(self.validator, list):
return self.validator[0].choice()
... | [
"def",
"answer",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"validator",
",",
"list",
")",
":",
"return",
"self",
".",
"validator",
"[",
"0",
"]",
".",
"choice",
"(",
")",
"return",
"self",
".",
"validator",
".",
"choice",
"(",
")... | Return the answer for the question from the validator.
This will ultimately only be called on the first validator if
multiple validators have been added. | [
"Return",
"the",
"answer",
"for",
"the",
"question",
"from",
"the",
"validator",
"."
] | f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b | https://github.com/UMIACS/qav/blob/f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b/qav/questions.py#L195-L203 | train | Return the answer for the question from the validator. |
UMIACS/qav | qav/questions.py | Question.choices | def choices(self):
""" Print the choices for this question.
This may be a empty string and in the case of a list of validators
we will only show the first validator's choices.
"""
if isinstance(self.validator, list):
return self.validator[0].print_choices()
... | python | def choices(self):
""" Print the choices for this question.
This may be a empty string and in the case of a list of validators
we will only show the first validator's choices.
"""
if isinstance(self.validator, list):
return self.validator[0].print_choices()
... | [
"def",
"choices",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"validator",
",",
"list",
")",
":",
"return",
"self",
".",
"validator",
"[",
"0",
"]",
".",
"print_choices",
"(",
")",
"return",
"self",
".",
"validator",
".",
"print_choice... | Print the choices for this question.
This may be a empty string and in the case of a list of validators
we will only show the first validator's choices. | [
"Print",
"the",
"choices",
"for",
"this",
"question",
"."
] | f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b | https://github.com/UMIACS/qav/blob/f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b/qav/questions.py#L205-L213 | train | Print the choices for this question. |
iansf/qj | qj/qj.py | qj | def qj(x='', # pylint: disable=invalid-name
s='',
l=None,
d=False,
p=False,
t=False,
n=False,
r=_QJ_R_MAGIC,
z=False,
b=True,
pad=False,
tfc=False,
tic=False,
toc=False,
time=False,
catch=False,
log_all_call... | python | def qj(x='', # pylint: disable=invalid-name
s='',
l=None,
d=False,
p=False,
t=False,
n=False,
r=_QJ_R_MAGIC,
z=False,
b=True,
pad=False,
tfc=False,
tic=False,
toc=False,
time=False,
catch=False,
log_all_call... | [
"def",
"qj",
"(",
"x",
"=",
"''",
",",
"# pylint: disable=invalid-name",
"s",
"=",
"''",
",",
"l",
"=",
"None",
",",
"d",
"=",
"False",
",",
"p",
"=",
"False",
",",
"t",
"=",
"False",
",",
"n",
"=",
"False",
",",
"r",
"=",
"_QJ_R_MAGIC",
",",
"... | A combined logging and debugging function.
Arguments:
x: The thing to log. x is also the return value. Defaults to '', although
it's somewhat odd to call this function without passing x.
s: Optional string to prefix the log message with. Defaults to '', which
results in the function prefixing t... | [
"A",
"combined",
"logging",
"and",
"debugging",
"function",
"."
] | 179864c62ed5d2d8a11b4e8c95328f68953cfa16 | https://github.com/iansf/qj/blob/179864c62ed5d2d8a11b4e8c95328f68953cfa16/qj/qj.py#L42-L498 | train | A combined logging and debugging function for a given object. |
iansf/qj | qj/qj.py | _timing | def _timing(f, logs_every=100):
"""Decorator to time function calls and log the stats."""
@functools.wraps(f)
def wrap(*args, **kw):
"""The timer function."""
ts = _time.time()
result = f(*args, **kw)
te = _time.time()
qj._call_counts[f] += 1
qj._timings[f] += (te - ts)
count = qj._cal... | python | def _timing(f, logs_every=100):
"""Decorator to time function calls and log the stats."""
@functools.wraps(f)
def wrap(*args, **kw):
"""The timer function."""
ts = _time.time()
result = f(*args, **kw)
te = _time.time()
qj._call_counts[f] += 1
qj._timings[f] += (te - ts)
count = qj._cal... | [
"def",
"_timing",
"(",
"f",
",",
"logs_every",
"=",
"100",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrap",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"\"\"\"The timer function.\"\"\"",
"ts",
"=",
"_time",
".",
"time",
... | Decorator to time function calls and log the stats. | [
"Decorator",
"to",
"time",
"function",
"calls",
"and",
"log",
"the",
"stats",
"."
] | 179864c62ed5d2d8a11b4e8c95328f68953cfa16 | https://github.com/iansf/qj/blob/179864c62ed5d2d8a11b4e8c95328f68953cfa16/qj/qj.py#L596-L611 | train | Decorator to time function calls and log the stats. |
iansf/qj | qj/qj.py | _catch | def _catch(f, exception_type):
"""Decorator to drop into the debugger if a function throws an exception."""
if not (inspect.isclass(exception_type)
and issubclass(exception_type, Exception)):
exception_type = Exception
@functools.wraps(f)
def wrap(*args, **kw):
try:
return f(*args, **kw... | python | def _catch(f, exception_type):
"""Decorator to drop into the debugger if a function throws an exception."""
if not (inspect.isclass(exception_type)
and issubclass(exception_type, Exception)):
exception_type = Exception
@functools.wraps(f)
def wrap(*args, **kw):
try:
return f(*args, **kw... | [
"def",
"_catch",
"(",
"f",
",",
"exception_type",
")",
":",
"if",
"not",
"(",
"inspect",
".",
"isclass",
"(",
"exception_type",
")",
"and",
"issubclass",
"(",
"exception_type",
",",
"Exception",
")",
")",
":",
"exception_type",
"=",
"Exception",
"@",
"func... | Decorator to drop into the debugger if a function throws an exception. | [
"Decorator",
"to",
"drop",
"into",
"the",
"debugger",
"if",
"a",
"function",
"throws",
"an",
"exception",
"."
] | 179864c62ed5d2d8a11b4e8c95328f68953cfa16 | https://github.com/iansf/qj/blob/179864c62ed5d2d8a11b4e8c95328f68953cfa16/qj/qj.py#L615-L627 | train | Decorator to drop into the debugger if a function throws an exception. |
iansf/qj | qj/qj.py | _disassemble3 | def _disassemble3(co, lasti):
"""Disassemble a code object."""
cell_names = co.co_cellvars + co.co_freevars
linestarts = dict(dis.findlinestarts(co))
_disassemble_bytes(co.co_code, lasti, co.co_varnames, co.co_names,
co.co_consts, cell_names, linestarts) | python | def _disassemble3(co, lasti):
"""Disassemble a code object."""
cell_names = co.co_cellvars + co.co_freevars
linestarts = dict(dis.findlinestarts(co))
_disassemble_bytes(co.co_code, lasti, co.co_varnames, co.co_names,
co.co_consts, cell_names, linestarts) | [
"def",
"_disassemble3",
"(",
"co",
",",
"lasti",
")",
":",
"cell_names",
"=",
"co",
".",
"co_cellvars",
"+",
"co",
".",
"co_freevars",
"linestarts",
"=",
"dict",
"(",
"dis",
".",
"findlinestarts",
"(",
"co",
")",
")",
"_disassemble_bytes",
"(",
"co",
"."... | Disassemble a code object. | [
"Disassemble",
"a",
"code",
"object",
"."
] | 179864c62ed5d2d8a11b4e8c95328f68953cfa16 | https://github.com/iansf/qj/blob/179864c62ed5d2d8a11b4e8c95328f68953cfa16/qj/qj.py#L637-L642 | train | Disassemble a code object. |
iansf/qj | qj/qj.py | _stack_effect3 | def _stack_effect3(op_code, oparg):
"""Compute the effect an op_code and oparg have on the stack. See python/compile.c."""
if op_code == 'UNPACK_SEQUENCE':
return oparg - 1
if op_code == 'UNPACK_EX':
return (oparg & 0xFF) + (oparg >> 8)
if op_code == 'BUILD_TUPLE':
return -oparg # Was 1 - oparg
... | python | def _stack_effect3(op_code, oparg):
"""Compute the effect an op_code and oparg have on the stack. See python/compile.c."""
if op_code == 'UNPACK_SEQUENCE':
return oparg - 1
if op_code == 'UNPACK_EX':
return (oparg & 0xFF) + (oparg >> 8)
if op_code == 'BUILD_TUPLE':
return -oparg # Was 1 - oparg
... | [
"def",
"_stack_effect3",
"(",
"op_code",
",",
"oparg",
")",
":",
"if",
"op_code",
"==",
"'UNPACK_SEQUENCE'",
":",
"return",
"oparg",
"-",
"1",
"if",
"op_code",
"==",
"'UNPACK_EX'",
":",
"return",
"(",
"oparg",
"&",
"0xFF",
")",
"+",
"(",
"oparg",
">>",
... | Compute the effect an op_code and oparg have on the stack. See python/compile.c. | [
"Compute",
"the",
"effect",
"an",
"op_code",
"and",
"oparg",
"have",
"on",
"the",
"stack",
".",
"See",
"python",
"/",
"compile",
".",
"c",
"."
] | 179864c62ed5d2d8a11b4e8c95328f68953cfa16 | https://github.com/iansf/qj/blob/179864c62ed5d2d8a11b4e8c95328f68953cfa16/qj/qj.py#L931-L979 | train | Compute the effect an op_code and oparg have on the stack. |
iansf/qj | qj/qj.py | _findlinestarts | def _findlinestarts(code):
"""Find the offsets in a byte code which are start of lines in the source.
Generate pairs (offset, lineno) as described in Python/compile.c.
Arguments:
code: code object.
Yields:
Address and line number pairs.
"""
byte_increments = [ord(c) for c in code.co_lnotab[0::2]]... | python | def _findlinestarts(code):
"""Find the offsets in a byte code which are start of lines in the source.
Generate pairs (offset, lineno) as described in Python/compile.c.
Arguments:
code: code object.
Yields:
Address and line number pairs.
"""
byte_increments = [ord(c) for c in code.co_lnotab[0::2]]... | [
"def",
"_findlinestarts",
"(",
"code",
")",
":",
"byte_increments",
"=",
"[",
"ord",
"(",
"c",
")",
"for",
"c",
"in",
"code",
".",
"co_lnotab",
"[",
"0",
":",
":",
"2",
"]",
"]",
"line_increments",
"=",
"[",
"ord",
"(",
"c",
")",
"for",
"c",
"in"... | Find the offsets in a byte code which are start of lines in the source.
Generate pairs (offset, lineno) as described in Python/compile.c.
Arguments:
code: code object.
Yields:
Address and line number pairs. | [
"Find",
"the",
"offsets",
"in",
"a",
"byte",
"code",
"which",
"are",
"start",
"of",
"lines",
"in",
"the",
"source",
"."
] | 179864c62ed5d2d8a11b4e8c95328f68953cfa16 | https://github.com/iansf/qj/blob/179864c62ed5d2d8a11b4e8c95328f68953cfa16/qj/qj.py#L986-L1011 | train | Find the offsets in a byte code which are start of lines in the source. |
iansf/qj | qj/qj.py | _stack_effect | def _stack_effect(op_code, oparg):
"""Compute the effect an op_code and oparg have on the stack. See python/compile.c."""
n_args = lambda o: (o % 256) + 2 * (o // 256)
if op_code == 'DUP_TOPX':
return oparg
elif op_code == 'UNPACK_SEQUENCE':
return oparg - 1
elif op_code == 'BUILD_TUPLE':
return... | python | def _stack_effect(op_code, oparg):
"""Compute the effect an op_code and oparg have on the stack. See python/compile.c."""
n_args = lambda o: (o % 256) + 2 * (o // 256)
if op_code == 'DUP_TOPX':
return oparg
elif op_code == 'UNPACK_SEQUENCE':
return oparg - 1
elif op_code == 'BUILD_TUPLE':
return... | [
"def",
"_stack_effect",
"(",
"op_code",
",",
"oparg",
")",
":",
"n_args",
"=",
"lambda",
"o",
":",
"(",
"o",
"%",
"256",
")",
"+",
"2",
"*",
"(",
"o",
"//",
"256",
")",
"if",
"op_code",
"==",
"'DUP_TOPX'",
":",
"return",
"oparg",
"elif",
"op_code",... | Compute the effect an op_code and oparg have on the stack. See python/compile.c. | [
"Compute",
"the",
"effect",
"an",
"op_code",
"and",
"oparg",
"have",
"on",
"the",
"stack",
".",
"See",
"python",
"/",
"compile",
".",
"c",
"."
] | 179864c62ed5d2d8a11b4e8c95328f68953cfa16 | https://github.com/iansf/qj/blob/179864c62ed5d2d8a11b4e8c95328f68953cfa16/qj/qj.py#L1193-L1227 | train | Compute the effect an op_code and oparg have on the stack. |
iansf/qj | qj/qj.py | _annotate_fn_args | def _annotate_fn_args(stack, fn_opname, nargs, nkw=-1, consume_fn_name=True):
"""Add commas and equals as appropriate to function argument lists in the stack."""
kwarg_names = []
if nkw == -1:
if sys.version_info[0] < 3:
# Compute nkw and nargs from nargs for python 2.7
nargs, nkw = (nargs % 256, ... | python | def _annotate_fn_args(stack, fn_opname, nargs, nkw=-1, consume_fn_name=True):
"""Add commas and equals as appropriate to function argument lists in the stack."""
kwarg_names = []
if nkw == -1:
if sys.version_info[0] < 3:
# Compute nkw and nargs from nargs for python 2.7
nargs, nkw = (nargs % 256, ... | [
"def",
"_annotate_fn_args",
"(",
"stack",
",",
"fn_opname",
",",
"nargs",
",",
"nkw",
"=",
"-",
"1",
",",
"consume_fn_name",
"=",
"True",
")",
":",
"kwarg_names",
"=",
"[",
"]",
"if",
"nkw",
"==",
"-",
"1",
":",
"if",
"sys",
".",
"version_info",
"[",... | Add commas and equals as appropriate to function argument lists in the stack. | [
"Add",
"commas",
"and",
"equals",
"as",
"appropriate",
"to",
"function",
"argument",
"lists",
"in",
"the",
"stack",
"."
] | 179864c62ed5d2d8a11b4e8c95328f68953cfa16 | https://github.com/iansf/qj/blob/179864c62ed5d2d8a11b4e8c95328f68953cfa16/qj/qj.py#L1299-L1357 | train | Add commas and equals as appropriate to function argument lists in the stack. |
iansf/qj | qj/qj.py | _collect_pops | def _collect_pops(stack, depth, pops, skip):
"""Recursively collects stack entries off the top of the stack according to the stack entry's depth."""
if depth >= 0:
return pops
set_current_depth_after_recursion = False
set_skip_for_current_entry_children = False
set_skip_after_current_entry = False
extr... | python | def _collect_pops(stack, depth, pops, skip):
"""Recursively collects stack entries off the top of the stack according to the stack entry's depth."""
if depth >= 0:
return pops
set_current_depth_after_recursion = False
set_skip_for_current_entry_children = False
set_skip_after_current_entry = False
extr... | [
"def",
"_collect_pops",
"(",
"stack",
",",
"depth",
",",
"pops",
",",
"skip",
")",
":",
"if",
"depth",
">=",
"0",
":",
"return",
"pops",
"set_current_depth_after_recursion",
"=",
"False",
"set_skip_for_current_entry_children",
"=",
"False",
"set_skip_after_current_e... | Recursively collects stack entries off the top of the stack according to the stack entry's depth. | [
"Recursively",
"collects",
"stack",
"entries",
"off",
"the",
"top",
"of",
"the",
"stack",
"according",
"to",
"the",
"stack",
"entry",
"s",
"depth",
"."
] | 179864c62ed5d2d8a11b4e8c95328f68953cfa16 | https://github.com/iansf/qj/blob/179864c62ed5d2d8a11b4e8c95328f68953cfa16/qj/qj.py#L1360-L1523 | train | Recursively collects stack entries off the top of the stack according to the stack entry s depth. |
iansf/qj | qj/qj.py | _find_current_fn_call | def _find_current_fn_call(co, lasti):
"""Find current function call in the byte code."""
qj._DEBUG_QJ and qj.LOG_FN('co = {}'.format(co))
if sys.version_info[0] < 3:
stack = _build_instruction_stack(co, lasti)
else:
stack = _build_instruction_stack3(co, lasti)
source_lines, source_offset = inspect.g... | python | def _find_current_fn_call(co, lasti):
"""Find current function call in the byte code."""
qj._DEBUG_QJ and qj.LOG_FN('co = {}'.format(co))
if sys.version_info[0] < 3:
stack = _build_instruction_stack(co, lasti)
else:
stack = _build_instruction_stack3(co, lasti)
source_lines, source_offset = inspect.g... | [
"def",
"_find_current_fn_call",
"(",
"co",
",",
"lasti",
")",
":",
"qj",
".",
"_DEBUG_QJ",
"and",
"qj",
".",
"LOG_FN",
"(",
"'co = {}'",
".",
"format",
"(",
"co",
")",
")",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
"3",
":",
"stack",
"=... | Find current function call in the byte code. | [
"Find",
"current",
"function",
"call",
"in",
"the",
"byte",
"code",
"."
] | 179864c62ed5d2d8a11b4e8c95328f68953cfa16 | https://github.com/iansf/qj/blob/179864c62ed5d2d8a11b4e8c95328f68953cfa16/qj/qj.py#L1687-L1805 | train | Find the current function call in the byte code. |
tjcsl/cslbot | cslbot/commands/cve.py | cmd | def cmd(send, msg, args):
"""Gets info on a CVE id from MITRE's CVE database
Syntax: {command} <cveid>
"""
elements = msg.split('-')
if len(elements) > 3 or len(elements) < 2:
send("Invalid CVE format")
return
# If there are three fields, ignore the first (we don't actually need ... | python | def cmd(send, msg, args):
"""Gets info on a CVE id from MITRE's CVE database
Syntax: {command} <cveid>
"""
elements = msg.split('-')
if len(elements) > 3 or len(elements) < 2:
send("Invalid CVE format")
return
# If there are three fields, ignore the first (we don't actually need ... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"elements",
"=",
"msg",
".",
"split",
"(",
"'-'",
")",
"if",
"len",
"(",
"elements",
")",
">",
"3",
"or",
"len",
"(",
"elements",
")",
"<",
"2",
":",
"send",
"(",
"\"Invalid CVE format... | Gets info on a CVE id from MITRE's CVE database
Syntax: {command} <cveid> | [
"Gets",
"info",
"on",
"a",
"CVE",
"id",
"from",
"MITRE",
"s",
"CVE",
"database",
"Syntax",
":",
"{",
"command",
"}",
"<cveid",
">"
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/cve.py#L29-L56 | train | Gets info on a CVE id from MITRE s CVE database |
dubsmash/config-reader | config_reader/reader.py | ConfigReader._read_file_data | def _read_file_data(self, path):
"""
Attempts to read the contents of the given configuration file.
:param path: Path to a configuration file.
:raises: ConfigParseError if file does not exist or cannot be read.
:return: Dictionary of configuration data.
"""
_, ext... | python | def _read_file_data(self, path):
"""
Attempts to read the contents of the given configuration file.
:param path: Path to a configuration file.
:raises: ConfigParseError if file does not exist or cannot be read.
:return: Dictionary of configuration data.
"""
_, ext... | [
"def",
"_read_file_data",
"(",
"self",
",",
"path",
")",
":",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"path",
")",
"# YAML files",
"if",
"ext",
"in",
"(",
"'.yml'",
",",
"'.yaml'",
")",
":",
"try",
":",
"with",
"open",
"(",
... | Attempts to read the contents of the given configuration file.
:param path: Path to a configuration file.
:raises: ConfigParseError if file does not exist or cannot be read.
:return: Dictionary of configuration data. | [
"Attempts",
"to",
"read",
"the",
"contents",
"of",
"the",
"given",
"configuration",
"file",
".",
":",
"param",
"path",
":",
"Path",
"to",
"a",
"configuration",
"file",
".",
":",
"raises",
":",
"ConfigParseError",
"if",
"file",
"does",
"not",
"exist",
"or",... | 0c76bb96925a44945e2f79c8cd1b57354d4e4562 | https://github.com/dubsmash/config-reader/blob/0c76bb96925a44945e2f79c8cd1b57354d4e4562/config_reader/reader.py#L40-L62 | train | Reads the contents of the given configuration file. |
dubsmash/config-reader | config_reader/reader.py | ConfigReader.get_int | def get_int(self, key, optional=False):
"""
Tries to fetch a variable from the config and expects it to be strictly an int
:param key: Variable to look for
:param optional: Whether to raise ConfigKeyNotFoundError if key was not found.
:return: int
"""
return self.... | python | def get_int(self, key, optional=False):
"""
Tries to fetch a variable from the config and expects it to be strictly an int
:param key: Variable to look for
:param optional: Whether to raise ConfigKeyNotFoundError if key was not found.
:return: int
"""
return self.... | [
"def",
"get_int",
"(",
"self",
",",
"key",
",",
"optional",
"=",
"False",
")",
":",
"return",
"self",
".",
"_get_typed_value",
"(",
"key",
",",
"int",
",",
"lambda",
"x",
":",
"int",
"(",
"x",
")",
",",
"optional",
")"
] | Tries to fetch a variable from the config and expects it to be strictly an int
:param key: Variable to look for
:param optional: Whether to raise ConfigKeyNotFoundError if key was not found.
:return: int | [
"Tries",
"to",
"fetch",
"a",
"variable",
"from",
"the",
"config",
"and",
"expects",
"it",
"to",
"be",
"strictly",
"an",
"int",
":",
"param",
"key",
":",
"Variable",
"to",
"look",
"for",
":",
"param",
"optional",
":",
"Whether",
"to",
"raise",
"ConfigKeyN... | 0c76bb96925a44945e2f79c8cd1b57354d4e4562 | https://github.com/dubsmash/config-reader/blob/0c76bb96925a44945e2f79c8cd1b57354d4e4562/config_reader/reader.py#L64-L71 | train | Tries to fetch a variable from the config and expects it to be strictly an int |
dubsmash/config-reader | config_reader/reader.py | ConfigReader.get_float | def get_float(self, key, optional=False):
"""
Tries to fetch a variable from the config and expects it to be strictly a float
:param key: Variable to look for
:param optional: Whether to raise ConfigKeyNotFoundError if key was not found
:return: float
"""
return s... | python | def get_float(self, key, optional=False):
"""
Tries to fetch a variable from the config and expects it to be strictly a float
:param key: Variable to look for
:param optional: Whether to raise ConfigKeyNotFoundError if key was not found
:return: float
"""
return s... | [
"def",
"get_float",
"(",
"self",
",",
"key",
",",
"optional",
"=",
"False",
")",
":",
"return",
"self",
".",
"_get_typed_value",
"(",
"key",
",",
"float",
",",
"lambda",
"x",
":",
"float",
"(",
"x",
")",
",",
"optional",
")"
] | Tries to fetch a variable from the config and expects it to be strictly a float
:param key: Variable to look for
:param optional: Whether to raise ConfigKeyNotFoundError if key was not found
:return: float | [
"Tries",
"to",
"fetch",
"a",
"variable",
"from",
"the",
"config",
"and",
"expects",
"it",
"to",
"be",
"strictly",
"a",
"float",
":",
"param",
"key",
":",
"Variable",
"to",
"look",
"for",
":",
"param",
"optional",
":",
"Whether",
"to",
"raise",
"ConfigKey... | 0c76bb96925a44945e2f79c8cd1b57354d4e4562 | https://github.com/dubsmash/config-reader/blob/0c76bb96925a44945e2f79c8cd1b57354d4e4562/config_reader/reader.py#L73-L80 | train | Tries to fetch a variable from the config and expects it to be strictly a float |
dubsmash/config-reader | config_reader/reader.py | ConfigReader.get_boolean | def get_boolean(self, key, optional=False):
"""
Tries to fetch a variable from the config and expects it to be a truthy value. This could be a string ("1", "Y")
or an actual boolean. This is because we use the strtobool function in the case we find a string. The function
strtobool expect... | python | def get_boolean(self, key, optional=False):
"""
Tries to fetch a variable from the config and expects it to be a truthy value. This could be a string ("1", "Y")
or an actual boolean. This is because we use the strtobool function in the case we find a string. The function
strtobool expect... | [
"def",
"get_boolean",
"(",
"self",
",",
"key",
",",
"optional",
"=",
"False",
")",
":",
"return",
"self",
".",
"_get_typed_value",
"(",
"key",
",",
"bool",
",",
"lambda",
"x",
":",
"bool",
"(",
"util",
".",
"strtobool",
"(",
"x",
")",
")",
",",
"op... | Tries to fetch a variable from the config and expects it to be a truthy value. This could be a string ("1", "Y")
or an actual boolean. This is because we use the strtobool function in the case we find a string. The function
strtobool expects values of the form ("1", "Y", "YES", "true", "True", "t") and ... | [
"Tries",
"to",
"fetch",
"a",
"variable",
"from",
"the",
"config",
"and",
"expects",
"it",
"to",
"be",
"a",
"truthy",
"value",
".",
"This",
"could",
"be",
"a",
"string",
"(",
"1",
"Y",
")",
"or",
"an",
"actual",
"boolean",
".",
"This",
"is",
"because"... | 0c76bb96925a44945e2f79c8cd1b57354d4e4562 | https://github.com/dubsmash/config-reader/blob/0c76bb96925a44945e2f79c8cd1b57354d4e4562/config_reader/reader.py#L82-L93 | train | Tries to fetch a variable from the config and expects it to be a truthy value. |
dubsmash/config-reader | config_reader/reader.py | ConfigReader.get_string | def get_string(self, key, optional=False):
"""
Tries to fetch a variable from the config and expects it to be a string
:param key: The variable to search for in a possible list of configs
:param optional: Whether to raise ConfigKeyNotFoundError if key was not found.
:return: str ... | python | def get_string(self, key, optional=False):
"""
Tries to fetch a variable from the config and expects it to be a string
:param key: The variable to search for in a possible list of configs
:param optional: Whether to raise ConfigKeyNotFoundError if key was not found.
:return: str ... | [
"def",
"get_string",
"(",
"self",
",",
"key",
",",
"optional",
"=",
"False",
")",
":",
"return",
"self",
".",
"_get_typed_value",
"(",
"key",
",",
"str",
",",
"lambda",
"x",
":",
"str",
"(",
"x",
")",
",",
"optional",
")"
] | Tries to fetch a variable from the config and expects it to be a string
:param key: The variable to search for in a possible list of configs
:param optional: Whether to raise ConfigKeyNotFoundError if key was not found.
:return: str string | [
"Tries",
"to",
"fetch",
"a",
"variable",
"from",
"the",
"config",
"and",
"expects",
"it",
"to",
"be",
"a",
"string",
":",
"param",
"key",
":",
"The",
"variable",
"to",
"search",
"for",
"in",
"a",
"possible",
"list",
"of",
"configs",
":",
"param",
"opti... | 0c76bb96925a44945e2f79c8cd1b57354d4e4562 | https://github.com/dubsmash/config-reader/blob/0c76bb96925a44945e2f79c8cd1b57354d4e4562/config_reader/reader.py#L95-L102 | train | Tries to fetch a string from the config and expects it to be a string. |
dubsmash/config-reader | config_reader/reader.py | ConfigReader.get_string_list | def get_string_list(self, key, optional=False):
"""
Tries to fetch a string which could be composed of multiple lines, with each line having some sort of
separator. Try to convert the string fetched into a list by separating on the given separator, defaulting to
the newline character. If... | python | def get_string_list(self, key, optional=False):
"""
Tries to fetch a string which could be composed of multiple lines, with each line having some sort of
separator. Try to convert the string fetched into a list by separating on the given separator, defaulting to
the newline character. If... | [
"def",
"get_string_list",
"(",
"self",
",",
"key",
",",
"optional",
"=",
"False",
")",
":",
"try",
":",
"return",
"self",
".",
"_get_typed_value",
"(",
"key",
",",
"list",
",",
"lambda",
"x",
":",
"x",
".",
"splitlines",
"(",
")",
",",
"optional",
")... | Tries to fetch a string which could be composed of multiple lines, with each line having some sort of
separator. Try to convert the string fetched into a list by separating on the given separator, defaulting to
the newline character. If the string is not present we just return None.
:param key: ... | [
"Tries",
"to",
"fetch",
"a",
"string",
"which",
"could",
"be",
"composed",
"of",
"multiple",
"lines",
"with",
"each",
"line",
"having",
"some",
"sort",
"of",
"separator",
".",
"Try",
"to",
"convert",
"the",
"string",
"fetched",
"into",
"a",
"list",
"by",
... | 0c76bb96925a44945e2f79c8cd1b57354d4e4562 | https://github.com/dubsmash/config-reader/blob/0c76bb96925a44945e2f79c8cd1b57354d4e4562/config_reader/reader.py#L104-L117 | train | Tries to fetch a string which could be composed of multiple lines with each line having some sort of
separator. If the string could not be fetched it will return None. If the string could not be fetched it will return an empty list. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.