repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
sunlightlabs/django-locksmith | locksmith/hub/views.py | profile | def profile(request):
'''
Viewing of signup details and editing of password
'''
context = {}
if request.method == 'POST':
form = PasswordChangeForm(request.user, request.POST)
if form.is_valid():
form.save()
messages.info(request, 'Password Changed.')
... | python | def profile(request):
'''
Viewing of signup details and editing of password
'''
context = {}
if request.method == 'POST':
form = PasswordChangeForm(request.user, request.POST)
if form.is_valid():
form.save()
messages.info(request, 'Password Changed.')
... | [
"def",
"profile",
"(",
"request",
")",
":",
"context",
"=",
"{",
"}",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"form",
"=",
"PasswordChangeForm",
"(",
"request",
".",
"user",
",",
"request",
".",
"POST",
")",
"if",
"form",
".",
"is_valid",
... | Viewing of signup details and editing of password | [
"Viewing",
"of",
"signup",
"details",
"and",
"editing",
"of",
"password"
] | train | https://github.com/sunlightlabs/django-locksmith/blob/eef5b7c25404560aaad50b6e622594f89239b74b/locksmith/hub/views.py#L180-L208 |
sunlightlabs/django-locksmith | locksmith/hub/views.py | _dictlist_to_lists | def _dictlist_to_lists(dl, *keys):
''' convert a list of dictionaries to a dictionary of lists
>>> dl = [{'a': 'test', 'b': 3}, {'a': 'zaz', 'b': 444},
{'a': 'wow', 'b': 300}]
>>> _dictlist_to_lists(dl)
(['test', 'zaz', 'wow'], [3, 444, 300])
'''
lists = []
for k in keys:
... | python | def _dictlist_to_lists(dl, *keys):
''' convert a list of dictionaries to a dictionary of lists
>>> dl = [{'a': 'test', 'b': 3}, {'a': 'zaz', 'b': 444},
{'a': 'wow', 'b': 300}]
>>> _dictlist_to_lists(dl)
(['test', 'zaz', 'wow'], [3, 444, 300])
'''
lists = []
for k in keys:
... | [
"def",
"_dictlist_to_lists",
"(",
"dl",
",",
"*",
"keys",
")",
":",
"lists",
"=",
"[",
"]",
"for",
"k",
"in",
"keys",
":",
"lists",
".",
"append",
"(",
"[",
"]",
")",
"for",
"item",
"in",
"dl",
":",
"for",
"i",
",",
"key",
"in",
"enumerate",
"(... | convert a list of dictionaries to a dictionary of lists
>>> dl = [{'a': 'test', 'b': 3}, {'a': 'zaz', 'b': 444},
{'a': 'wow', 'b': 300}]
>>> _dictlist_to_lists(dl)
(['test', 'zaz', 'wow'], [3, 444, 300]) | [
"convert",
"a",
"list",
"of",
"dictionaries",
"to",
"a",
"dictionary",
"of",
"lists"
] | train | https://github.com/sunlightlabs/django-locksmith/blob/eef5b7c25404560aaad50b6e622594f89239b74b/locksmith/hub/views.py#L212-L229 |
sunlightlabs/django-locksmith | locksmith/hub/views.py | _cumulative_by_date | def _cumulative_by_date(model, datefield):
'''
Given a model and date field, generate monthly cumulative totals.
'''
monthly_counts = defaultdict(int)
for obj in model.objects.all().order_by(datefield):
datevalue = getattr(obj, datefield)
monthkey = (datevalue.year, datevalue.mon... | python | def _cumulative_by_date(model, datefield):
'''
Given a model and date field, generate monthly cumulative totals.
'''
monthly_counts = defaultdict(int)
for obj in model.objects.all().order_by(datefield):
datevalue = getattr(obj, datefield)
monthkey = (datevalue.year, datevalue.mon... | [
"def",
"_cumulative_by_date",
"(",
"model",
",",
"datefield",
")",
":",
"monthly_counts",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"obj",
"in",
"model",
".",
"objects",
".",
"all",
"(",
")",
".",
"order_by",
"(",
"datefield",
")",
":",
"datevalue",
"=... | Given a model and date field, generate monthly cumulative totals. | [
"Given",
"a",
"model",
"and",
"date",
"field",
"generate",
"monthly",
"cumulative",
"totals",
"."
] | train | https://github.com/sunlightlabs/django-locksmith/blob/eef5b7c25404560aaad50b6e622594f89239b74b/locksmith/hub/views.py#L231-L254 |
luismasuelli/python-cantrips | cantrips/types/exception.py | factory | def factory(codes, base=_Exception):
"""
Creates a custom exception class with arbitrary error codes and arguments.
"""
if not issubclass(base, _Exception):
raise FactoryException("Invalid class passed as parent: Must be a subclass of an Exception class created with this function",
... | python | def factory(codes, base=_Exception):
"""
Creates a custom exception class with arbitrary error codes and arguments.
"""
if not issubclass(base, _Exception):
raise FactoryException("Invalid class passed as parent: Must be a subclass of an Exception class created with this function",
... | [
"def",
"factory",
"(",
"codes",
",",
"base",
"=",
"_Exception",
")",
":",
"if",
"not",
"issubclass",
"(",
"base",
",",
"_Exception",
")",
":",
"raise",
"FactoryException",
"(",
"\"Invalid class passed as parent: Must be a subclass of an Exception class created with this f... | Creates a custom exception class with arbitrary error codes and arguments. | [
"Creates",
"a",
"custom",
"exception",
"class",
"with",
"arbitrary",
"error",
"codes",
"and",
"arguments",
"."
] | train | https://github.com/luismasuelli/python-cantrips/blob/dba2742c1d1a60863bb65f4a291464f6e68eb2ee/cantrips/types/exception.py#L11-L37 |
hactar-is/frink | frink/orm.py | InstanceLayerMixin.save | def save(self):
"""
Save the current instance to the DB
"""
with rconnect() as conn:
try:
self.validate()
except ValidationError as e:
log.warn(e.messages)
raise
except ModelValidationError as e:
... | python | def save(self):
"""
Save the current instance to the DB
"""
with rconnect() as conn:
try:
self.validate()
except ValidationError as e:
log.warn(e.messages)
raise
except ModelValidationError as e:
... | [
"def",
"save",
"(",
"self",
")",
":",
"with",
"rconnect",
"(",
")",
"as",
"conn",
":",
"try",
":",
"self",
".",
"validate",
"(",
")",
"except",
"ValidationError",
"as",
"e",
":",
"log",
".",
"warn",
"(",
"e",
".",
"messages",
")",
"raise",
"except"... | Save the current instance to the DB | [
"Save",
"the",
"current",
"instance",
"to",
"the",
"DB"
] | train | https://github.com/hactar-is/frink/blob/0d2c11daca8ef6d4365e98914bdc0bc65478ae72/frink/orm.py#L33-L90 |
hactar-is/frink | frink/orm.py | InstanceLayerMixin.delete | def delete(self):
"""
Delete the current instance from the DB.
"""
with rconnect() as conn:
# Can't delete an object without an ID.
if self.id is None:
raise FrinkError("You can't delete an object with no ID")
else:
... | python | def delete(self):
"""
Delete the current instance from the DB.
"""
with rconnect() as conn:
# Can't delete an object without an ID.
if self.id is None:
raise FrinkError("You can't delete an object with no ID")
else:
... | [
"def",
"delete",
"(",
"self",
")",
":",
"with",
"rconnect",
"(",
")",
"as",
"conn",
":",
"# Can't delete an object without an ID.",
"if",
"self",
".",
"id",
"is",
"None",
":",
"raise",
"FrinkError",
"(",
"\"You can't delete an object with no ID\"",
")",
"else",
... | Delete the current instance from the DB. | [
"Delete",
"the",
"current",
"instance",
"from",
"the",
"DB",
"."
] | train | https://github.com/hactar-is/frink/blob/0d2c11daca8ef6d4365e98914bdc0bc65478ae72/frink/orm.py#L92-L118 |
hactar-is/frink | frink/orm.py | ORMLayer.get | def get(self, id):
"""
Get a single instance by pk id.
:param id: The UUID of the instance you want to retrieve.
"""
with rconnect() as conn:
if id is None:
raise ValueError
if isinstance(id, uuid.UUID):
id = str(... | python | def get(self, id):
"""
Get a single instance by pk id.
:param id: The UUID of the instance you want to retrieve.
"""
with rconnect() as conn:
if id is None:
raise ValueError
if isinstance(id, uuid.UUID):
id = str(... | [
"def",
"get",
"(",
"self",
",",
"id",
")",
":",
"with",
"rconnect",
"(",
")",
"as",
"conn",
":",
"if",
"id",
"is",
"None",
":",
"raise",
"ValueError",
"if",
"isinstance",
"(",
"id",
",",
"uuid",
".",
"UUID",
")",
":",
"id",
"=",
"str",
"(",
"id... | Get a single instance by pk id.
:param id: The UUID of the instance you want to retrieve. | [
"Get",
"a",
"single",
"instance",
"by",
"pk",
"id",
"."
] | train | https://github.com/hactar-is/frink/blob/0d2c11daca8ef6d4365e98914bdc0bc65478ae72/frink/orm.py#L148-L178 |
hactar-is/frink | frink/orm.py | ORMLayer.filter | def filter(self, order_by=None, limit=0, **kwargs):
"""
Fetch a list of instances.
:param order_by: column on which to order the results. \
To change the sort, prepend with < or >.
:param limit: How many rows to fetch.
:param kwargs: keyword args on w... | python | def filter(self, order_by=None, limit=0, **kwargs):
"""
Fetch a list of instances.
:param order_by: column on which to order the results. \
To change the sort, prepend with < or >.
:param limit: How many rows to fetch.
:param kwargs: keyword args on w... | [
"def",
"filter",
"(",
"self",
",",
"order_by",
"=",
"None",
",",
"limit",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"rconnect",
"(",
")",
"as",
"conn",
":",
"if",
"len",
"(",
"kwargs",
")",
"==",
"0",
":",
"raise",
"ValueError",
"try",... | Fetch a list of instances.
:param order_by: column on which to order the results. \
To change the sort, prepend with < or >.
:param limit: How many rows to fetch.
:param kwargs: keyword args on which to filter, column=value | [
"Fetch",
"a",
"list",
"of",
"instances",
"."
] | train | https://github.com/hactar-is/frink/blob/0d2c11daca8ef6d4365e98914bdc0bc65478ae72/frink/orm.py#L180-L215 |
hactar-is/frink | frink/orm.py | ORMLayer.find_by | def find_by(self, column=None, value=None, order_by=None, limit=0):
"""
Find all items that matches your a column/value.
:param column: column to search.
:param value: value to look for in `column`.
:param limit: How many rows to fetch.
:param order_b... | python | def find_by(self, column=None, value=None, order_by=None, limit=0):
"""
Find all items that matches your a column/value.
:param column: column to search.
:param value: value to look for in `column`.
:param limit: How many rows to fetch.
:param order_b... | [
"def",
"find_by",
"(",
"self",
",",
"column",
"=",
"None",
",",
"value",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"limit",
"=",
"0",
")",
":",
"with",
"rconnect",
"(",
")",
"as",
"conn",
":",
"if",
"column",
"is",
"None",
"or",
"value",
"i... | Find all items that matches your a column/value.
:param column: column to search.
:param value: value to look for in `column`.
:param limit: How many rows to fetch.
:param order_by: column on which to order the results. \
To change the sort, prepend with < or... | [
"Find",
"all",
"items",
"that",
"matches",
"your",
"a",
"column",
"/",
"value",
"."
] | train | https://github.com/hactar-is/frink/blob/0d2c11daca8ef6d4365e98914bdc0bc65478ae72/frink/orm.py#L255-L284 |
hactar-is/frink | frink/orm.py | ORMLayer.get_by | def get_by(self, column=None, value=None):
"""
Find one item that matches your a column/value. Raises `NotUniqueError` if
it finds more than one.
:param column: column to search.
:param value: value to look for in `column`.
:param limit: How many rows... | python | def get_by(self, column=None, value=None):
"""
Find one item that matches your a column/value. Raises `NotUniqueError` if
it finds more than one.
:param column: column to search.
:param value: value to look for in `column`.
:param limit: How many rows... | [
"def",
"get_by",
"(",
"self",
",",
"column",
"=",
"None",
",",
"value",
"=",
"None",
")",
":",
"with",
"rconnect",
"(",
")",
"as",
"conn",
":",
"if",
"column",
"is",
"None",
"or",
"value",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"You need to... | Find one item that matches your a column/value. Raises `NotUniqueError` if
it finds more than one.
:param column: column to search.
:param value: value to look for in `column`.
:param limit: How many rows to fetch.
:param order_by: column on which to order th... | [
"Find",
"one",
"item",
"that",
"matches",
"your",
"a",
"column",
"/",
"value",
".",
"Raises",
"NotUniqueError",
"if",
"it",
"finds",
"more",
"than",
"one",
"."
] | train | https://github.com/hactar-is/frink/blob/0d2c11daca8ef6d4365e98914bdc0bc65478ae72/frink/orm.py#L286-L318 |
hactar-is/frink | frink/orm.py | ORMLayer.all | def all(self, order_by=None, limit=0):
"""
Fetch all items.
:param limit: How many rows to fetch.
:param order_by: column on which to order the results. \
To change the sort, prepend with < or >.
"""
with rconnect() as conn:
try:
... | python | def all(self, order_by=None, limit=0):
"""
Fetch all items.
:param limit: How many rows to fetch.
:param order_by: column on which to order the results. \
To change the sort, prepend with < or >.
"""
with rconnect() as conn:
try:
... | [
"def",
"all",
"(",
"self",
",",
"order_by",
"=",
"None",
",",
"limit",
"=",
"0",
")",
":",
"with",
"rconnect",
"(",
")",
"as",
"conn",
":",
"try",
":",
"query",
"=",
"self",
".",
"_base",
"(",
")",
"if",
"order_by",
"is",
"not",
"None",
":",
"q... | Fetch all items.
:param limit: How many rows to fetch.
:param order_by: column on which to order the results. \
To change the sort, prepend with < or >. | [
"Fetch",
"all",
"items",
"."
] | train | https://github.com/hactar-is/frink/blob/0d2c11daca8ef6d4365e98914bdc0bc65478ae72/frink/orm.py#L320-L344 |
Exanis/django-rest-generators | django_rest_generators/steps/database.py | then_a_model_exists | def then_a_model_exists(context, model_name, key, value):
"""
:type model_name: str
:type key: str
:type value: str
:type context: behave.runner.Context
"""
model = apps.get_model(model_name)
args = {
key: value
}
obj = model.objects.get(**args)
assert obj... | python | def then_a_model_exists(context, model_name, key, value):
"""
:type model_name: str
:type key: str
:type value: str
:type context: behave.runner.Context
"""
model = apps.get_model(model_name)
args = {
key: value
}
obj = model.objects.get(**args)
assert obj... | [
"def",
"then_a_model_exists",
"(",
"context",
",",
"model_name",
",",
"key",
",",
"value",
")",
":",
"model",
"=",
"apps",
".",
"get_model",
"(",
"model_name",
")",
"args",
"=",
"{",
"key",
":",
"value",
"}",
"obj",
"=",
"model",
".",
"objects",
".",
... | :type model_name: str
:type key: str
:type value: str
:type context: behave.runner.Context | [
":",
"type",
"model_name",
":",
"str",
":",
"type",
"key",
":",
"str",
":",
"type",
"value",
":",
"str",
":",
"type",
"context",
":",
"behave",
".",
"runner",
".",
"Context"
] | train | https://github.com/Exanis/django-rest-generators/blob/fb14ccbba8cb029dc056d852bc13d9216dc924e4/django_rest_generators/steps/database.py#L9-L21 |
Exanis/django-rest-generators | django_rest_generators/steps/database.py | then_no_model_exists | def then_no_model_exists(context, model_name, key, value):
"""
:type model_name: str
:type key: str
:type value: str
:type context: behave.runner.Context
"""
model = apps.get_model(model_name)
args = {
key: value
}
obj = model.objects.filter(**args)
assert... | python | def then_no_model_exists(context, model_name, key, value):
"""
:type model_name: str
:type key: str
:type value: str
:type context: behave.runner.Context
"""
model = apps.get_model(model_name)
args = {
key: value
}
obj = model.objects.filter(**args)
assert... | [
"def",
"then_no_model_exists",
"(",
"context",
",",
"model_name",
",",
"key",
",",
"value",
")",
":",
"model",
"=",
"apps",
".",
"get_model",
"(",
"model_name",
")",
"args",
"=",
"{",
"key",
":",
"value",
"}",
"obj",
"=",
"model",
".",
"objects",
".",
... | :type model_name: str
:type key: str
:type value: str
:type context: behave.runner.Context | [
":",
"type",
"model_name",
":",
"str",
":",
"type",
"key",
":",
"str",
":",
"type",
"value",
":",
"str",
":",
"type",
"context",
":",
"behave",
".",
"runner",
".",
"Context"
] | train | https://github.com/Exanis/django-rest-generators/blob/fb14ccbba8cb029dc056d852bc13d9216dc924e4/django_rest_generators/steps/database.py#L25-L37 |
dusty-phillips/opterator | opterator.py | generate_options | def generate_options():
'''Helper coroutine to identify short options that haven't been used
yet. Yields lists of short option (if available) and long option for
the given name, keeping track of which short options have been previously
used.
If you aren't familiar with coroutines, use similar to a ... | python | def generate_options():
'''Helper coroutine to identify short options that haven't been used
yet. Yields lists of short option (if available) and long option for
the given name, keeping track of which short options have been previously
used.
If you aren't familiar with coroutines, use similar to a ... | [
"def",
"generate_options",
"(",
")",
":",
"used_short_options",
"=",
"set",
"(",
")",
"param_name",
"=",
"yield",
"while",
"True",
":",
"names",
"=",
"[",
"'--'",
"+",
"param_name",
"]",
"for",
"letter",
"in",
"param_name",
":",
"if",
"letter",
"not",
"i... | Helper coroutine to identify short options that haven't been used
yet. Yields lists of short option (if available) and long option for
the given name, keeping track of which short options have been previously
used.
If you aren't familiar with coroutines, use similar to a generator:
x = generate_opt... | [
"Helper",
"coroutine",
"to",
"identify",
"short",
"options",
"that",
"haven",
"t",
"been",
"used",
"yet",
".",
"Yields",
"lists",
"of",
"short",
"option",
"(",
"if",
"available",
")",
"and",
"long",
"option",
"for",
"the",
"given",
"name",
"keeping",
"trac... | train | https://github.com/dusty-phillips/opterator/blob/84fe31f22c73dc0a3666ed82c179461b1799c257/opterator.py#L29-L49 |
dusty-phillips/opterator | opterator.py | portable_argspec | def portable_argspec(func):
'''
Given a function, return a tuple of
(positional_params, keyword_params, varargs, defaults, annotations)
where
* positional_params is a list of parameters that don't have default values
* keyword_params is a list of parameters that have default values
* varargs... | python | def portable_argspec(func):
'''
Given a function, return a tuple of
(positional_params, keyword_params, varargs, defaults, annotations)
where
* positional_params is a list of parameters that don't have default values
* keyword_params is a list of parameters that have default values
* varargs... | [
"def",
"portable_argspec",
"(",
"func",
")",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
":",
"# PYTHON 2 MUST DIE",
"argnames",
",",
"varargs",
",",
"varkw",
",",
"defaults",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
... | Given a function, return a tuple of
(positional_params, keyword_params, varargs, defaults, annotations)
where
* positional_params is a list of parameters that don't have default values
* keyword_params is a list of parameters that have default values
* varargs is the string name for variable argumen... | [
"Given",
"a",
"function",
"return",
"a",
"tuple",
"of",
"(",
"positional_params",
"keyword_params",
"varargs",
"defaults",
"annotations",
")",
"where",
"*",
"positional_params",
"is",
"a",
"list",
"of",
"parameters",
"that",
"don",
"t",
"have",
"default",
"value... | train | https://github.com/dusty-phillips/opterator/blob/84fe31f22c73dc0a3666ed82c179461b1799c257/opterator.py#L52-L78 |
dusty-phillips/opterator | opterator.py | opterate | def opterate(func):
'''A decorator for a main function entry point to a script. It
automatically generates the options for the main entry point based on the
arguments, keyword arguments, and docstring.
All keyword arguments in the function definition are options. Positional
arguments are mandatory ... | python | def opterate(func):
'''A decorator for a main function entry point to a script. It
automatically generates the options for the main entry point based on the
arguments, keyword arguments, and docstring.
All keyword arguments in the function definition are options. Positional
arguments are mandatory ... | [
"def",
"opterate",
"(",
"func",
")",
":",
"(",
"positional_params",
",",
"kw_params",
",",
"varargs",
",",
"defaults",
",",
"annotations",
")",
"=",
"portable_argspec",
"(",
"func",
")",
"description",
"=",
"''",
"param_docs",
"=",
"{",
"}",
"if",
"func",
... | A decorator for a main function entry point to a script. It
automatically generates the options for the main entry point based on the
arguments, keyword arguments, and docstring.
All keyword arguments in the function definition are options. Positional
arguments are mandatory arguments that store a stri... | [
"A",
"decorator",
"for",
"a",
"main",
"function",
"entry",
"point",
"to",
"a",
"script",
".",
"It",
"automatically",
"generates",
"the",
"options",
"for",
"the",
"main",
"entry",
"point",
"based",
"on",
"the",
"arguments",
"keyword",
"arguments",
"and",
"doc... | train | https://github.com/dusty-phillips/opterator/blob/84fe31f22c73dc0a3666ed82c179461b1799c257/opterator.py#L81-L175 |
mayfield/shellish | shellish/command/contrib/syscomplete.py | SystemCompletion.show_setup | def show_setup(self):
""" Provide a helper script for the user to setup completion. """
shell = os.getenv('SHELL')
if not shell:
raise SystemError("No $SHELL env var found")
shell = os.path.basename(shell)
if shell not in self.script_body:
raise SystemErro... | python | def show_setup(self):
""" Provide a helper script for the user to setup completion. """
shell = os.getenv('SHELL')
if not shell:
raise SystemError("No $SHELL env var found")
shell = os.path.basename(shell)
if shell not in self.script_body:
raise SystemErro... | [
"def",
"show_setup",
"(",
"self",
")",
":",
"shell",
"=",
"os",
".",
"getenv",
"(",
"'SHELL'",
")",
"if",
"not",
"shell",
":",
"raise",
"SystemError",
"(",
"\"No $SHELL env var found\"",
")",
"shell",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"shell"... | Provide a helper script for the user to setup completion. | [
"Provide",
"a",
"helper",
"script",
"for",
"the",
"user",
"to",
"setup",
"completion",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/command/contrib/syscomplete.py#L84-L99 |
mayfield/shellish | shellish/command/contrib/syscomplete.py | SystemCompletion.trim | def trim(self, text):
""" Trim whitespace indentation from text. """
lines = text.splitlines()
firstline = lines[0] or lines[1]
indent = len(firstline) - len(firstline.lstrip())
return '\n'.join(x[indent:] for x in lines if x.strip()) | python | def trim(self, text):
""" Trim whitespace indentation from text. """
lines = text.splitlines()
firstline = lines[0] or lines[1]
indent = len(firstline) - len(firstline.lstrip())
return '\n'.join(x[indent:] for x in lines if x.strip()) | [
"def",
"trim",
"(",
"self",
",",
"text",
")",
":",
"lines",
"=",
"text",
".",
"splitlines",
"(",
")",
"firstline",
"=",
"lines",
"[",
"0",
"]",
"or",
"lines",
"[",
"1",
"]",
"indent",
"=",
"len",
"(",
"firstline",
")",
"-",
"len",
"(",
"firstline... | Trim whitespace indentation from text. | [
"Trim",
"whitespace",
"indentation",
"from",
"text",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/command/contrib/syscomplete.py#L101-L106 |
holmes-app/holmes-alf | holmesalf/wrapper.py | AlfAuthNZWrapper.sync_client | def sync_client(self):
"""Synchronous OAuth 2.0 Bearer client"""
if not self._sync_client:
self._sync_client = AlfSyncClient(
token_endpoint=self.config.get('OAUTH_TOKEN_ENDPOINT'),
client_id=self.config.get('OAUTH_CLIENT_ID'),
client_secret=se... | python | def sync_client(self):
"""Synchronous OAuth 2.0 Bearer client"""
if not self._sync_client:
self._sync_client = AlfSyncClient(
token_endpoint=self.config.get('OAUTH_TOKEN_ENDPOINT'),
client_id=self.config.get('OAUTH_CLIENT_ID'),
client_secret=se... | [
"def",
"sync_client",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_sync_client",
":",
"self",
".",
"_sync_client",
"=",
"AlfSyncClient",
"(",
"token_endpoint",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'OAUTH_TOKEN_ENDPOINT'",
")",
",",
"client_id"... | Synchronous OAuth 2.0 Bearer client | [
"Synchronous",
"OAuth",
"2",
".",
"0",
"Bearer",
"client"
] | train | https://github.com/holmes-app/holmes-alf/blob/4bf891831390ecfae818cf37d8ffc3a76fe9f1ec/holmesalf/wrapper.py#L26-L34 |
holmes-app/holmes-alf | holmesalf/wrapper.py | AlfAuthNZWrapper.async_client | def async_client(self):
"""Asynchronous OAuth 2.0 Bearer client"""
if not self._async_client:
self._async_client = AlfAsyncClient(
token_endpoint=self.config.get('OAUTH_TOKEN_ENDPOINT'),
client_id=self.config.get('OAUTH_CLIENT_ID'),
client_secr... | python | def async_client(self):
"""Asynchronous OAuth 2.0 Bearer client"""
if not self._async_client:
self._async_client = AlfAsyncClient(
token_endpoint=self.config.get('OAUTH_TOKEN_ENDPOINT'),
client_id=self.config.get('OAUTH_CLIENT_ID'),
client_secr... | [
"def",
"async_client",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_async_client",
":",
"self",
".",
"_async_client",
"=",
"AlfAsyncClient",
"(",
"token_endpoint",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'OAUTH_TOKEN_ENDPOINT'",
")",
",",
"client... | Asynchronous OAuth 2.0 Bearer client | [
"Asynchronous",
"OAuth",
"2",
".",
"0",
"Bearer",
"client"
] | train | https://github.com/holmes-app/holmes-alf/blob/4bf891831390ecfae818cf37d8ffc3a76fe9f1ec/holmesalf/wrapper.py#L37-L45 |
thwehner/python-firepit | setup.py | get_package_version | def get_package_version():
"""returns package version without importing it"""
base = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(base, "firepit/__init__.py")) as pkg:
for line in pkg:
m = version.match(line.strip())
if not m:
continue
... | python | def get_package_version():
"""returns package version without importing it"""
base = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(base, "firepit/__init__.py")) as pkg:
for line in pkg:
m = version.match(line.strip())
if not m:
continue
... | [
"def",
"get_package_version",
"(",
")",
":",
"base",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"\"firepit/__init__... | returns package version without importing it | [
"returns",
"package",
"version",
"without",
"importing",
"it"
] | train | https://github.com/thwehner/python-firepit/blob/68aa3b9c9e034e6a9a3498d997ac8d9a03f8c0f9/setup.py#L12-L20 |
pavelsof/ipalint | ipalint/ipa.py | Recogniser._load_ipa_data | def _load_ipa_data(self, ipa_data_path):
"""
Loads and returns the {symbol: name} dictionary stored in the
data/ipa.tsv file.
"""
ipa = {}
try:
with open(ipa_data_path, newline='') as f:
reader = csv.reader(f, delimiter='\t')
for line in reader:
if len(line) != 2:
continue
if li... | python | def _load_ipa_data(self, ipa_data_path):
"""
Loads and returns the {symbol: name} dictionary stored in the
data/ipa.tsv file.
"""
ipa = {}
try:
with open(ipa_data_path, newline='') as f:
reader = csv.reader(f, delimiter='\t')
for line in reader:
if len(line) != 2:
continue
if li... | [
"def",
"_load_ipa_data",
"(",
"self",
",",
"ipa_data_path",
")",
":",
"ipa",
"=",
"{",
"}",
"try",
":",
"with",
"open",
"(",
"ipa_data_path",
",",
"newline",
"=",
"''",
")",
"as",
"f",
":",
"reader",
"=",
"csv",
".",
"reader",
"(",
"f",
",",
"delim... | Loads and returns the {symbol: name} dictionary stored in the
data/ipa.tsv file. | [
"Loads",
"and",
"returns",
"the",
"{",
"symbol",
":",
"name",
"}",
"dictionary",
"stored",
"in",
"the",
"data",
"/",
"ipa",
".",
"tsv",
"file",
"."
] | train | https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/ipa.py#L81-L104 |
pavelsof/ipalint | ipalint/ipa.py | Recogniser._load_common_err_data | def _load_common_err_data(self, common_err_data_path):
"""
Loads and returns the {bad: good} dictionary stored in the common
errors data file. Note that the dict's keys are single characters while
the values do not have to be. The method also asserts that all the
values are valid IPA strings.
"""
common_e... | python | def _load_common_err_data(self, common_err_data_path):
"""
Loads and returns the {bad: good} dictionary stored in the common
errors data file. Note that the dict's keys are single characters while
the values do not have to be. The method also asserts that all the
values are valid IPA strings.
"""
common_e... | [
"def",
"_load_common_err_data",
"(",
"self",
",",
"common_err_data_path",
")",
":",
"common_err",
"=",
"{",
"}",
"try",
":",
"with",
"open",
"(",
"common_err_data_path",
",",
"newline",
"=",
"''",
")",
"as",
"f",
":",
"reader",
"=",
"csv",
".",
"reader",
... | Loads and returns the {bad: good} dictionary stored in the common
errors data file. Note that the dict's keys are single characters while
the values do not have to be. The method also asserts that all the
values are valid IPA strings. | [
"Loads",
"and",
"returns",
"the",
"{",
"bad",
":",
"good",
"}",
"dictionary",
"stored",
"in",
"the",
"common",
"errors",
"data",
"file",
".",
"Note",
"that",
"the",
"dict",
"s",
"keys",
"are",
"single",
"characters",
"while",
"the",
"values",
"do",
"not"... | train | https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/ipa.py#L107-L135 |
pavelsof/ipalint | ipalint/ipa.py | Recogniser.get_nfc_chars | def get_nfc_chars(self):
"""
Returns the set of IPA symbols that are precomposed (decomposable)
chars. These should not be decomposed during string normalisation,
because they will not be recognised otherwise.
In IPA 2015 there is only one precomposed character: ç, the voiceless
palatal fricative.
"""
... | python | def get_nfc_chars(self):
"""
Returns the set of IPA symbols that are precomposed (decomposable)
chars. These should not be decomposed during string normalisation,
because they will not be recognised otherwise.
In IPA 2015 there is only one precomposed character: ç, the voiceless
palatal fricative.
"""
... | [
"def",
"get_nfc_chars",
"(",
"self",
")",
":",
"ex",
"=",
"[",
"]",
"for",
"char",
"in",
"self",
".",
"ipa",
".",
"keys",
"(",
")",
":",
"if",
"len",
"(",
"char",
")",
"==",
"1",
":",
"decomp",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFD'",
... | Returns the set of IPA symbols that are precomposed (decomposable)
chars. These should not be decomposed during string normalisation,
because they will not be recognised otherwise.
In IPA 2015 there is only one precomposed character: ç, the voiceless
palatal fricative. | [
"Returns",
"the",
"set",
"of",
"IPA",
"symbols",
"that",
"are",
"precomposed",
"(",
"decomposable",
")",
"chars",
".",
"These",
"should",
"not",
"be",
"decomposed",
"during",
"string",
"normalisation",
"because",
"they",
"will",
"not",
"be",
"recognised",
"oth... | train | https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/ipa.py#L138-L155 |
pavelsof/ipalint | ipalint/ipa.py | Recogniser.recognise | def recognise(self, string, line_num):
"""
Splits the string into chars and distributes these into the buckets of
IPA and non-IPA symbols. Expects that there are no precomposed chars in
the string.
"""
symbols = []
unknown = []
for char in string:
if char == SPACE:
continue
try:
name = u... | python | def recognise(self, string, line_num):
"""
Splits the string into chars and distributes these into the buckets of
IPA and non-IPA symbols. Expects that there are no precomposed chars in
the string.
"""
symbols = []
unknown = []
for char in string:
if char == SPACE:
continue
try:
name = u... | [
"def",
"recognise",
"(",
"self",
",",
"string",
",",
"line_num",
")",
":",
"symbols",
"=",
"[",
"]",
"unknown",
"=",
"[",
"]",
"for",
"char",
"in",
"string",
":",
"if",
"char",
"==",
"SPACE",
":",
"continue",
"try",
":",
"name",
"=",
"unicodedata",
... | Splits the string into chars and distributes these into the buckets of
IPA and non-IPA symbols. Expects that there are no precomposed chars in
the string. | [
"Splits",
"the",
"string",
"into",
"chars",
"and",
"distributes",
"these",
"into",
"the",
"buckets",
"of",
"IPA",
"and",
"non",
"-",
"IPA",
"symbols",
".",
"Expects",
"that",
"there",
"are",
"no",
"precomposed",
"chars",
"in",
"the",
"string",
"."
] | train | https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/ipa.py#L158-L185 |
pavelsof/ipalint | ipalint/ipa.py | Recogniser.report | def report(self, reporter):
"""
Adds the problems that have been found so far to the given Reporter
instance.
"""
for symbol in sorted(self.unk_symbols.keys()):
err = '{} ({}) is not part of IPA'.format(symbol.char, symbol.name)
if symbol.char in self.common_err:
repl = self.common_err[symbol.char]... | python | def report(self, reporter):
"""
Adds the problems that have been found so far to the given Reporter
instance.
"""
for symbol in sorted(self.unk_symbols.keys()):
err = '{} ({}) is not part of IPA'.format(symbol.char, symbol.name)
if symbol.char in self.common_err:
repl = self.common_err[symbol.char]... | [
"def",
"report",
"(",
"self",
",",
"reporter",
")",
":",
"for",
"symbol",
"in",
"sorted",
"(",
"self",
".",
"unk_symbols",
".",
"keys",
"(",
")",
")",
":",
"err",
"=",
"'{} ({}) is not part of IPA'",
".",
"format",
"(",
"symbol",
".",
"char",
",",
"sym... | Adds the problems that have been found so far to the given Reporter
instance. | [
"Adds",
"the",
"problems",
"that",
"have",
"been",
"found",
"so",
"far",
"to",
"the",
"given",
"Reporter",
"instance",
"."
] | train | https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/ipa.py#L188-L202 |
pztrick/DjScript | setup.py | custom_install.run_npm | def run_npm(self):
""" h/t https://github.com/elbaschid/virtual-node/blob/master/setup.py """
for name, version in npm_dependencies.items():
# packages are installed globally to make sure that they are
# installed in the virtualenv rather than the current directory.
... | python | def run_npm(self):
""" h/t https://github.com/elbaschid/virtual-node/blob/master/setup.py """
for name, version in npm_dependencies.items():
# packages are installed globally to make sure that they are
# installed in the virtualenv rather than the current directory.
... | [
"def",
"run_npm",
"(",
"self",
")",
":",
"for",
"name",
",",
"version",
"in",
"npm_dependencies",
".",
"items",
"(",
")",
":",
"# packages are installed globally to make sure that they are",
"# installed in the virtualenv rather than the current directory.",
"# it is also neces... | h/t https://github.com/elbaschid/virtual-node/blob/master/setup.py | [
"h",
"/",
"t",
"https",
":",
"//",
"github",
".",
"com",
"/",
"elbaschid",
"/",
"virtual",
"-",
"node",
"/",
"blob",
"/",
"master",
"/",
"setup",
".",
"py"
] | train | https://github.com/pztrick/DjScript/blob/a1fc3b975e7ba7015ef3e5d3d69e02d69b7c1d24/setup.py#L17-L25 |
pztrick/DjScript | setup.py | custom_install.run_cmd | def run_cmd(self, cmd, cwd=None, extra_env=None):
""" h/t https://github.com/elbaschid/virtual-node/blob/master/setup.py """
all_output = []
cmd_parts = []
for part in cmd:
if len(part) > 45:
part = part[:20] + "..." + part[-20:]
if ' ' in part or... | python | def run_cmd(self, cmd, cwd=None, extra_env=None):
""" h/t https://github.com/elbaschid/virtual-node/blob/master/setup.py """
all_output = []
cmd_parts = []
for part in cmd:
if len(part) > 45:
part = part[:20] + "..." + part[-20:]
if ' ' in part or... | [
"def",
"run_cmd",
"(",
"self",
",",
"cmd",
",",
"cwd",
"=",
"None",
",",
"extra_env",
"=",
"None",
")",
":",
"all_output",
"=",
"[",
"]",
"cmd_parts",
"=",
"[",
"]",
"for",
"part",
"in",
"cmd",
":",
"if",
"len",
"(",
"part",
")",
">",
"45",
":"... | h/t https://github.com/elbaschid/virtual-node/blob/master/setup.py | [
"h",
"/",
"t",
"https",
":",
"//",
"github",
".",
"com",
"/",
"elbaschid",
"/",
"virtual",
"-",
"node",
"/",
"blob",
"/",
"master",
"/",
"setup",
".",
"py"
] | train | https://github.com/pztrick/DjScript/blob/a1fc3b975e7ba7015ef3e5d3d69e02d69b7c1d24/setup.py#L27-L79 |
mrstephenneal/dirutility | dirutility/gui.py | WalkGUI.parsing | def parsing(self):
"""Parameters for parsing directory trees"""
with gui.FlexForm(self.title, auto_size_text=True, default_element_size=(40, 1)) as form:
layout = [
[gui.Text('Directory Paths utility', size=(30, 1), font=("Helvetica", 25), text_color='blue')],
... | python | def parsing(self):
"""Parameters for parsing directory trees"""
with gui.FlexForm(self.title, auto_size_text=True, default_element_size=(40, 1)) as form:
layout = [
[gui.Text('Directory Paths utility', size=(30, 1), font=("Helvetica", 25), text_color='blue')],
... | [
"def",
"parsing",
"(",
"self",
")",
":",
"with",
"gui",
".",
"FlexForm",
"(",
"self",
".",
"title",
",",
"auto_size_text",
"=",
"True",
",",
"default_element_size",
"=",
"(",
"40",
",",
"1",
")",
")",
"as",
"form",
":",
"layout",
"=",
"[",
"[",
"gu... | Parameters for parsing directory trees | [
"Parameters",
"for",
"parsing",
"directory",
"trees"
] | train | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/gui.py#L51-L114 |
mrstephenneal/dirutility | dirutility/gui.py | BackupZipGUI.source | def source(self):
"""Parameters for saving zip backups"""
with gui.FlexForm(self.title, auto_size_text=True, default_element_size=(40, 1)) as form:
layout = [
[gui.Text('Zip Backup utility', size=(30, 1), font=("Helvetica", 30), text_color='blue')],
[gui.Text(... | python | def source(self):
"""Parameters for saving zip backups"""
with gui.FlexForm(self.title, auto_size_text=True, default_element_size=(40, 1)) as form:
layout = [
[gui.Text('Zip Backup utility', size=(30, 1), font=("Helvetica", 30), text_color='blue')],
[gui.Text(... | [
"def",
"source",
"(",
"self",
")",
":",
"with",
"gui",
".",
"FlexForm",
"(",
"self",
".",
"title",
",",
"auto_size_text",
"=",
"True",
",",
"default_element_size",
"=",
"(",
"40",
",",
"1",
")",
")",
"as",
"form",
":",
"layout",
"=",
"[",
"[",
"gui... | Parameters for saving zip backups | [
"Parameters",
"for",
"saving",
"zip",
"backups"
] | train | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/gui.py#L123-L143 |
Pertino/pertino-sdk-python | pertinosdk/__init__.py | QueryBuilder.contains | def contains(self, desired):
'''Return the filter closure fully constructed.'''
field = self.__field
def aFilter(testDictionary):
return (desired in testDictionary[field])
return aFilter | python | def contains(self, desired):
'''Return the filter closure fully constructed.'''
field = self.__field
def aFilter(testDictionary):
return (desired in testDictionary[field])
return aFilter | [
"def",
"contains",
"(",
"self",
",",
"desired",
")",
":",
"field",
"=",
"self",
".",
"__field",
"def",
"aFilter",
"(",
"testDictionary",
")",
":",
"return",
"(",
"desired",
"in",
"testDictionary",
"[",
"field",
"]",
")",
"return",
"aFilter"
] | Return the filter closure fully constructed. | [
"Return",
"the",
"filter",
"closure",
"fully",
"constructed",
"."
] | train | https://github.com/Pertino/pertino-sdk-python/blob/d7d75bd374b7f44967ae6f1626a6520507be3a54/pertinosdk/__init__.py#L20-L25 |
Pertino/pertino-sdk-python | pertinosdk/__init__.py | PertinoSdk.listOrgs | def listOrgs(self, closure=lambda x: True):
"""
:param closure: optional filter of the results :py:QueryBuilder
:returns: a list of organizations (as dictionaries) you belong to.
:raises: HTTP errors
"""
url = self.BASE_URL+self.BASE_PATH+self.ORGS_PATH+self.USER_QUERY
... | python | def listOrgs(self, closure=lambda x: True):
"""
:param closure: optional filter of the results :py:QueryBuilder
:returns: a list of organizations (as dictionaries) you belong to.
:raises: HTTP errors
"""
url = self.BASE_URL+self.BASE_PATH+self.ORGS_PATH+self.USER_QUERY
... | [
"def",
"listOrgs",
"(",
"self",
",",
"closure",
"=",
"lambda",
"x",
":",
"True",
")",
":",
"url",
"=",
"self",
".",
"BASE_URL",
"+",
"self",
".",
"BASE_PATH",
"+",
"self",
".",
"ORGS_PATH",
"+",
"self",
".",
"USER_QUERY",
"response",
"=",
"self",
"."... | :param closure: optional filter of the results :py:QueryBuilder
:returns: a list of organizations (as dictionaries) you belong to.
:raises: HTTP errors | [
":",
"param",
"closure",
":",
"optional",
"filter",
"of",
"the",
"results",
":",
"py",
":",
"QueryBuilder",
":",
"returns",
":",
"a",
"list",
"of",
"organizations",
"(",
"as",
"dictionaries",
")",
"you",
"belong",
"to",
".",
":",
"raises",
":",
"HTTP",
... | train | https://github.com/Pertino/pertino-sdk-python/blob/d7d75bd374b7f44967ae6f1626a6520507be3a54/pertinosdk/__init__.py#L53-L62 |
Pertino/pertino-sdk-python | pertinosdk/__init__.py | PertinoSdk.listDevicesIn | def listDevicesIn(self, organization, closure=lambda x: True):
"""
:param closure: optional filter of the results :py:QueryBuilder
:returns: a list of devices (as dictionaries) in organization
:raises: HTTP errors
"""
url = self.BASE_URL+self.BASE_PATH+self.ORGS_PATH+"/"+... | python | def listDevicesIn(self, organization, closure=lambda x: True):
"""
:param closure: optional filter of the results :py:QueryBuilder
:returns: a list of devices (as dictionaries) in organization
:raises: HTTP errors
"""
url = self.BASE_URL+self.BASE_PATH+self.ORGS_PATH+"/"+... | [
"def",
"listDevicesIn",
"(",
"self",
",",
"organization",
",",
"closure",
"=",
"lambda",
"x",
":",
"True",
")",
":",
"url",
"=",
"self",
".",
"BASE_URL",
"+",
"self",
".",
"BASE_PATH",
"+",
"self",
".",
"ORGS_PATH",
"+",
"\"/\"",
"+",
"str",
"(",
"or... | :param closure: optional filter of the results :py:QueryBuilder
:returns: a list of devices (as dictionaries) in organization
:raises: HTTP errors | [
":",
"param",
"closure",
":",
"optional",
"filter",
"of",
"the",
"results",
":",
"py",
":",
"QueryBuilder",
":",
"returns",
":",
"a",
"list",
"of",
"devices",
"(",
"as",
"dictionaries",
")",
"in",
"organization",
":",
"raises",
":",
"HTTP",
"errors"
] | train | https://github.com/Pertino/pertino-sdk-python/blob/d7d75bd374b7f44967ae6f1626a6520507be3a54/pertinosdk/__init__.py#L64-L73 |
Pertino/pertino-sdk-python | pertinosdk/__init__.py | PertinoSdk.deleteFrom | def deleteFrom(self, organization, devices):
"""
Deletes all devices in a list.
:raises: HTTP errors
"""
for device in devices:
url = self.BASE_URL+self.BASE_PATH+self.ORGS_PATH+"/"+ str(organization["id"]) + self.DEVICES_PATH+ "/" + str(device["id"]) + self.USER_QUER... | python | def deleteFrom(self, organization, devices):
"""
Deletes all devices in a list.
:raises: HTTP errors
"""
for device in devices:
url = self.BASE_URL+self.BASE_PATH+self.ORGS_PATH+"/"+ str(organization["id"]) + self.DEVICES_PATH+ "/" + str(device["id"]) + self.USER_QUER... | [
"def",
"deleteFrom",
"(",
"self",
",",
"organization",
",",
"devices",
")",
":",
"for",
"device",
"in",
"devices",
":",
"url",
"=",
"self",
".",
"BASE_URL",
"+",
"self",
".",
"BASE_PATH",
"+",
"self",
".",
"ORGS_PATH",
"+",
"\"/\"",
"+",
"str",
"(",
... | Deletes all devices in a list.
:raises: HTTP errors | [
"Deletes",
"all",
"devices",
"in",
"a",
"list",
".",
":",
"raises",
":",
"HTTP",
"errors"
] | train | https://github.com/Pertino/pertino-sdk-python/blob/d7d75bd374b7f44967ae6f1626a6520507be3a54/pertinosdk/__init__.py#L75-L83 |
marccarre/py_sak | py_sak/validation.py | is_valid_file | def is_valid_file(path):
''' Returns True if provided file exists and is a file, or False otherwise. '''
return os.path.exists(path) and os.path.isfile(path) | python | def is_valid_file(path):
''' Returns True if provided file exists and is a file, or False otherwise. '''
return os.path.exists(path) and os.path.isfile(path) | [
"def",
"is_valid_file",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")"
] | Returns True if provided file exists and is a file, or False otherwise. | [
"Returns",
"True",
"if",
"provided",
"file",
"exists",
"and",
"is",
"a",
"file",
"or",
"False",
"otherwise",
"."
] | train | https://github.com/marccarre/py_sak/blob/8ad4cafbd725d2700a31b50526804c0330d828dd/py_sak/validation.py#L42-L44 |
marccarre/py_sak | py_sak/validation.py | is_valid_dir | def is_valid_dir(path):
''' Returns True if provided directory exists and is a directory, or False otherwise. '''
return os.path.exists(path) and os.path.isdir(path) | python | def is_valid_dir(path):
''' Returns True if provided directory exists and is a directory, or False otherwise. '''
return os.path.exists(path) and os.path.isdir(path) | [
"def",
"is_valid_dir",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")"
] | Returns True if provided directory exists and is a directory, or False otherwise. | [
"Returns",
"True",
"if",
"provided",
"directory",
"exists",
"and",
"is",
"a",
"directory",
"or",
"False",
"otherwise",
"."
] | train | https://github.com/marccarre/py_sak/blob/8ad4cafbd725d2700a31b50526804c0330d828dd/py_sak/validation.py#L47-L49 |
marccarre/py_sak | py_sak/validation.py | is_readable | def is_readable(path):
'''
Returns True if provided file or directory exists and can be read with the current user.
Returns False otherwise.
'''
return os.access(os.path.abspath(path), os.R_OK) | python | def is_readable(path):
'''
Returns True if provided file or directory exists and can be read with the current user.
Returns False otherwise.
'''
return os.access(os.path.abspath(path), os.R_OK) | [
"def",
"is_readable",
"(",
"path",
")",
":",
"return",
"os",
".",
"access",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
",",
"os",
".",
"R_OK",
")"
] | Returns True if provided file or directory exists and can be read with the current user.
Returns False otherwise. | [
"Returns",
"True",
"if",
"provided",
"file",
"or",
"directory",
"exists",
"and",
"can",
"be",
"read",
"with",
"the",
"current",
"user",
".",
"Returns",
"False",
"otherwise",
"."
] | train | https://github.com/marccarre/py_sak/blob/8ad4cafbd725d2700a31b50526804c0330d828dd/py_sak/validation.py#L52-L57 |
jlesquembre/doc2git | doc2git/cmdline.py | run | def run(command, get_output=False, cwd=None):
"""By default, run all commands at GITPATH directory.
If command fails, stop program execution.
"""
if cwd is None:
cwd = GITPATH
cprint('===')
cprint('=== Command: ', command)
cprint('=== CWD: ', cwd)
cprint('===')
if get... | python | def run(command, get_output=False, cwd=None):
"""By default, run all commands at GITPATH directory.
If command fails, stop program execution.
"""
if cwd is None:
cwd = GITPATH
cprint('===')
cprint('=== Command: ', command)
cprint('=== CWD: ', cwd)
cprint('===')
if get... | [
"def",
"run",
"(",
"command",
",",
"get_output",
"=",
"False",
",",
"cwd",
"=",
"None",
")",
":",
"if",
"cwd",
"is",
"None",
":",
"cwd",
"=",
"GITPATH",
"cprint",
"(",
"'==='",
")",
"cprint",
"(",
"'=== Command: '",
",",
"command",
")",
"cprint",
"(... | By default, run all commands at GITPATH directory.
If command fails, stop program execution. | [
"By",
"default",
"run",
"all",
"commands",
"at",
"GITPATH",
"directory",
".",
"If",
"command",
"fails",
"stop",
"program",
"execution",
"."
] | train | https://github.com/jlesquembre/doc2git/blob/9aa5b0d220ae018573375f50bb035e700e2ca56e/doc2git/cmdline.py#L85-L105 |
zeromake/aiko | aiko/context.py | ContextCookie.get | def get(self, key: Any, default: Any = None) -> Any:
"""
读取使用 req like koa
"""
return self._req_cookies.get(key, default) | python | def get(self, key: Any, default: Any = None) -> Any:
"""
读取使用 req like koa
"""
return self._req_cookies.get(key, default) | [
"def",
"get",
"(",
"self",
",",
"key",
":",
"Any",
",",
"default",
":",
"Any",
"=",
"None",
")",
"->",
"Any",
":",
"return",
"self",
".",
"_req_cookies",
".",
"get",
"(",
"key",
",",
"default",
")"
] | 读取使用 req like koa | [
"读取使用",
"req",
"like",
"koa"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/context.py#L141-L145 |
zeromake/aiko | aiko/context.py | ContextCookie.set | def set(self, key: str, value: str, opt: dict = None) -> None:
"""
写入使用 res like koa
"""
self._res_cookies.set(key, value, opt) | python | def set(self, key: str, value: str, opt: dict = None) -> None:
"""
写入使用 res like koa
"""
self._res_cookies.set(key, value, opt) | [
"def",
"set",
"(",
"self",
",",
"key",
":",
"str",
",",
"value",
":",
"str",
",",
"opt",
":",
"dict",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"_res_cookies",
".",
"set",
"(",
"key",
",",
"value",
",",
"opt",
")"
] | 写入使用 res like koa | [
"写入使用",
"res",
"like",
"koa"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/context.py#L147-L151 |
CognitionGuidedSurgery/pyclictk | clictk/argparseutil.py | build_argument_parser | def build_argument_parser(executable):
"""creates an argument parser from the given `executable` model.
An argument '__xml__' for "--xml" is added independently.
:param executable: CLI Model
:type executable: clictk.model.Executable
:return:
"""
a = ArgumentParser()
a.add_argument("--... | python | def build_argument_parser(executable):
"""creates an argument parser from the given `executable` model.
An argument '__xml__' for "--xml" is added independently.
:param executable: CLI Model
:type executable: clictk.model.Executable
:return:
"""
a = ArgumentParser()
a.add_argument("--... | [
"def",
"build_argument_parser",
"(",
"executable",
")",
":",
"a",
"=",
"ArgumentParser",
"(",
")",
"a",
".",
"add_argument",
"(",
"\"--xml\"",
",",
"action",
"=",
"\"store_true\"",
",",
"dest",
"=",
"\"__xml__\"",
",",
"help",
"=",
"\"show cli xml\"",
")",
"... | creates an argument parser from the given `executable` model.
An argument '__xml__' for "--xml" is added independently.
:param executable: CLI Model
:type executable: clictk.model.Executable
:return: | [
"creates",
"an",
"argument",
"parser",
"from",
"the",
"given",
"executable",
"model",
"."
] | train | https://github.com/CognitionGuidedSurgery/pyclictk/blob/74915098a24a33adb46d8738f9c4746d91ecc1dc/clictk/argparseutil.py#L13-L38 |
CognitionGuidedSurgery/pyclictk | clictk/argparseutil.py | cmdline | def cmdline(executable):
"""Generates a valid command line call for the executable given by call arguments in `kwargs`
:param kwargs: values to call the executable
:return: the command line
:rtype: list
"""
args = [executable.executable]
indexed_args = []
for parameter in executable:
... | python | def cmdline(executable):
"""Generates a valid command line call for the executable given by call arguments in `kwargs`
:param kwargs: values to call the executable
:return: the command line
:rtype: list
"""
args = [executable.executable]
indexed_args = []
for parameter in executable:
... | [
"def",
"cmdline",
"(",
"executable",
")",
":",
"args",
"=",
"[",
"executable",
".",
"executable",
"]",
"indexed_args",
"=",
"[",
"]",
"for",
"parameter",
"in",
"executable",
":",
"optional",
"=",
"(",
"parameter",
".",
"type",
"==",
"'boolean'",
")",
"or... | Generates a valid command line call for the executable given by call arguments in `kwargs`
:param kwargs: values to call the executable
:return: the command line
:rtype: list | [
"Generates",
"a",
"valid",
"command",
"line",
"call",
"for",
"the",
"executable",
"given",
"by",
"call",
"arguments",
"in",
"kwargs",
":",
"param",
"kwargs",
":",
"values",
"to",
"call",
"the",
"executable",
":",
"return",
":",
"the",
"command",
"line",
":... | train | https://github.com/CognitionGuidedSurgery/pyclictk/blob/74915098a24a33adb46d8738f9c4746d91ecc1dc/clictk/argparseutil.py#L41-L77 |
vingd/vingd-api-python | vingd/util.py | absdatetime | def absdatetime(ts, default=None):
"""Accepts relative timestamp (`timedelta` or `timedelta`-supported ``dict``
fmt), absolute `datetime`, or failbacks to `default`. Returns `datetime` (or
`None` if `datetime` can not be derived from `ts`)."""
if ts is None:
ts = default
if isinstance(ts, di... | python | def absdatetime(ts, default=None):
"""Accepts relative timestamp (`timedelta` or `timedelta`-supported ``dict``
fmt), absolute `datetime`, or failbacks to `default`. Returns `datetime` (or
`None` if `datetime` can not be derived from `ts`)."""
if ts is None:
ts = default
if isinstance(ts, di... | [
"def",
"absdatetime",
"(",
"ts",
",",
"default",
"=",
"None",
")",
":",
"if",
"ts",
"is",
"None",
":",
"ts",
"=",
"default",
"if",
"isinstance",
"(",
"ts",
",",
"dict",
")",
":",
"ts",
"=",
"timedelta",
"(",
"*",
"*",
"ts",
")",
"if",
"isinstance... | Accepts relative timestamp (`timedelta` or `timedelta`-supported ``dict``
fmt), absolute `datetime`, or failbacks to `default`. Returns `datetime` (or
`None` if `datetime` can not be derived from `ts`). | [
"Accepts",
"relative",
"timestamp",
"(",
"timedelta",
"or",
"timedelta",
"-",
"supported",
"dict",
"fmt",
")",
"absolute",
"datetime",
"or",
"failbacks",
"to",
"default",
".",
"Returns",
"datetime",
"(",
"or",
"None",
"if",
"datetime",
"can",
"not",
"be",
"d... | train | https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/util.py#L49-L61 |
vingd/vingd-api-python | vingd/util.py | parse_duration | def parse_duration(string):
'''
Parses duration/period stamp expressed in a subset of ISO8601 duration
specification formats and returns a dictionary of time components (as
integers). Accepted formats are:
* ``PnYnMnDTnHnMnS``
Note: n is positive integer! Floats are NOT supported.... | python | def parse_duration(string):
'''
Parses duration/period stamp expressed in a subset of ISO8601 duration
specification formats and returns a dictionary of time components (as
integers). Accepted formats are:
* ``PnYnMnDTnHnMnS``
Note: n is positive integer! Floats are NOT supported.... | [
"def",
"parse_duration",
"(",
"string",
")",
":",
"string",
"=",
"string",
".",
"replace",
"(",
"' '",
",",
"''",
")",
".",
"upper",
"(",
")",
"# try `PnYnMnDTnHnMnS` form",
"match",
"=",
"re",
".",
"match",
"(",
"\"^P(?:(?:(?P<years>\\d+)Y)?(?:(?P<months>\\d+)M... | Parses duration/period stamp expressed in a subset of ISO8601 duration
specification formats and returns a dictionary of time components (as
integers). Accepted formats are:
* ``PnYnMnDTnHnMnS``
Note: n is positive integer! Floats are NOT supported. Any component (nX)
is optional, ... | [
"Parses",
"duration",
"/",
"period",
"stamp",
"expressed",
"in",
"a",
"subset",
"of",
"ISO8601",
"duration",
"specification",
"formats",
"and",
"returns",
"a",
"dictionary",
"of",
"time",
"components",
"(",
"as",
"integers",
")",
".",
"Accepted",
"formats",
"a... | train | https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/util.py#L64-L141 |
vingd/vingd-api-python | vingd/util.py | safeformat | def safeformat(format_string, *args):
"""String formatter with type validation. Python `format`-alike.
Examples::
- implicit indexing:
safeformat("Decimal {:int}, hexadecimal {1:hex}", 2, "abc")
--> "Decimal 2, hexadecimal abc"
- reusable argum... | python | def safeformat(format_string, *args):
"""String formatter with type validation. Python `format`-alike.
Examples::
- implicit indexing:
safeformat("Decimal {:int}, hexadecimal {1:hex}", 2, "abc")
--> "Decimal 2, hexadecimal abc"
- reusable argum... | [
"def",
"safeformat",
"(",
"format_string",
",",
"*",
"args",
")",
":",
"def",
"hex",
"(",
"x",
")",
":",
"\"\"\"Allow hexadecimal digits.\"\"\"",
"if",
"re",
".",
"match",
"(",
"'^[a-fA-F\\d]*$'",
",",
"str",
"(",
"x",
")",
")",
":",
"return",
"str",
"("... | String formatter with type validation. Python `format`-alike.
Examples::
- implicit indexing:
safeformat("Decimal {:int}, hexadecimal {1:hex}", 2, "abc")
--> "Decimal 2, hexadecimal abc"
- reusable arguments:
safeformat("{:hex}... | [
"String",
"formatter",
"with",
"type",
"validation",
".",
"Python",
"format",
"-",
"alike",
".",
"Examples",
"::",
"-",
"implicit",
"indexing",
":",
"safeformat",
"(",
"Decimal",
"{",
":",
"int",
"}",
"hexadecimal",
"{",
"1",
":",
"hex",
"}",
"2",
"abc",... | train | https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/util.py#L149-L235 |
the01/python-paps | paps/person.py | Person.from_dict | def from_dict(self, d):
"""
Set this person from dict
:param d: Dictionary representing a person ('sitting'[, 'id'])
:type d: dict
:rtype: Person
:raises KeyError: 'sitting' not set
"""
self.sitting = d['sitting']
self.id = d.get('id', None)
... | python | def from_dict(self, d):
"""
Set this person from dict
:param d: Dictionary representing a person ('sitting'[, 'id'])
:type d: dict
:rtype: Person
:raises KeyError: 'sitting' not set
"""
self.sitting = d['sitting']
self.id = d.get('id', None)
... | [
"def",
"from_dict",
"(",
"self",
",",
"d",
")",
":",
"self",
".",
"sitting",
"=",
"d",
"[",
"'sitting'",
"]",
"self",
".",
"id",
"=",
"d",
".",
"get",
"(",
"'id'",
",",
"None",
")",
"return",
"self"
] | Set this person from dict
:param d: Dictionary representing a person ('sitting'[, 'id'])
:type d: dict
:rtype: Person
:raises KeyError: 'sitting' not set | [
"Set",
"this",
"person",
"from",
"dict"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/person.py#L53-L64 |
the01/python-paps | paps/person.py | Person.from_tuple | def from_tuple(self, t):
"""
Set this person from tuple
:param t: Tuple representing a person (sitting[, id])
:type t: (bool) | (bool, None | str | unicode | int)
:rtype: Person
"""
if len(t) > 1:
self.id = t[0]
self.sitting = t[1]
... | python | def from_tuple(self, t):
"""
Set this person from tuple
:param t: Tuple representing a person (sitting[, id])
:type t: (bool) | (bool, None | str | unicode | int)
:rtype: Person
"""
if len(t) > 1:
self.id = t[0]
self.sitting = t[1]
... | [
"def",
"from_tuple",
"(",
"self",
",",
"t",
")",
":",
"if",
"len",
"(",
"t",
")",
">",
"1",
":",
"self",
".",
"id",
"=",
"t",
"[",
"0",
"]",
"self",
".",
"sitting",
"=",
"t",
"[",
"1",
"]",
"else",
":",
"self",
".",
"sitting",
"=",
"t",
"... | Set this person from tuple
:param t: Tuple representing a person (sitting[, id])
:type t: (bool) | (bool, None | str | unicode | int)
:rtype: Person | [
"Set",
"this",
"person",
"from",
"tuple"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/person.py#L75-L89 |
the01/python-paps | paps/person.py | Person.from_bits | def from_bits(self, bits):
"""
Set this person from bits (ignores the id)
:param bits: Bits representing a person
:type bits: bytearray
:rtype: Person
:raises ValueError: Bits has an unexpected length
"""
# TODO include id
if len(bits) != Person.B... | python | def from_bits(self, bits):
"""
Set this person from bits (ignores the id)
:param bits: Bits representing a person
:type bits: bytearray
:rtype: Person
:raises ValueError: Bits has an unexpected length
"""
# TODO include id
if len(bits) != Person.B... | [
"def",
"from_bits",
"(",
"self",
",",
"bits",
")",
":",
"# TODO include id",
"if",
"len",
"(",
"bits",
")",
"!=",
"Person",
".",
"BITS_PER_PERSON",
":",
"raise",
"ValueError",
"(",
"u\"Person requires exactly {} bits\"",
".",
"format",
"(",
"Person",
".",
"BIT... | Set this person from bits (ignores the id)
:param bits: Bits representing a person
:type bits: bytearray
:rtype: Person
:raises ValueError: Bits has an unexpected length | [
"Set",
"this",
"person",
"from",
"bits",
"(",
"ignores",
"the",
"id",
")"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/person.py#L103-L118 |
the01/python-paps | paps/person.py | Person.from_person | def from_person(person):
"""
Copy person
:param person: Person to copy into new instance
:type person: Person
:rtype: Person
"""
p = Person()
p.id = person.id
p.sitting = person.sitting
return p | python | def from_person(person):
"""
Copy person
:param person: Person to copy into new instance
:type person: Person
:rtype: Person
"""
p = Person()
p.id = person.id
p.sitting = person.sitting
return p | [
"def",
"from_person",
"(",
"person",
")",
":",
"p",
"=",
"Person",
"(",
")",
"p",
".",
"id",
"=",
"person",
".",
"id",
"p",
".",
"sitting",
"=",
"person",
".",
"sitting",
"return",
"p"
] | Copy person
:param person: Person to copy into new instance
:type person: Person
:rtype: Person | [
"Copy",
"person"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/person.py#L121-L132 |
hobson/pug-dj | pug/dj/explore.py | meta_bar_chart | def meta_bar_chart(series=None, N=20):
"Each column in the series is a dict of dicts"
if not series or isinstance(series, basestring):
series = json.load(load_app_meta)
if isinstance(series, Mapping) and isinstance(series.values()[0], Mapping):
rows_received = series['# Received'].items()
... | python | def meta_bar_chart(series=None, N=20):
"Each column in the series is a dict of dicts"
if not series or isinstance(series, basestring):
series = json.load(load_app_meta)
if isinstance(series, Mapping) and isinstance(series.values()[0], Mapping):
rows_received = series['# Received'].items()
... | [
"def",
"meta_bar_chart",
"(",
"series",
"=",
"None",
",",
"N",
"=",
"20",
")",
":",
"if",
"not",
"series",
"or",
"isinstance",
"(",
"series",
",",
"basestring",
")",
":",
"series",
"=",
"json",
".",
"load",
"(",
"load_app_meta",
")",
"if",
"isinstance"... | Each column in the series is a dict of dicts | [
"Each",
"column",
"in",
"the",
"series",
"is",
"a",
"dict",
"of",
"dicts"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L105-L138 |
hobson/pug-dj | pug/dj/explore.py | get_db_meta | def get_db_meta(app=DEFAULT_APP_NAME, db_alias=None, table=None, verbosity=0, column=None):
"""Return a dict of dicts containing metadata about the database tables associated with an app
TODO: allow multiple apps
>>> get_db_meta('crawler', db_alias='default', table='crawler_wikiitem') # doctest: +ELLIPSIS... | python | def get_db_meta(app=DEFAULT_APP_NAME, db_alias=None, table=None, verbosity=0, column=None):
"""Return a dict of dicts containing metadata about the database tables associated with an app
TODO: allow multiple apps
>>> get_db_meta('crawler', db_alias='default', table='crawler_wikiitem') # doctest: +ELLIPSIS... | [
"def",
"get_db_meta",
"(",
"app",
"=",
"DEFAULT_APP_NAME",
",",
"db_alias",
"=",
"None",
",",
"table",
"=",
"None",
",",
"verbosity",
"=",
"0",
",",
"column",
"=",
"None",
")",
":",
"if",
"verbosity",
">",
"0",
":",
"print",
"'Looking for app %r.'",
"%",... | Return a dict of dicts containing metadata about the database tables associated with an app
TODO: allow multiple apps
>>> get_db_meta('crawler', db_alias='default', table='crawler_wikiitem') # doctest: +ELLIPSIS
OrderedDict([('WikiItem', OrderedDict([('Meta', OrderedDict([('primary_key', None), ('count', ... | [
"Return",
"a",
"dict",
"of",
"dicts",
"containing",
"metadata",
"about",
"the",
"database",
"tables",
"associated",
"with",
"an",
"app"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L142-L217 |
hobson/pug-dj | pug/dj/explore.py | augment_model_meta | def augment_model_meta(model, db_alias, model_meta, column_name_filters=None, count=0, verbosity=0):
"""Fields are keyed by their db_column name rather than field name (like model_meta)"""
if settings.DEBUG and verbosity > 2:
print 'Augmenting model meta data for %r...' % model
column_name_filters ... | python | def augment_model_meta(model, db_alias, model_meta, column_name_filters=None, count=0, verbosity=0):
"""Fields are keyed by their db_column name rather than field name (like model_meta)"""
if settings.DEBUG and verbosity > 2:
print 'Augmenting model meta data for %r...' % model
column_name_filters ... | [
"def",
"augment_model_meta",
"(",
"model",
",",
"db_alias",
",",
"model_meta",
",",
"column_name_filters",
"=",
"None",
",",
"count",
"=",
"0",
",",
"verbosity",
"=",
"0",
")",
":",
"if",
"settings",
".",
"DEBUG",
"and",
"verbosity",
">",
"2",
":",
"prin... | Fields are keyed by their db_column name rather than field name (like model_meta) | [
"Fields",
"are",
"keyed",
"by",
"their",
"db_column",
"name",
"rather",
"than",
"field",
"name",
"(",
"like",
"model_meta",
")"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L268-L322 |
hobson/pug-dj | pug/dj/explore.py | augment_field_meta | def augment_field_meta(field, queryset, field_properties, verbosity=0, count=0):
"""Return a dict of statistical properties (metadata) for a database column (model field)
Strings are UTF-8 encoded (UTF-16 or invalid UTF-8 characters are ignored)
Resulting dictionary is json-serializable using the pug.nlp.d... | python | def augment_field_meta(field, queryset, field_properties, verbosity=0, count=0):
"""Return a dict of statistical properties (metadata) for a database column (model field)
Strings are UTF-8 encoded (UTF-16 or invalid UTF-8 characters are ignored)
Resulting dictionary is json-serializable using the pug.nlp.d... | [
"def",
"augment_field_meta",
"(",
"field",
",",
"queryset",
",",
"field_properties",
",",
"verbosity",
"=",
"0",
",",
"count",
"=",
"0",
")",
":",
"if",
"settings",
".",
"DEBUG",
"and",
"verbosity",
">",
"3",
":",
"print",
"'Augmenting field meta data for %r..... | Return a dict of statistical properties (metadata) for a database column (model field)
Strings are UTF-8 encoded (UTF-16 or invalid UTF-8 characters are ignored)
Resulting dictionary is json-serializable using the pug.nlp.db.RobustEncoder class.
{
'num_distinct': # count of distinct (different) ... | [
"Return",
"a",
"dict",
"of",
"statistical",
"properties",
"(",
"metadata",
")",
"for",
"a",
"database",
"column",
"(",
"model",
"field",
")"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L325-L418 |
hobson/pug-dj | pug/dj/explore.py | index_with_dupes | def index_with_dupes(values_list, unique_together=2, model_number_i=0, serial_number_i=1, verbosity=1):
'''Create dict from values_list with first N values as a compound key.
Default N (number of columns assumbed to be "unique_together") is 2.
>>> index_with_dupes([(1,2,3), (5,6,7), (5,6,8), (2,1,3)]) == (... | python | def index_with_dupes(values_list, unique_together=2, model_number_i=0, serial_number_i=1, verbosity=1):
'''Create dict from values_list with first N values as a compound key.
Default N (number of columns assumbed to be "unique_together") is 2.
>>> index_with_dupes([(1,2,3), (5,6,7), (5,6,8), (2,1,3)]) == (... | [
"def",
"index_with_dupes",
"(",
"values_list",
",",
"unique_together",
"=",
"2",
",",
"model_number_i",
"=",
"0",
",",
"serial_number_i",
"=",
"1",
",",
"verbosity",
"=",
"1",
")",
":",
"try",
":",
"N",
"=",
"values_list",
".",
"count",
"(",
")",
"except... | Create dict from values_list with first N values as a compound key.
Default N (number of columns assumbed to be "unique_together") is 2.
>>> index_with_dupes([(1,2,3), (5,6,7), (5,6,8), (2,1,3)]) == ({(1, 2): (1, 2, 3), (2, 1): (2, 1, 3), (5, 6): (5, 6, 7)}, {(5, 6): [(5, 6, 7), (5, 6, 8)]})
True | [
"Create",
"dict",
"from",
"values_list",
"with",
"first",
"N",
"values",
"as",
"a",
"compound",
"key",
"."
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L421-L461 |
hobson/pug-dj | pug/dj/explore.py | index_model_field | def index_model_field(model, field, value_field='pk', key_formatter=str.strip, value_formatter=str.strip, batch_len=10000, limit=10000000, verbosity=1):
'''Create dict {obj.<field>: obj.pk} for all field_values in a model or queryset.
'''
try:
qs = model.objects
except:
qs = model
N... | python | def index_model_field(model, field, value_field='pk', key_formatter=str.strip, value_formatter=str.strip, batch_len=10000, limit=10000000, verbosity=1):
'''Create dict {obj.<field>: obj.pk} for all field_values in a model or queryset.
'''
try:
qs = model.objects
except:
qs = model
N... | [
"def",
"index_model_field",
"(",
"model",
",",
"field",
",",
"value_field",
"=",
"'pk'",
",",
"key_formatter",
"=",
"str",
".",
"strip",
",",
"value_formatter",
"=",
"str",
".",
"strip",
",",
"batch_len",
"=",
"10000",
",",
"limit",
"=",
"10000000",
",",
... | Create dict {obj.<field>: obj.pk} for all field_values in a model or queryset. | [
"Create",
"dict",
"{",
"obj",
".",
"<field",
">",
":",
"obj",
".",
"pk",
"}",
"for",
"all",
"field_values",
"in",
"a",
"model",
"or",
"queryset",
"."
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L464-L513 |
hobson/pug-dj | pug/dj/explore.py | index_model_field_batches | def index_model_field_batches(model_or_queryset, key_fields=['model_number', 'serial_number'], value_fields=['pk'],
key_formatter=lambda x: str.lstrip(str.strip(str(x or '')), '0'),
value_formatter=lambda x: str.strip(str(x)), batch_len=10000,
limit=100000000, verbosity=1):
'''Like index_model_field e... | python | def index_model_field_batches(model_or_queryset, key_fields=['model_number', 'serial_number'], value_fields=['pk'],
key_formatter=lambda x: str.lstrip(str.strip(str(x or '')), '0'),
value_formatter=lambda x: str.strip(str(x)), batch_len=10000,
limit=100000000, verbosity=1):
'''Like index_model_field e... | [
"def",
"index_model_field_batches",
"(",
"model_or_queryset",
",",
"key_fields",
"=",
"[",
"'model_number'",
",",
"'serial_number'",
"]",
",",
"value_fields",
"=",
"[",
"'pk'",
"]",
",",
"key_formatter",
"=",
"lambda",
"x",
":",
"str",
".",
"lstrip",
"(",
"str... | Like index_model_field except uses 50x less memory and 10x more processing cycles
Returns 2 dicts where both the keys and values are tuples:
target_index = {(<key_fields[0]>, <key_fields[1]>, ...): (<value_fields[0]>,)} for all distinct model-serial pairs in the Sales queryset
target_dupes = {(<key_fields... | [
"Like",
"index_model_field",
"except",
"uses",
"50x",
"less",
"memory",
"and",
"10x",
"more",
"processing",
"cycles"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L516-L577 |
hobson/pug-dj | pug/dj/explore.py | find_index | def find_index(model_meta, weights=None, verbosity=0):
"""Return a tuple of index metadata for the model metadata dict provided
return value format is:
(
field_name,
{
'primary_key': boolean representing whether it's the primary key,
'unique': ... | python | def find_index(model_meta, weights=None, verbosity=0):
"""Return a tuple of index metadata for the model metadata dict provided
return value format is:
(
field_name,
{
'primary_key': boolean representing whether it's the primary key,
'unique': ... | [
"def",
"find_index",
"(",
"model_meta",
",",
"weights",
"=",
"None",
",",
"verbosity",
"=",
"0",
")",
":",
"weights",
"=",
"weights",
"or",
"find_index",
".",
"default_weights",
"N",
"=",
"model_meta",
"[",
"'Meta'",
"]",
".",
"get",
"(",
"'count'",
",",... | Return a tuple of index metadata for the model metadata dict provided
return value format is:
(
field_name,
{
'primary_key': boolean representing whether it's the primary key,
'unique': boolean representing whether it's a unique index
... | [
"Return",
"a",
"tuple",
"of",
"index",
"metadata",
"for",
"the",
"model",
"metadata",
"dict",
"provided"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L580-L641 |
hobson/pug-dj | pug/dj/explore.py | meta_to_indexes | def meta_to_indexes(meta, table_name=None, model_name=None):
"""Find all the indexes (primary keys) based on the meta data
"""
indexes, pk_field = {}, None
indexes = []
for meta_model_name, model_meta in meta.iteritems():
if (table_name or model_name) and not (table_name == model_meta['Met... | python | def meta_to_indexes(meta, table_name=None, model_name=None):
"""Find all the indexes (primary keys) based on the meta data
"""
indexes, pk_field = {}, None
indexes = []
for meta_model_name, model_meta in meta.iteritems():
if (table_name or model_name) and not (table_name == model_meta['Met... | [
"def",
"meta_to_indexes",
"(",
"meta",
",",
"table_name",
"=",
"None",
",",
"model_name",
"=",
"None",
")",
":",
"indexes",
",",
"pk_field",
"=",
"{",
"}",
",",
"None",
"indexes",
"=",
"[",
"]",
"for",
"meta_model_name",
",",
"model_meta",
"in",
"meta",
... | Find all the indexes (primary keys) based on the meta data | [
"Find",
"all",
"the",
"indexes",
"(",
"primary",
"keys",
")",
"based",
"on",
"the",
"meta",
"data"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L647-L658 |
hobson/pug-dj | pug/dj/explore.py | try_convert | def try_convert(value, datetime_to_ms=False, precise=False):
"""Convert a str into more useful python type (datetime, float, int, bool), if possible
Some precision may be lost (e.g. Decimal converted to a float)
>>> try_convert('false')
False
>>> try_convert('123456789.123456')
123456789.12345... | python | def try_convert(value, datetime_to_ms=False, precise=False):
"""Convert a str into more useful python type (datetime, float, int, bool), if possible
Some precision may be lost (e.g. Decimal converted to a float)
>>> try_convert('false')
False
>>> try_convert('123456789.123456')
123456789.12345... | [
"def",
"try_convert",
"(",
"value",
",",
"datetime_to_ms",
"=",
"False",
",",
"precise",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"return",
"value",
"if",
"value",
"in",
"db",
".",
"YES_VALUES",
"or",
... | Convert a str into more useful python type (datetime, float, int, bool), if possible
Some precision may be lost (e.g. Decimal converted to a float)
>>> try_convert('false')
False
>>> try_convert('123456789.123456')
123456789.123456
>>> try_convert('1234')
1234
>>> try_convert(1234)
... | [
"Convert",
"a",
"str",
"into",
"more",
"useful",
"python",
"type",
"(",
"datetime",
"float",
"int",
"bool",
")",
"if",
"possible"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L673-L739 |
hobson/pug-dj | pug/dj/explore.py | make_serializable | def make_serializable(data, mutable=True, key_stringifier=lambda x:x, simplify_midnight_datetime=True):
r"""Make sure the data structure is json serializable (json.dumps-able), all they way down to scalars in nested structures.
If mutable=False then return tuples for all iterables, except basestrings (strs),
... | python | def make_serializable(data, mutable=True, key_stringifier=lambda x:x, simplify_midnight_datetime=True):
r"""Make sure the data structure is json serializable (json.dumps-able), all they way down to scalars in nested structures.
If mutable=False then return tuples for all iterables, except basestrings (strs),
... | [
"def",
"make_serializable",
"(",
"data",
",",
"mutable",
"=",
"True",
",",
"key_stringifier",
"=",
"lambda",
"x",
":",
"x",
",",
"simplify_midnight_datetime",
"=",
"True",
")",
":",
"# print 'serializabling: ' + repr(data)",
"# print 'type: ' + repr(type(data))",
"if",
... | r"""Make sure the data structure is json serializable (json.dumps-able), all they way down to scalars in nested structures.
If mutable=False then return tuples for all iterables, except basestrings (strs),
so that they can be used as keys in a Mapping (dict).
>>> from collections import OrderedDict
... | [
"r",
"Make",
"sure",
"the",
"data",
"structure",
"is",
"json",
"serializable",
"(",
"json",
".",
"dumps",
"-",
"able",
")",
"all",
"they",
"way",
"down",
"to",
"scalars",
"in",
"nested",
"structures",
"."
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L742-L815 |
hobson/pug-dj | pug/dj/explore.py | convert_loaded_json | def convert_loaded_json(js):
"""Convert strings loaded as part of a json file/string to native python types
convert_loaded_json({'x': '123'})
{'x': 123}
convert_loaded_json([{'x': '123.'}, {'x': 'Jan 28, 2014'}])
[{'x': 123}, datetime.datetime(2014, 1, 18)]
"""
if not isinstance(js, (Mappin... | python | def convert_loaded_json(js):
"""Convert strings loaded as part of a json file/string to native python types
convert_loaded_json({'x': '123'})
{'x': 123}
convert_loaded_json([{'x': '123.'}, {'x': 'Jan 28, 2014'}])
[{'x': 123}, datetime.datetime(2014, 1, 18)]
"""
if not isinstance(js, (Mappin... | [
"def",
"convert_loaded_json",
"(",
"js",
")",
":",
"if",
"not",
"isinstance",
"(",
"js",
",",
"(",
"Mapping",
",",
"tuple",
",",
"list",
")",
")",
":",
"return",
"try_convert",
"(",
"js",
")",
"try",
":",
"return",
"type",
"(",
"js",
")",
"(",
"con... | Convert strings loaded as part of a json file/string to native python types
convert_loaded_json({'x': '123'})
{'x': 123}
convert_loaded_json([{'x': '123.'}, {'x': 'Jan 28, 2014'}])
[{'x': 123}, datetime.datetime(2014, 1, 18)] | [
"Convert",
"strings",
"loaded",
"as",
"part",
"of",
"a",
"json",
"file",
"/",
"string",
"to",
"native",
"python",
"types"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L818-L834 |
hobson/pug-dj | pug/dj/explore.py | models_with_unique_column | def models_with_unique_column(meta, exclude_single_pk=True, exclude_multi_pk=True):
"""Return a list of model names for models that have at least 1 field that has all distinct values (could be used as primary_key)"""
models_with_potential_pk = {}
fields_distinct = {}
for model_name, model_fields in meta... | python | def models_with_unique_column(meta, exclude_single_pk=True, exclude_multi_pk=True):
"""Return a list of model names for models that have at least 1 field that has all distinct values (could be used as primary_key)"""
models_with_potential_pk = {}
fields_distinct = {}
for model_name, model_fields in meta... | [
"def",
"models_with_unique_column",
"(",
"meta",
",",
"exclude_single_pk",
"=",
"True",
",",
"exclude_multi_pk",
"=",
"True",
")",
":",
"models_with_potential_pk",
"=",
"{",
"}",
"fields_distinct",
"=",
"{",
"}",
"for",
"model_name",
",",
"model_fields",
"in",
"... | Return a list of model names for models that have at least 1 field that has all distinct values (could be used as primary_key) | [
"Return",
"a",
"list",
"of",
"model",
"names",
"for",
"models",
"that",
"have",
"at",
"least",
"1",
"field",
"that",
"has",
"all",
"distinct",
"values",
"(",
"could",
"be",
"used",
"as",
"primary_key",
")"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L837-L853 |
hobson/pug-dj | pug/dj/explore.py | count_unique | def count_unique(table, field=-1):
"""Use the Django ORM or collections.Counter to count unique values of a field in a table
`table` is one of:
1. An iterable of Django model instances for a database table (e.g. a Django queryset)
2. An iterable of dicts or lists with elements accessed by row[field] wh... | python | def count_unique(table, field=-1):
"""Use the Django ORM or collections.Counter to count unique values of a field in a table
`table` is one of:
1. An iterable of Django model instances for a database table (e.g. a Django queryset)
2. An iterable of dicts or lists with elements accessed by row[field] wh... | [
"def",
"count_unique",
"(",
"table",
",",
"field",
"=",
"-",
"1",
")",
":",
"from",
"collections",
"import",
"Counter",
"# try/except only happens once, and fastest route (straight to db) tried first",
"try",
":",
"ans",
"=",
"{",
"}",
"for",
"row",
"in",
"table",
... | Use the Django ORM or collections.Counter to count unique values of a field in a table
`table` is one of:
1. An iterable of Django model instances for a database table (e.g. a Django queryset)
2. An iterable of dicts or lists with elements accessed by row[field] where field can be an integer or string
... | [
"Use",
"the",
"Django",
"ORM",
"or",
"collections",
".",
"Counter",
"to",
"count",
"unique",
"values",
"of",
"a",
"field",
"in",
"a",
"table"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L913-L941 |
webadmin87/midnight | midnight_main/services.py | get_page_tpl_ctx | def get_page_tpl_ctx(page, request):
"""
Возвращает контекст для рендеринга представления текстовой страницы
:param page: модель страницы
:param request: запрос
:return:
"""
text = Template(page.text).render(Context())
meta = MetaSeo(page)
comments = get_object_comments(PageComment, ... | python | def get_page_tpl_ctx(page, request):
"""
Возвращает контекст для рендеринга представления текстовой страницы
:param page: модель страницы
:param request: запрос
:return:
"""
text = Template(page.text).render(Context())
meta = MetaSeo(page)
comments = get_object_comments(PageComment, ... | [
"def",
"get_page_tpl_ctx",
"(",
"page",
",",
"request",
")",
":",
"text",
"=",
"Template",
"(",
"page",
".",
"text",
")",
".",
"render",
"(",
"Context",
"(",
")",
")",
"meta",
"=",
"MetaSeo",
"(",
"page",
")",
"comments",
"=",
"get_object_comments",
"(... | Возвращает контекст для рендеринга представления текстовой страницы
:param page: модель страницы
:param request: запрос
:return: | [
"Возвращает",
"контекст",
"для",
"рендеринга",
"представления",
"текстовой",
"страницы",
":",
"param",
"page",
":",
"модель",
"страницы",
":",
"param",
"request",
":",
"запрос",
":",
"return",
":"
] | train | https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_main/services.py#L9-L24 |
webadmin87/midnight | midnight_main/services.py | get_comment_init | def get_comment_init(request, obj):
"""
Возвращает словарь для инициализации начальных значений модели комментария
:param request: запрос
:param obj: объект к которому добавляется комментарий
:return:
"""
if request.user.is_authenticated():
init = {'obj': obj, 'username': request.use... | python | def get_comment_init(request, obj):
"""
Возвращает словарь для инициализации начальных значений модели комментария
:param request: запрос
:param obj: объект к которому добавляется комментарий
:return:
"""
if request.user.is_authenticated():
init = {'obj': obj, 'username': request.use... | [
"def",
"get_comment_init",
"(",
"request",
",",
"obj",
")",
":",
"if",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"init",
"=",
"{",
"'obj'",
":",
"obj",
",",
"'username'",
":",
"request",
".",
"user",
".",
"username",
",",
"'email'... | Возвращает словарь для инициализации начальных значений модели комментария
:param request: запрос
:param obj: объект к которому добавляется комментарий
:return: | [
"Возвращает",
"словарь",
"для",
"инициализации",
"начальных",
"значений",
"модели",
"комментария",
":",
"param",
"request",
":",
"запрос",
":",
"param",
"obj",
":",
"объект",
"к",
"которому",
"добавляется",
"комментарий",
":",
"return",
":"
] | train | https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_main/services.py#L27-L38 |
webadmin87/midnight | midnight_main/services.py | post_comment | def post_comment(form, user):
"""
Постинг комментария
:param form: форма комментария
:param user: пользователь
:return:
"""
if form.is_valid():
model = form.save(commit=False)
if user.is_authenticated():
model.author = user
model.save()
return True... | python | def post_comment(form, user):
"""
Постинг комментария
:param form: форма комментария
:param user: пользователь
:return:
"""
if form.is_valid():
model = form.save(commit=False)
if user.is_authenticated():
model.author = user
model.save()
return True... | [
"def",
"post_comment",
"(",
"form",
",",
"user",
")",
":",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"model",
"=",
"form",
".",
"save",
"(",
"commit",
"=",
"False",
")",
"if",
"user",
".",
"is_authenticated",
"(",
")",
":",
"model",
".",
"autho... | Постинг комментария
:param form: форма комментария
:param user: пользователь
:return: | [
"Постинг",
"комментария",
":",
"param",
"form",
":",
"форма",
"комментария",
":",
"param",
"user",
":",
"пользователь",
":",
"return",
":"
] | train | https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_main/services.py#L51-L65 |
webadmin87/midnight | midnight_main/services.py | save_formset_with_author | def save_formset_with_author(formset, user):
"""
Проставляет моделям из набора форм автора
:param formset: набор форм
:param user: автор
:return:
"""
instances = formset.save(commit=False)
for obj in formset.deleted_objects:
obj.delete()
for instance in instances:
if ... | python | def save_formset_with_author(formset, user):
"""
Проставляет моделям из набора форм автора
:param formset: набор форм
:param user: автор
:return:
"""
instances = formset.save(commit=False)
for obj in formset.deleted_objects:
obj.delete()
for instance in instances:
if ... | [
"def",
"save_formset_with_author",
"(",
"formset",
",",
"user",
")",
":",
"instances",
"=",
"formset",
".",
"save",
"(",
"commit",
"=",
"False",
")",
"for",
"obj",
"in",
"formset",
".",
"deleted_objects",
":",
"obj",
".",
"delete",
"(",
")",
"for",
"inst... | Проставляет моделям из набора форм автора
:param formset: набор форм
:param user: автор
:return: | [
"Проставляет",
"моделям",
"из",
"набора",
"форм",
"автора",
":",
"param",
"formset",
":",
"набор",
"форм",
":",
"param",
"user",
":",
"автор",
":",
"return",
":"
] | train | https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_main/services.py#L68-L82 |
webadmin87/midnight | midnight_main/services.py | get_by_page | def get_by_page(query, page, page_size):
"""
Осуществляет пагинацию
:param query: запрос
:param page: номер страницы
:param page_size: количество объектов на странице
:return:
"""
pager = Paginator(query, page_size)
try:
models = pager.page(page)
except PageNotAnInteger:... | python | def get_by_page(query, page, page_size):
"""
Осуществляет пагинацию
:param query: запрос
:param page: номер страницы
:param page_size: количество объектов на странице
:return:
"""
pager = Paginator(query, page_size)
try:
models = pager.page(page)
except PageNotAnInteger:... | [
"def",
"get_by_page",
"(",
"query",
",",
"page",
",",
"page_size",
")",
":",
"pager",
"=",
"Paginator",
"(",
"query",
",",
"page_size",
")",
"try",
":",
"models",
"=",
"pager",
".",
"page",
"(",
"page",
")",
"except",
"PageNotAnInteger",
":",
"# If page ... | Осуществляет пагинацию
:param query: запрос
:param page: номер страницы
:param page_size: количество объектов на странице
:return: | [
"Осуществляет",
"пагинацию",
":",
"param",
"query",
":",
"запрос",
":",
"param",
"page",
":",
"номер",
"страницы",
":",
"param",
"page_size",
":",
"количество",
"объектов",
"на",
"странице",
":",
"return",
":"
] | train | https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_main/services.py#L85-L104 |
webadmin87/midnight | midnight_main/services.py | mark_current_menus | def mark_current_menus(menus, path_info):
"""
Отмечает активные модели меню (У которых ссылка соответствует текущему path info)
:param menus: список моделей меню
:param path_info: path info
:return:
"""
for menu in menus:
if menu.get_absolute_url() == "/":
menu.is_current... | python | def mark_current_menus(menus, path_info):
"""
Отмечает активные модели меню (У которых ссылка соответствует текущему path info)
:param menus: список моделей меню
:param path_info: path info
:return:
"""
for menu in menus:
if menu.get_absolute_url() == "/":
menu.is_current... | [
"def",
"mark_current_menus",
"(",
"menus",
",",
"path_info",
")",
":",
"for",
"menu",
"in",
"menus",
":",
"if",
"menu",
".",
"get_absolute_url",
"(",
")",
"==",
"\"/\"",
":",
"menu",
".",
"is_current",
"=",
"menu",
".",
"get_absolute_url",
"(",
")",
"=="... | Отмечает активные модели меню (У которых ссылка соответствует текущему path info)
:param menus: список моделей меню
:param path_info: path info
:return: | [
"Отмечает",
"активные",
"модели",
"меню",
"(",
"У",
"которых",
"ссылка",
"соответствует",
"текущему",
"path",
"info",
")",
":",
"param",
"menus",
":",
"список",
"моделей",
"меню",
":",
"param",
"path_info",
":",
"path",
"info",
":",
"return",
":"
] | train | https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_main/services.py#L107-L118 |
shi-cong/PYSTUDY | PYSTUDY/encryptlib.py | caesar_cipher | def caesar_cipher(message, key):
"""
凯特加密法
:param message: 待加密数据
:param key: 加密向量
:return: 被加密的字符串
"""
LEFTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
translated = ''
message = message.upper()
for symbol in message:
if symbol in LEFTERS:
num = LEFTERS.find(symbol)
... | python | def caesar_cipher(message, key):
"""
凯特加密法
:param message: 待加密数据
:param key: 加密向量
:return: 被加密的字符串
"""
LEFTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
translated = ''
message = message.upper()
for symbol in message:
if symbol in LEFTERS:
num = LEFTERS.find(symbol)
... | [
"def",
"caesar_cipher",
"(",
"message",
",",
"key",
")",
":",
"LEFTERS",
"=",
"'ABCDEFGHIJKLMNOPQRSTUVWXYZ'",
"translated",
"=",
"''",
"message",
"=",
"message",
".",
"upper",
"(",
")",
"for",
"symbol",
"in",
"message",
":",
"if",
"symbol",
"in",
"LEFTERS",
... | 凯特加密法
:param message: 待加密数据
:param key: 加密向量
:return: 被加密的字符串 | [
"凯特加密法",
":",
"param",
"message",
":",
"待加密数据",
":",
"param",
"key",
":",
"加密向量",
":",
"return",
":",
"被加密的字符串"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/encryptlib.py#L17-L41 |
shi-cong/PYSTUDY | PYSTUDY/encryptlib.py | reverse_cipher | def reverse_cipher(message):
"""
反转加密法
:param message: 待加密字符串
:return: 被加密字符串
"""
translated = ''
i = len(message) - 1
while i >= 0:
translated = translated + message[i]
i = i - 1
return translated | python | def reverse_cipher(message):
"""
反转加密法
:param message: 待加密字符串
:return: 被加密字符串
"""
translated = ''
i = len(message) - 1
while i >= 0:
translated = translated + message[i]
i = i - 1
return translated | [
"def",
"reverse_cipher",
"(",
"message",
")",
":",
"translated",
"=",
"''",
"i",
"=",
"len",
"(",
"message",
")",
"-",
"1",
"while",
"i",
">=",
"0",
":",
"translated",
"=",
"translated",
"+",
"message",
"[",
"i",
"]",
"i",
"=",
"i",
"-",
"1",
"re... | 反转加密法
:param message: 待加密字符串
:return: 被加密字符串 | [
"反转加密法",
":",
"param",
"message",
":",
"待加密字符串",
":",
"return",
":",
"被加密字符串"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/encryptlib.py#L44-L57 |
shi-cong/PYSTUDY | PYSTUDY/encryptlib.py | transposition_cipher | def transposition_cipher(key, message):
"""
换位加密法
:param key: 数字Key
:param message: 待加密字符串
:return: 被加密数据
"""
ciphertext = [''] * key
ml = len(message)
for col in range(key):
pointer = col
while pointer < ml:
ciphertext[col] += message[pointer]
... | python | def transposition_cipher(key, message):
"""
换位加密法
:param key: 数字Key
:param message: 待加密字符串
:return: 被加密数据
"""
ciphertext = [''] * key
ml = len(message)
for col in range(key):
pointer = col
while pointer < ml:
ciphertext[col] += message[pointer]
... | [
"def",
"transposition_cipher",
"(",
"key",
",",
"message",
")",
":",
"ciphertext",
"=",
"[",
"''",
"]",
"*",
"key",
"ml",
"=",
"len",
"(",
"message",
")",
"for",
"col",
"in",
"range",
"(",
"key",
")",
":",
"pointer",
"=",
"col",
"while",
"pointer",
... | 换位加密法
:param key: 数字Key
:param message: 待加密字符串
:return: 被加密数据 | [
"换位加密法",
":",
"param",
"key",
":",
"数字Key",
":",
"param",
"message",
":",
"待加密字符串",
":",
"return",
":",
"被加密数据"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/encryptlib.py#L60-L75 |
ttm/participationLegacy | participation/triplification/participaTriplification.py | ParticipaTriplification.readTables | def readTables(self):
"""Retrieves data (D) and names (N) from relational tables.
"""
class D: pass
cur=self.cur
cur.execute('SELECT * FROM users')
D.users = cur.fetchall()
cur.execute('SELECT * FROM profiles')
D.profiles = cur.fetchall()
cur.execu... | python | def readTables(self):
"""Retrieves data (D) and names (N) from relational tables.
"""
class D: pass
cur=self.cur
cur.execute('SELECT * FROM users')
D.users = cur.fetchall()
cur.execute('SELECT * FROM profiles')
D.profiles = cur.fetchall()
cur.execu... | [
"def",
"readTables",
"(",
"self",
")",
":",
"class",
"D",
":",
"pass",
"cur",
"=",
"self",
".",
"cur",
"cur",
".",
"execute",
"(",
"'SELECT * FROM users'",
")",
"D",
".",
"users",
"=",
"cur",
".",
"fetchall",
"(",
")",
"cur",
".",
"execute",
"(",
"... | Retrieves data (D) and names (N) from relational tables. | [
"Retrieves",
"data",
"(",
"D",
")",
"and",
"names",
"(",
"N",
")",
"from",
"relational",
"tables",
"."
] | train | https://github.com/ttm/participationLegacy/blob/d78975038a64ea018120889d019a559409dae631/participation/triplification/participaTriplification.py#L36-L84 |
ttm/participationLegacy | participation/triplification/participaTriplification.py | ParticipaTriplification.startGraph | def startGraph(self):
"""Starts RDF graph and bing namespaces"""
g = r.Graph()
g.namespace_manager.bind("rdf", r.namespace.RDF)
g.namespace_manager.bind("foaf", r.namespace.FOAF)
g.namespace_manager.bind("xsd", r.namespace.XSD)
g.namespace_manager.bind("opa", ... | python | def startGraph(self):
"""Starts RDF graph and bing namespaces"""
g = r.Graph()
g.namespace_manager.bind("rdf", r.namespace.RDF)
g.namespace_manager.bind("foaf", r.namespace.FOAF)
g.namespace_manager.bind("xsd", r.namespace.XSD)
g.namespace_manager.bind("opa", ... | [
"def",
"startGraph",
"(",
"self",
")",
":",
"g",
"=",
"r",
".",
"Graph",
"(",
")",
"g",
".",
"namespace_manager",
".",
"bind",
"(",
"\"rdf\"",
",",
"r",
".",
"namespace",
".",
"RDF",
")",
"g",
".",
"namespace_manager",
".",
"bind",
"(",
"\"foaf\"",
... | Starts RDF graph and bing namespaces | [
"Starts",
"RDF",
"graph",
"and",
"bing",
"namespaces"
] | train | https://github.com/ttm/participationLegacy/blob/d78975038a64ea018120889d019a559409dae631/participation/triplification/participaTriplification.py#L102-L117 |
ttm/participationLegacy | participation/triplification/participaTriplification.py | ParticipaTriplification.triplifyPortalInfo | def triplifyPortalInfo(self):
"""Make triples with information about the portal.
"""
uri=self.P.opa.ParticipationPortal+self.separator+"participabr"
self.X.G(uri,self.P.rdf.type,self.P.opa.ParticipationPortal)
self.X.G(uri,self.P.opa.description,self.X.L(DATA.portal_description,s... | python | def triplifyPortalInfo(self):
"""Make triples with information about the portal.
"""
uri=self.P.opa.ParticipationPortal+self.separator+"participabr"
self.X.G(uri,self.P.rdf.type,self.P.opa.ParticipationPortal)
self.X.G(uri,self.P.opa.description,self.X.L(DATA.portal_description,s... | [
"def",
"triplifyPortalInfo",
"(",
"self",
")",
":",
"uri",
"=",
"self",
".",
"P",
".",
"opa",
".",
"ParticipationPortal",
"+",
"self",
".",
"separator",
"+",
"\"participabr\"",
"self",
".",
"X",
".",
"G",
"(",
"uri",
",",
"self",
".",
"P",
".",
"rdf"... | Make triples with information about the portal. | [
"Make",
"triples",
"with",
"information",
"about",
"the",
"portal",
"."
] | train | https://github.com/ttm/participationLegacy/blob/d78975038a64ea018120889d019a559409dae631/participation/triplification/participaTriplification.py#L150-L156 |
ttm/participationLegacy | participation/triplification/participaTriplification.py | ParticipaTriplification.triplifyOverallStructures | def triplifyOverallStructures(self):
"""Insert into RDF graph the textual and network structures.
Ideally, one should be able to make bag of words related to
each item (communities, users, posts, comments, tags, etc).
Interaction and friendship networks should be made.
Human net... | python | def triplifyOverallStructures(self):
"""Insert into RDF graph the textual and network structures.
Ideally, one should be able to make bag of words related to
each item (communities, users, posts, comments, tags, etc).
Interaction and friendship networks should be made.
Human net... | [
"def",
"triplifyOverallStructures",
"(",
"self",
")",
":",
"if",
"self",
".",
"compute_networks",
":",
"self",
".",
"computeNetworks",
"(",
")",
"if",
"self",
".",
"compute_bows",
":",
"self",
".",
"computeBows",
"(",
")"
] | Insert into RDF graph the textual and network structures.
Ideally, one should be able to make bag of words related to
each item (communities, users, posts, comments, tags, etc).
Interaction and friendship networks should be made.
Human networks mediated by co-ocurrance (time os posts,
... | [
"Insert",
"into",
"RDF",
"graph",
"the",
"textual",
"and",
"network",
"structures",
"."
] | train | https://github.com/ttm/participationLegacy/blob/d78975038a64ea018120889d019a559409dae631/participation/triplification/participaTriplification.py#L157-L170 |
rehandalal/buchner | buchner/project-template/manage.py | db_create | def db_create():
"""Create the database"""
try:
migrate_api.version_control(url=db_url, repository=db_repo)
db_upgrade()
except DatabaseAlreadyControlledError:
print 'ERROR: Database is already version controlled.' | python | def db_create():
"""Create the database"""
try:
migrate_api.version_control(url=db_url, repository=db_repo)
db_upgrade()
except DatabaseAlreadyControlledError:
print 'ERROR: Database is already version controlled.' | [
"def",
"db_create",
"(",
")",
":",
"try",
":",
"migrate_api",
".",
"version_control",
"(",
"url",
"=",
"db_url",
",",
"repository",
"=",
"db_repo",
")",
"db_upgrade",
"(",
")",
"except",
"DatabaseAlreadyControlledError",
":",
"print",
"'ERROR: Database is already ... | Create the database | [
"Create",
"the",
"database"
] | train | https://github.com/rehandalal/buchner/blob/dc22a61c493b9d4a74d76e8b42a319aa13e385f3/buchner/project-template/manage.py#L30-L36 |
rehandalal/buchner | buchner/project-template/manage.py | db_downgrade | def db_downgrade(version):
"""Downgrade the database"""
v1 = get_db_version()
migrate_api.downgrade(url=db_url, repository=db_repo, version=version)
v2 = get_db_version()
if v1 == v2:
print 'No changes made.'
else:
print 'Downgraded: %s ... %s' % (v1, v2) | python | def db_downgrade(version):
"""Downgrade the database"""
v1 = get_db_version()
migrate_api.downgrade(url=db_url, repository=db_repo, version=version)
v2 = get_db_version()
if v1 == v2:
print 'No changes made.'
else:
print 'Downgraded: %s ... %s' % (v1, v2) | [
"def",
"db_downgrade",
"(",
"version",
")",
":",
"v1",
"=",
"get_db_version",
"(",
")",
"migrate_api",
".",
"downgrade",
"(",
"url",
"=",
"db_url",
",",
"repository",
"=",
"db_repo",
",",
"version",
"=",
"version",
")",
"v2",
"=",
"get_db_version",
"(",
... | Downgrade the database | [
"Downgrade",
"the",
"database"
] | train | https://github.com/rehandalal/buchner/blob/dc22a61c493b9d4a74d76e8b42a319aa13e385f3/buchner/project-template/manage.py#L40-L49 |
rehandalal/buchner | buchner/project-template/manage.py | db_upgrade | def db_upgrade(version=None):
"""Upgrade the database"""
v1 = get_db_version()
migrate_api.upgrade(url=db_url, repository=db_repo, version=version)
v2 = get_db_version()
if v1 == v2:
print 'Database already up-to-date.'
else:
print 'Upgraded: %s ... %s' % (v1, v2) | python | def db_upgrade(version=None):
"""Upgrade the database"""
v1 = get_db_version()
migrate_api.upgrade(url=db_url, repository=db_repo, version=version)
v2 = get_db_version()
if v1 == v2:
print 'Database already up-to-date.'
else:
print 'Upgraded: %s ... %s' % (v1, v2) | [
"def",
"db_upgrade",
"(",
"version",
"=",
"None",
")",
":",
"v1",
"=",
"get_db_version",
"(",
")",
"migrate_api",
".",
"upgrade",
"(",
"url",
"=",
"db_url",
",",
"repository",
"=",
"db_repo",
",",
"version",
"=",
"version",
")",
"v2",
"=",
"get_db_versio... | Upgrade the database | [
"Upgrade",
"the",
"database"
] | train | https://github.com/rehandalal/buchner/blob/dc22a61c493b9d4a74d76e8b42a319aa13e385f3/buchner/project-template/manage.py#L53-L62 |
rehandalal/buchner | buchner/project-template/manage.py | install_npm_modules | def install_npm_modules():
"""Uses npm to dependencies in node.json"""
# This is a little weird, but we do it this way because if you
# have package.json, then heroku thinks this might be a node.js
# app.
call_command('cp node.json package.json', verbose=True)
call_command('npm install', verbose... | python | def install_npm_modules():
"""Uses npm to dependencies in node.json"""
# This is a little weird, but we do it this way because if you
# have package.json, then heroku thinks this might be a node.js
# app.
call_command('cp node.json package.json', verbose=True)
call_command('npm install', verbose... | [
"def",
"install_npm_modules",
"(",
")",
":",
"# This is a little weird, but we do it this way because if you",
"# have package.json, then heroku thinks this might be a node.js",
"# app.",
"call_command",
"(",
"'cp node.json package.json'",
",",
"verbose",
"=",
"True",
")",
"call_comm... | Uses npm to dependencies in node.json | [
"Uses",
"npm",
"to",
"dependencies",
"in",
"node",
".",
"json"
] | train | https://github.com/rehandalal/buchner/blob/dc22a61c493b9d4a74d76e8b42a319aa13e385f3/buchner/project-template/manage.py#L79-L86 |
asyncdef/interfaces | asyncdef/interfaces/engine/itime.py | ITime.defer | def defer(
self,
func: typing.Callable[[], typing.Any],
until: typing.Union[int, float]=-1,
) -> typing.Any:
"""Defer the execution of a function until some clock value.
Args:
func (typing.Callable[[], typing.Any]): A callable that accepts no
... | python | def defer(
self,
func: typing.Callable[[], typing.Any],
until: typing.Union[int, float]=-1,
) -> typing.Any:
"""Defer the execution of a function until some clock value.
Args:
func (typing.Callable[[], typing.Any]): A callable that accepts no
... | [
"def",
"defer",
"(",
"self",
",",
"func",
":",
"typing",
".",
"Callable",
"[",
"[",
"]",
",",
"typing",
".",
"Any",
"]",
",",
"until",
":",
"typing",
".",
"Union",
"[",
"int",
",",
"float",
"]",
"=",
"-",
"1",
",",
")",
"->",
"typing",
".",
"... | Defer the execution of a function until some clock value.
Args:
func (typing.Callable[[], typing.Any]): A callable that accepts no
arguments. All return values are ignored.
until (typing.Union[int, float]): A numeric value that represents
the clock time w... | [
"Defer",
"the",
"execution",
"of",
"a",
"function",
"until",
"some",
"clock",
"value",
"."
] | train | https://github.com/asyncdef/interfaces/blob/17c589c6ab158e3d9977a6d9da6d5ecd44844285/asyncdef/interfaces/engine/itime.py#L24-L50 |
asyncdef/interfaces | asyncdef/interfaces/engine/itime.py | ITime.defer_for | def defer_for(
self,
wait: typing.Union[int, float],
func: typing.Callable[[], typing.Any],
) -> typing.Any:
"""Defer the execution of a function for some number of seconds.
Args:
wait (typing.Union[int, float]): A numeric value that represents
... | python | def defer_for(
self,
wait: typing.Union[int, float],
func: typing.Callable[[], typing.Any],
) -> typing.Any:
"""Defer the execution of a function for some number of seconds.
Args:
wait (typing.Union[int, float]): A numeric value that represents
... | [
"def",
"defer_for",
"(",
"self",
",",
"wait",
":",
"typing",
".",
"Union",
"[",
"int",
",",
"float",
"]",
",",
"func",
":",
"typing",
".",
"Callable",
"[",
"[",
"]",
",",
"typing",
".",
"Any",
"]",
",",
")",
"->",
"typing",
".",
"Any",
":",
"ra... | Defer the execution of a function for some number of seconds.
Args:
wait (typing.Union[int, float]): A numeric value that represents
the number of seconds that must pass before the callback
becomes available for execution. All given values must be
pos... | [
"Defer",
"the",
"execution",
"of",
"a",
"function",
"for",
"some",
"number",
"of",
"seconds",
"."
] | train | https://github.com/asyncdef/interfaces/blob/17c589c6ab158e3d9977a6d9da6d5ecd44844285/asyncdef/interfaces/engine/itime.py#L53-L73 |
asyncdef/interfaces | asyncdef/interfaces/engine/itime.py | ITime.delay | def delay(
self,
identifier: typing.Any,
until: typing.Union[int, float]=-1,
) -> bool:
"""Delay a deferred function until the given time.
Args:
identifier (typing.Any): The identifier returned from a call
to defer or defer_for.
... | python | def delay(
self,
identifier: typing.Any,
until: typing.Union[int, float]=-1,
) -> bool:
"""Delay a deferred function until the given time.
Args:
identifier (typing.Any): The identifier returned from a call
to defer or defer_for.
... | [
"def",
"delay",
"(",
"self",
",",
"identifier",
":",
"typing",
".",
"Any",
",",
"until",
":",
"typing",
".",
"Union",
"[",
"int",
",",
"float",
"]",
"=",
"-",
"1",
",",
")",
"->",
"bool",
":",
"raise",
"NotImplementedError",
"(",
")"
] | Delay a deferred function until the given time.
Args:
identifier (typing.Any): The identifier returned from a call
to defer or defer_for.
until (typing.Union[int, float]): A numeric value that represents
the clock time when the callback becomes available ... | [
"Delay",
"a",
"deferred",
"function",
"until",
"the",
"given",
"time",
"."
] | train | https://github.com/asyncdef/interfaces/blob/17c589c6ab158e3d9977a6d9da6d5ecd44844285/asyncdef/interfaces/engine/itime.py#L76-L95 |
asyncdef/interfaces | asyncdef/interfaces/engine/itime.py | ITime.delay_for | def delay_for(
self,
wait: typing.Union[int, float],
identifier: typing.Any,
) -> bool:
"""Defer the execution of a function for some number of seconds.
Args:
wait (typing.Union[int, float]): A numeric value that represents
the number ... | python | def delay_for(
self,
wait: typing.Union[int, float],
identifier: typing.Any,
) -> bool:
"""Defer the execution of a function for some number of seconds.
Args:
wait (typing.Union[int, float]): A numeric value that represents
the number ... | [
"def",
"delay_for",
"(",
"self",
",",
"wait",
":",
"typing",
".",
"Union",
"[",
"int",
",",
"float",
"]",
",",
"identifier",
":",
"typing",
".",
"Any",
",",
")",
"->",
"bool",
":",
"raise",
"NotImplementedError",
"(",
")"
] | Defer the execution of a function for some number of seconds.
Args:
wait (typing.Union[int, float]): A numeric value that represents
the number of seconds that must pass before the callback
becomes available for execution. All given values must be
pos... | [
"Defer",
"the",
"execution",
"of",
"a",
"function",
"for",
"some",
"number",
"of",
"seconds",
"."
] | train | https://github.com/asyncdef/interfaces/blob/17c589c6ab158e3d9977a6d9da6d5ecd44844285/asyncdef/interfaces/engine/itime.py#L98-L117 |
davidmiller/letter | letter/contrib/contact.py | EmailForm.send_email | def send_email(self, to):
"""
Do work.
"""
body = self.body()
subject = self.subject()
import letter
class Message(letter.Letter):
Postie = letter.DjangoPostman()
From = getattr(settings, 'DEFAULT_FROM_EMAIL', 'contact@example.com')
... | python | def send_email(self, to):
"""
Do work.
"""
body = self.body()
subject = self.subject()
import letter
class Message(letter.Letter):
Postie = letter.DjangoPostman()
From = getattr(settings, 'DEFAULT_FROM_EMAIL', 'contact@example.com')
... | [
"def",
"send_email",
"(",
"self",
",",
"to",
")",
":",
"body",
"=",
"self",
".",
"body",
"(",
")",
"subject",
"=",
"self",
".",
"subject",
"(",
")",
"import",
"letter",
"class",
"Message",
"(",
"letter",
".",
"Letter",
")",
":",
"Postie",
"=",
"let... | Do work. | [
"Do",
"work",
"."
] | train | https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/contrib/contact.py#L24-L45 |
davidmiller/letter | letter/contrib/contact.py | EmailView.form_valid | def form_valid(self, form):
"""
Praise be, someone has spammed us.
"""
form.send_email(to=self.to_addr)
return super(EmailView, self).form_valid(form) | python | def form_valid(self, form):
"""
Praise be, someone has spammed us.
"""
form.send_email(to=self.to_addr)
return super(EmailView, self).form_valid(form) | [
"def",
"form_valid",
"(",
"self",
",",
"form",
")",
":",
"form",
".",
"send_email",
"(",
"to",
"=",
"self",
".",
"to_addr",
")",
"return",
"super",
"(",
"EmailView",
",",
"self",
")",
".",
"form_valid",
"(",
"form",
")"
] | Praise be, someone has spammed us. | [
"Praise",
"be",
"someone",
"has",
"spammed",
"us",
"."
] | train | https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/contrib/contact.py#L87-L92 |
tevino/mongu | mongu.py | Client.register_model | def register_model(self, model_cls):
"""Decorator for registering model."""
if not getattr(model_cls, '_database_'):
raise ModelAttributeError('_database_ missing '
'on %s!' % model_cls.__name__)
if not getattr(model_cls, '_collection_'):
... | python | def register_model(self, model_cls):
"""Decorator for registering model."""
if not getattr(model_cls, '_database_'):
raise ModelAttributeError('_database_ missing '
'on %s!' % model_cls.__name__)
if not getattr(model_cls, '_collection_'):
... | [
"def",
"register_model",
"(",
"self",
",",
"model_cls",
")",
":",
"if",
"not",
"getattr",
"(",
"model_cls",
",",
"'_database_'",
")",
":",
"raise",
"ModelAttributeError",
"(",
"'_database_ missing '",
"'on %s!'",
"%",
"model_cls",
".",
"__name__",
")",
"if",
"... | Decorator for registering model. | [
"Decorator",
"for",
"registering",
"model",
"."
] | train | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L34-L46 |
tevino/mongu | mongu.py | Client.enable_counter | def enable_counter(self, base=None, database='counter',
collection='counters'):
"""Register the builtin counter model, return the registered Counter
class and the corresponding ``CounterMixin`` class.
The ``CounterMixin`` automatically increases and decreases the counter
... | python | def enable_counter(self, base=None, database='counter',
collection='counters'):
"""Register the builtin counter model, return the registered Counter
class and the corresponding ``CounterMixin`` class.
The ``CounterMixin`` automatically increases and decreases the counter
... | [
"def",
"enable_counter",
"(",
"self",
",",
"base",
"=",
"None",
",",
"database",
"=",
"'counter'",
",",
"collection",
"=",
"'counters'",
")",
":",
"Counter",
".",
"_database_",
"=",
"database",
"Counter",
".",
"_collection_",
"=",
"collection",
"bases",
"=",... | Register the builtin counter model, return the registered Counter
class and the corresponding ``CounterMixin`` class.
The ``CounterMixin`` automatically increases and decreases the counter
after model creation(save without ``_id``) and deletion.
It contains a classmethod ``count()`` wh... | [
"Register",
"the",
"builtin",
"counter",
"model",
"return",
"the",
"registered",
"Counter",
"class",
"and",
"the",
"corresponding",
"CounterMixin",
"class",
"."
] | train | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L48-L100 |
tevino/mongu | mongu.py | Model.by_id | def by_id(cls, oid):
"""Find a model object by its ``ObjectId``,
``oid`` can be string or ObjectId"""
if oid:
d = cls.collection.find_one(ObjectId(oid))
if d:
return cls(**d) | python | def by_id(cls, oid):
"""Find a model object by its ``ObjectId``,
``oid`` can be string or ObjectId"""
if oid:
d = cls.collection.find_one(ObjectId(oid))
if d:
return cls(**d) | [
"def",
"by_id",
"(",
"cls",
",",
"oid",
")",
":",
"if",
"oid",
":",
"d",
"=",
"cls",
".",
"collection",
".",
"find_one",
"(",
"ObjectId",
"(",
"oid",
")",
")",
"if",
"d",
":",
"return",
"cls",
"(",
"*",
"*",
"d",
")"
] | Find a model object by its ``ObjectId``,
``oid`` can be string or ObjectId | [
"Find",
"a",
"model",
"object",
"by",
"its",
"ObjectId",
"oid",
"can",
"be",
"string",
"or",
"ObjectId"
] | train | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L164-L170 |
tevino/mongu | mongu.py | Model.from_dict | def from_dict(cls, d):
"""Build model object from a dict. Will be removed in v1.0"""
warnings.warn(
'from_dict is deprecated and will be removed in v1.0!',
stacklevel=2)
d = d or {}
return cls(**d) | python | def from_dict(cls, d):
"""Build model object from a dict. Will be removed in v1.0"""
warnings.warn(
'from_dict is deprecated and will be removed in v1.0!',
stacklevel=2)
d = d or {}
return cls(**d) | [
"def",
"from_dict",
"(",
"cls",
",",
"d",
")",
":",
"warnings",
".",
"warn",
"(",
"'from_dict is deprecated and will be removed in v1.0!'",
",",
"stacklevel",
"=",
"2",
")",
"d",
"=",
"d",
"or",
"{",
"}",
"return",
"cls",
"(",
"*",
"*",
"d",
")"
] | Build model object from a dict. Will be removed in v1.0 | [
"Build",
"model",
"object",
"from",
"a",
"dict",
".",
"Will",
"be",
"removed",
"in",
"v1",
".",
"0"
] | train | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L180-L186 |
tevino/mongu | mongu.py | Model.find | def find(cls, *args, **kwargs):
"""Same as ``collection.find``, returns model object instead of dict."""
return cls.from_cursor(cls.collection.find(*args, **kwargs)) | python | def find(cls, *args, **kwargs):
"""Same as ``collection.find``, returns model object instead of dict."""
return cls.from_cursor(cls.collection.find(*args, **kwargs)) | [
"def",
"find",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
".",
"from_cursor",
"(",
"cls",
".",
"collection",
".",
"find",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | Same as ``collection.find``, returns model object instead of dict. | [
"Same",
"as",
"collection",
".",
"find",
"returns",
"model",
"object",
"instead",
"of",
"dict",
"."
] | train | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L195-L197 |
tevino/mongu | mongu.py | Model.find_one | def find_one(cls, *args, **kwargs):
"""Same as ``collection.find_one``, returns model object instead of
dict."""
d = cls.collection.find_one(*args, **kwargs)
if d:
return cls(**d) | python | def find_one(cls, *args, **kwargs):
"""Same as ``collection.find_one``, returns model object instead of
dict."""
d = cls.collection.find_one(*args, **kwargs)
if d:
return cls(**d) | [
"def",
"find_one",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"cls",
".",
"collection",
".",
"find_one",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"d",
":",
"return",
"cls",
"(",
"*",
"*",
"d",
")"
... | Same as ``collection.find_one``, returns model object instead of
dict. | [
"Same",
"as",
"collection",
".",
"find_one",
"returns",
"model",
"object",
"instead",
"of",
"dict",
"."
] | train | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L200-L205 |
tevino/mongu | mongu.py | Model.reload | def reload(self, d=None):
"""Reload model from given dict or database."""
if d:
self.clear()
self.update(d)
elif self.id:
new_dict = self.by_id(self._id)
self.clear()
self.update(new_dict)
else:
# should I raise an e... | python | def reload(self, d=None):
"""Reload model from given dict or database."""
if d:
self.clear()
self.update(d)
elif self.id:
new_dict = self.by_id(self._id)
self.clear()
self.update(new_dict)
else:
# should I raise an e... | [
"def",
"reload",
"(",
"self",
",",
"d",
"=",
"None",
")",
":",
"if",
"d",
":",
"self",
".",
"clear",
"(",
")",
"self",
".",
"update",
"(",
"d",
")",
"elif",
"self",
".",
"id",
":",
"new_dict",
"=",
"self",
".",
"by_id",
"(",
"self",
".",
"_id... | Reload model from given dict or database. | [
"Reload",
"model",
"from",
"given",
"dict",
"or",
"database",
"."
] | train | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L213-L225 |
tevino/mongu | mongu.py | Model.save | def save(self):
"""Save model object to database."""
d = dict(self)
old_dict = d.copy()
_id = self.collection.save(d)
self._id = _id
self.on_save(old_dict)
return self._id | python | def save(self):
"""Save model object to database."""
d = dict(self)
old_dict = d.copy()
_id = self.collection.save(d)
self._id = _id
self.on_save(old_dict)
return self._id | [
"def",
"save",
"(",
"self",
")",
":",
"d",
"=",
"dict",
"(",
"self",
")",
"old_dict",
"=",
"d",
".",
"copy",
"(",
")",
"_id",
"=",
"self",
".",
"collection",
".",
"save",
"(",
"d",
")",
"self",
".",
"_id",
"=",
"_id",
"self",
".",
"on_save",
... | Save model object to database. | [
"Save",
"model",
"object",
"to",
"database",
"."
] | train | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L231-L238 |
tevino/mongu | mongu.py | Model.delete | def delete(self):
"""Remove from database."""
if not self.id:
return
self.collection.remove({'_id': self._id})
self.on_delete(self) | python | def delete(self):
"""Remove from database."""
if not self.id:
return
self.collection.remove({'_id': self._id})
self.on_delete(self) | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"id",
":",
"return",
"self",
".",
"collection",
".",
"remove",
"(",
"{",
"'_id'",
":",
"self",
".",
"_id",
"}",
")",
"self",
".",
"on_delete",
"(",
"self",
")"
] | Remove from database. | [
"Remove",
"from",
"database",
"."
] | train | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L244-L249 |
tevino/mongu | mongu.py | Counter.set_to | def set_to(cls, name, num):
"""Set counter of ``name`` to ``num``."""
if num < 0:
raise CounterValueError('Counter[%s] can not be set to %s' % (
name, num))
else:
counter = cls.collection.find_and_modify(
{'name': name},... | python | def set_to(cls, name, num):
"""Set counter of ``name`` to ``num``."""
if num < 0:
raise CounterValueError('Counter[%s] can not be set to %s' % (
name, num))
else:
counter = cls.collection.find_and_modify(
{'name': name},... | [
"def",
"set_to",
"(",
"cls",
",",
"name",
",",
"num",
")",
":",
"if",
"num",
"<",
"0",
":",
"raise",
"CounterValueError",
"(",
"'Counter[%s] can not be set to %s'",
"%",
"(",
"name",
",",
"num",
")",
")",
"else",
":",
"counter",
"=",
"cls",
".",
"colle... | Set counter of ``name`` to ``num``. | [
"Set",
"counter",
"of",
"name",
"to",
"num",
"."
] | train | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L255-L267 |
tevino/mongu | mongu.py | Counter.change_by | def change_by(cls, name, num):
"""Change counter of ``name`` by ``num`` (can be negative)."""
count = cls.count(name)
if count + num < 0:
raise CounterValueError('Counter[%s] will be negative '
'after %+d.' % (name, num))
counter = cls.col... | python | def change_by(cls, name, num):
"""Change counter of ``name`` by ``num`` (can be negative)."""
count = cls.count(name)
if count + num < 0:
raise CounterValueError('Counter[%s] will be negative '
'after %+d.' % (name, num))
counter = cls.col... | [
"def",
"change_by",
"(",
"cls",
",",
"name",
",",
"num",
")",
":",
"count",
"=",
"cls",
".",
"count",
"(",
"name",
")",
"if",
"count",
"+",
"num",
"<",
"0",
":",
"raise",
"CounterValueError",
"(",
"'Counter[%s] will be negative '",
"'after %+d.'",
"%",
"... | Change counter of ``name`` by ``num`` (can be negative). | [
"Change",
"counter",
"of",
"name",
"by",
"num",
"(",
"can",
"be",
"negative",
")",
"."
] | train | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L270-L283 |
tevino/mongu | mongu.py | Counter.count | def count(cls, name):
"""Return the count of ``name``"""
counter = cls.collection.find_one({'name': name}) or {}
return counter.get('seq', 0) | python | def count(cls, name):
"""Return the count of ``name``"""
counter = cls.collection.find_one({'name': name}) or {}
return counter.get('seq', 0) | [
"def",
"count",
"(",
"cls",
",",
"name",
")",
":",
"counter",
"=",
"cls",
".",
"collection",
".",
"find_one",
"(",
"{",
"'name'",
":",
"name",
"}",
")",
"or",
"{",
"}",
"return",
"counter",
".",
"get",
"(",
"'seq'",
",",
"0",
")"
] | Return the count of ``name`` | [
"Return",
"the",
"count",
"of",
"name"
] | train | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L296-L299 |
gear11/pypelogs | pypein/wikip.py | geo_filter | def geo_filter(d):
"""Inspects the given Wikipedia article dict for geo-coordinates.
If no coordinates are found, returns None. Otherwise, returns a new dict
with the title and URL of the original article, along with coordinates."""
page = d["page"]
if not "revision" in page:
return None
... | python | def geo_filter(d):
"""Inspects the given Wikipedia article dict for geo-coordinates.
If no coordinates are found, returns None. Otherwise, returns a new dict
with the title and URL of the original article, along with coordinates."""
page = d["page"]
if not "revision" in page:
return None
... | [
"def",
"geo_filter",
"(",
"d",
")",
":",
"page",
"=",
"d",
"[",
"\"page\"",
"]",
"if",
"not",
"\"revision\"",
"in",
"page",
":",
"return",
"None",
"title",
"=",
"page",
"[",
"\"title\"",
"]",
"if",
"skip_article",
"(",
"title",
")",
":",
"LOG",
".",
... | Inspects the given Wikipedia article dict for geo-coordinates.
If no coordinates are found, returns None. Otherwise, returns a new dict
with the title and URL of the original article, along with coordinates. | [
"Inspects",
"the",
"given",
"Wikipedia",
"article",
"dict",
"for",
"geo",
"-",
"coordinates",
"."
] | train | https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/wikip.py#L76-L111 |
gear11/pypelogs | pypein/wikip.py | find_geo_coords | def find_geo_coords(s):
"""Returns a list of lat/lons found by scanning the given text"""
coords = []
LOG.debug("Matching in text size %s", len(s))
for c in INFO_BOX_LAT_LON.findall(s):
try:
coord = (float(c[1]), float(c[2])) #, c[0])
coords.append(coord)
LOG... | python | def find_geo_coords(s):
"""Returns a list of lat/lons found by scanning the given text"""
coords = []
LOG.debug("Matching in text size %s", len(s))
for c in INFO_BOX_LAT_LON.findall(s):
try:
coord = (float(c[1]), float(c[2])) #, c[0])
coords.append(coord)
LOG... | [
"def",
"find_geo_coords",
"(",
"s",
")",
":",
"coords",
"=",
"[",
"]",
"LOG",
".",
"debug",
"(",
"\"Matching in text size %s\"",
",",
"len",
"(",
"s",
")",
")",
"for",
"c",
"in",
"INFO_BOX_LAT_LON",
".",
"findall",
"(",
"s",
")",
":",
"try",
":",
"co... | Returns a list of lat/lons found by scanning the given text | [
"Returns",
"a",
"list",
"of",
"lat",
"/",
"lons",
"found",
"by",
"scanning",
"the",
"given",
"text"
] | train | https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/wikip.py#L132-L177 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.