id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
6,300 | ckoepp/TwitterSearch | TwitterSearch/TwitterUserOrder.py | TwitterUserOrder.set_include_rts | def set_include_rts(self, rts):
""" Sets 'include_rts' parameter. When set to False, \
the timeline will strip any native retweets from the returned timeline
:param rts: Boolean triggering the usage of the parameter
:raises: TwitterSearchException
"""
if not isinstance(... | python | def set_include_rts(self, rts):
""" Sets 'include_rts' parameter. When set to False, \
the timeline will strip any native retweets from the returned timeline
:param rts: Boolean triggering the usage of the parameter
:raises: TwitterSearchException
"""
if not isinstance(... | [
"def",
"set_include_rts",
"(",
"self",
",",
"rts",
")",
":",
"if",
"not",
"isinstance",
"(",
"rts",
",",
"bool",
")",
":",
"raise",
"TwitterSearchException",
"(",
"1008",
")",
"self",
".",
"arguments",
".",
"update",
"(",
"{",
"'include_rts'",
":",
"'tru... | Sets 'include_rts' parameter. When set to False, \
the timeline will strip any native retweets from the returned timeline
:param rts: Boolean triggering the usage of the parameter
:raises: TwitterSearchException | [
"Sets",
"include_rts",
"parameter",
".",
"When",
"set",
"to",
"False",
"\\",
"the",
"timeline",
"will",
"strip",
"any",
"native",
"retweets",
"from",
"the",
"returned",
"timeline"
] | 627b9f519d49faf6b83859717f9082b3b2622aaf | https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterUserOrder.py#L68-L78 |
6,301 | ckoepp/TwitterSearch | TwitterSearch/TwitterUserOrder.py | TwitterUserOrder.set_exclude_replies | def set_exclude_replies(self, exclude):
""" Sets 'exclude_replies' parameter used to \
prevent replies from appearing in the returned timeline
:param exclude: Boolean triggering the usage of the parameter
:raises: TwitterSearchException
"""
if not isinstance(exclude, bo... | python | def set_exclude_replies(self, exclude):
""" Sets 'exclude_replies' parameter used to \
prevent replies from appearing in the returned timeline
:param exclude: Boolean triggering the usage of the parameter
:raises: TwitterSearchException
"""
if not isinstance(exclude, bo... | [
"def",
"set_exclude_replies",
"(",
"self",
",",
"exclude",
")",
":",
"if",
"not",
"isinstance",
"(",
"exclude",
",",
"bool",
")",
":",
"raise",
"TwitterSearchException",
"(",
"1008",
")",
"self",
".",
"arguments",
".",
"update",
"(",
"{",
"'exclude_replies'"... | Sets 'exclude_replies' parameter used to \
prevent replies from appearing in the returned timeline
:param exclude: Boolean triggering the usage of the parameter
:raises: TwitterSearchException | [
"Sets",
"exclude_replies",
"parameter",
"used",
"to",
"\\",
"prevent",
"replies",
"from",
"appearing",
"in",
"the",
"returned",
"timeline"
] | 627b9f519d49faf6b83859717f9082b3b2622aaf | https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterUserOrder.py#L80-L92 |
6,302 | ckoepp/TwitterSearch | TwitterSearch/TwitterUserOrder.py | TwitterUserOrder.set_contributor_details | def set_contributor_details(self, contdetails):
""" Sets 'contributor_details' parameter used to enhance the \
contributors element of the status response to include \
the screen_name of the contributor. By default only \
the user_id of the contributor is included
:param contdet... | python | def set_contributor_details(self, contdetails):
""" Sets 'contributor_details' parameter used to enhance the \
contributors element of the status response to include \
the screen_name of the contributor. By default only \
the user_id of the contributor is included
:param contdet... | [
"def",
"set_contributor_details",
"(",
"self",
",",
"contdetails",
")",
":",
"if",
"not",
"isinstance",
"(",
"contdetails",
",",
"bool",
")",
":",
"raise",
"TwitterSearchException",
"(",
"1008",
")",
"self",
".",
"arguments",
".",
"update",
"(",
"{",
"'contr... | Sets 'contributor_details' parameter used to enhance the \
contributors element of the status response to include \
the screen_name of the contributor. By default only \
the user_id of the contributor is included
:param contdetails: Boolean triggering the usage of the parameter
... | [
"Sets",
"contributor_details",
"parameter",
"used",
"to",
"enhance",
"the",
"\\",
"contributors",
"element",
"of",
"the",
"status",
"response",
"to",
"include",
"\\",
"the",
"screen_name",
"of",
"the",
"contributor",
".",
"By",
"default",
"only",
"\\",
"the",
... | 627b9f519d49faf6b83859717f9082b3b2622aaf | https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterUserOrder.py#L94-L108 |
6,303 | tkaemming/django-subdomains | subdomains/templatetags/subdomainurls.py | url | def url(context, view, subdomain=UNSET, *args, **kwargs):
"""
Resolves a URL in a template, using subdomain-based URL resolution.
If no subdomain is provided and a ``request`` is in the template context
when rendering, the URL will be resolved relative to the current request's
subdomain. If no ``re... | python | def url(context, view, subdomain=UNSET, *args, **kwargs):
"""
Resolves a URL in a template, using subdomain-based URL resolution.
If no subdomain is provided and a ``request`` is in the template context
when rendering, the URL will be resolved relative to the current request's
subdomain. If no ``re... | [
"def",
"url",
"(",
"context",
",",
"view",
",",
"subdomain",
"=",
"UNSET",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"subdomain",
"is",
"UNSET",
":",
"request",
"=",
"context",
".",
"get",
"(",
"'request'",
")",
"if",
"request",
"i... | Resolves a URL in a template, using subdomain-based URL resolution.
If no subdomain is provided and a ``request`` is in the template context
when rendering, the URL will be resolved relative to the current request's
subdomain. If no ``request`` is provided, the URL will be resolved relative
to current ... | [
"Resolves",
"a",
"URL",
"in",
"a",
"template",
"using",
"subdomain",
"-",
"based",
"URL",
"resolution",
"."
] | be6cc1c556a2007287ef4e647ea1784cf7690a44 | https://github.com/tkaemming/django-subdomains/blob/be6cc1c556a2007287ef4e647ea1784cf7690a44/subdomains/templatetags/subdomainurls.py#L12-L43 |
6,304 | tkaemming/django-subdomains | subdomains/utils.py | urljoin | def urljoin(domain, path=None, scheme=None):
"""
Joins a domain, path and scheme part together, returning a full URL.
:param domain: the domain, e.g. ``example.com``
:param path: the path part of the URL, e.g. ``/example/``
:param scheme: the scheme part of the URL, e.g. ``http``, defaulting to the... | python | def urljoin(domain, path=None, scheme=None):
"""
Joins a domain, path and scheme part together, returning a full URL.
:param domain: the domain, e.g. ``example.com``
:param path: the path part of the URL, e.g. ``/example/``
:param scheme: the scheme part of the URL, e.g. ``http``, defaulting to the... | [
"def",
"urljoin",
"(",
"domain",
",",
"path",
"=",
"None",
",",
"scheme",
"=",
"None",
")",
":",
"if",
"scheme",
"is",
"None",
":",
"scheme",
"=",
"getattr",
"(",
"settings",
",",
"'DEFAULT_URL_SCHEME'",
",",
"'http'",
")",
"return",
"urlunparse",
"(",
... | Joins a domain, path and scheme part together, returning a full URL.
:param domain: the domain, e.g. ``example.com``
:param path: the path part of the URL, e.g. ``/example/``
:param scheme: the scheme part of the URL, e.g. ``http``, defaulting to the
value of ``settings.DEFAULT_URL_SCHEME``
:re... | [
"Joins",
"a",
"domain",
"path",
"and",
"scheme",
"part",
"together",
"returning",
"a",
"full",
"URL",
"."
] | be6cc1c556a2007287ef4e647ea1784cf7690a44 | https://github.com/tkaemming/django-subdomains/blob/be6cc1c556a2007287ef4e647ea1784cf7690a44/subdomains/utils.py#L25-L38 |
6,305 | tkaemming/django-subdomains | subdomains/middleware.py | SubdomainMiddleware.process_request | def process_request(self, request):
"""
Adds a ``subdomain`` attribute to the ``request`` parameter.
"""
domain, host = map(lower,
(self.get_domain_for_request(request), request.get_host()))
pattern = r'^(?:(?P<subdomain>.*?)\.)?%s(?::.*)?$' % re.escape(domain)
... | python | def process_request(self, request):
"""
Adds a ``subdomain`` attribute to the ``request`` parameter.
"""
domain, host = map(lower,
(self.get_domain_for_request(request), request.get_host()))
pattern = r'^(?:(?P<subdomain>.*?)\.)?%s(?::.*)?$' % re.escape(domain)
... | [
"def",
"process_request",
"(",
"self",
",",
"request",
")",
":",
"domain",
",",
"host",
"=",
"map",
"(",
"lower",
",",
"(",
"self",
".",
"get_domain_for_request",
"(",
"request",
")",
",",
"request",
".",
"get_host",
"(",
")",
")",
")",
"pattern",
"=",... | Adds a ``subdomain`` attribute to the ``request`` parameter. | [
"Adds",
"a",
"subdomain",
"attribute",
"to",
"the",
"request",
"parameter",
"."
] | be6cc1c556a2007287ef4e647ea1784cf7690a44 | https://github.com/tkaemming/django-subdomains/blob/be6cc1c556a2007287ef4e647ea1784cf7690a44/subdomains/middleware.py#L28-L44 |
6,306 | tkaemming/django-subdomains | subdomains/middleware.py | SubdomainURLRoutingMiddleware.process_request | def process_request(self, request):
"""
Sets the current request's ``urlconf`` attribute to the urlconf
associated with the subdomain, if it is listed in
``settings.SUBDOMAIN_URLCONFS``.
"""
super(SubdomainURLRoutingMiddleware, self).process_request(request)
subd... | python | def process_request(self, request):
"""
Sets the current request's ``urlconf`` attribute to the urlconf
associated with the subdomain, if it is listed in
``settings.SUBDOMAIN_URLCONFS``.
"""
super(SubdomainURLRoutingMiddleware, self).process_request(request)
subd... | [
"def",
"process_request",
"(",
"self",
",",
"request",
")",
":",
"super",
"(",
"SubdomainURLRoutingMiddleware",
",",
"self",
")",
".",
"process_request",
"(",
"request",
")",
"subdomain",
"=",
"getattr",
"(",
"request",
",",
"'subdomain'",
",",
"UNSET",
")",
... | Sets the current request's ``urlconf`` attribute to the urlconf
associated with the subdomain, if it is listed in
``settings.SUBDOMAIN_URLCONFS``. | [
"Sets",
"the",
"current",
"request",
"s",
"urlconf",
"attribute",
"to",
"the",
"urlconf",
"associated",
"with",
"the",
"subdomain",
"if",
"it",
"is",
"listed",
"in",
"settings",
".",
"SUBDOMAIN_URLCONFS",
"."
] | be6cc1c556a2007287ef4e647ea1784cf7690a44 | https://github.com/tkaemming/django-subdomains/blob/be6cc1c556a2007287ef4e647ea1784cf7690a44/subdomains/middleware.py#L51-L66 |
6,307 | tkaemming/django-subdomains | subdomains/middleware.py | SubdomainURLRoutingMiddleware.process_response | def process_response(self, request, response):
"""
Forces the HTTP ``Vary`` header onto requests to avoid having responses
cached across subdomains.
"""
if getattr(settings, 'FORCE_VARY_ON_HOST', True):
patch_vary_headers(response, ('Host',))
return response | python | def process_response(self, request, response):
"""
Forces the HTTP ``Vary`` header onto requests to avoid having responses
cached across subdomains.
"""
if getattr(settings, 'FORCE_VARY_ON_HOST', True):
patch_vary_headers(response, ('Host',))
return response | [
"def",
"process_response",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"if",
"getattr",
"(",
"settings",
",",
"'FORCE_VARY_ON_HOST'",
",",
"True",
")",
":",
"patch_vary_headers",
"(",
"response",
",",
"(",
"'Host'",
",",
")",
")",
"return",
"re... | Forces the HTTP ``Vary`` header onto requests to avoid having responses
cached across subdomains. | [
"Forces",
"the",
"HTTP",
"Vary",
"header",
"onto",
"requests",
"to",
"avoid",
"having",
"responses",
"cached",
"across",
"subdomains",
"."
] | be6cc1c556a2007287ef4e647ea1784cf7690a44 | https://github.com/tkaemming/django-subdomains/blob/be6cc1c556a2007287ef4e647ea1784cf7690a44/subdomains/middleware.py#L68-L76 |
6,308 | python-constraint/python-constraint | documentation/source/conf.py | process_docstring | def process_docstring(app, what, name, obj, options, lines):
"""
Process the docstring for a given python object.
Note that the list 'lines' is changed in this function. Sphinx
uses the altered content of the list.
"""
result = [re.sub(r'U\{([^}]*)\}', r'\1',
re.sub(r'(L|C)\... | python | def process_docstring(app, what, name, obj, options, lines):
"""
Process the docstring for a given python object.
Note that the list 'lines' is changed in this function. Sphinx
uses the altered content of the list.
"""
result = [re.sub(r'U\{([^}]*)\}', r'\1',
re.sub(r'(L|C)\... | [
"def",
"process_docstring",
"(",
"app",
",",
"what",
",",
"name",
",",
"obj",
",",
"options",
",",
"lines",
")",
":",
"result",
"=",
"[",
"re",
".",
"sub",
"(",
"r'U\\{([^}]*)\\}'",
",",
"r'\\1'",
",",
"re",
".",
"sub",
"(",
"r'(L|C)\\{([^}]*)\\}'",
",... | Process the docstring for a given python object.
Note that the list 'lines' is changed in this function. Sphinx
uses the altered content of the list. | [
"Process",
"the",
"docstring",
"for",
"a",
"given",
"python",
"object",
".",
"Note",
"that",
"the",
"list",
"lines",
"is",
"changed",
"in",
"this",
"function",
".",
"Sphinx",
"uses",
"the",
"altered",
"content",
"of",
"the",
"list",
"."
] | e23fe9852cddddf1c3e258e03f2175df24b4c702 | https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/documentation/source/conf.py#L86-L97 |
6,309 | python-constraint/python-constraint | constraint/__init__.py | doArc8 | def doArc8(arcs, domains, assignments):
"""
Perform the ARC-8 arc checking algorithm and prune domains
@attention: Currently unused.
"""
check = dict.fromkeys(domains, True)
while check:
variable, _ = check.popitem()
if variable not in arcs or variable in assignments:
... | python | def doArc8(arcs, domains, assignments):
"""
Perform the ARC-8 arc checking algorithm and prune domains
@attention: Currently unused.
"""
check = dict.fromkeys(domains, True)
while check:
variable, _ = check.popitem()
if variable not in arcs or variable in assignments:
... | [
"def",
"doArc8",
"(",
"arcs",
",",
"domains",
",",
"assignments",
")",
":",
"check",
"=",
"dict",
".",
"fromkeys",
"(",
"domains",
",",
"True",
")",
"while",
"check",
":",
"variable",
",",
"_",
"=",
"check",
".",
"popitem",
"(",
")",
"if",
"variable"... | Perform the ARC-8 arc checking algorithm and prune domains
@attention: Currently unused. | [
"Perform",
"the",
"ARC",
"-",
"8",
"arc",
"checking",
"algorithm",
"and",
"prune",
"domains"
] | e23fe9852cddddf1c3e258e03f2175df24b4c702 | https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L322-L366 |
6,310 | python-constraint/python-constraint | constraint/__init__.py | Problem.addVariables | def addVariables(self, variables, domain):
"""
Add one or more variables to the problem
Example:
>>> problem = Problem()
>>> problem.addVariables(["a", "b"], [1, 2, 3])
>>> solutions = problem.getSolutions()
>>> len(solutions)
9
>>> {'a': 3, 'b':... | python | def addVariables(self, variables, domain):
"""
Add one or more variables to the problem
Example:
>>> problem = Problem()
>>> problem.addVariables(["a", "b"], [1, 2, 3])
>>> solutions = problem.getSolutions()
>>> len(solutions)
9
>>> {'a': 3, 'b':... | [
"def",
"addVariables",
"(",
"self",
",",
"variables",
",",
"domain",
")",
":",
"for",
"variable",
"in",
"variables",
":",
"self",
".",
"addVariable",
"(",
"variable",
",",
"domain",
")"
] | Add one or more variables to the problem
Example:
>>> problem = Problem()
>>> problem.addVariables(["a", "b"], [1, 2, 3])
>>> solutions = problem.getSolutions()
>>> len(solutions)
9
>>> {'a': 3, 'b': 1} in solutions
True
@param variables: Any ob... | [
"Add",
"one",
"or",
"more",
"variables",
"to",
"the",
"problem"
] | e23fe9852cddddf1c3e258e03f2175df24b4c702 | https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L160-L182 |
6,311 | python-constraint/python-constraint | constraint/__init__.py | Problem.addConstraint | def addConstraint(self, constraint, variables=None):
"""
Add a constraint to the problem
Example:
>>> problem = Problem()
>>> problem.addVariables(["a", "b"], [1, 2, 3])
>>> problem.addConstraint(lambda a, b: b == a+1, ["a", "b"])
>>> solutions = problem.getSolu... | python | def addConstraint(self, constraint, variables=None):
"""
Add a constraint to the problem
Example:
>>> problem = Problem()
>>> problem.addVariables(["a", "b"], [1, 2, 3])
>>> problem.addConstraint(lambda a, b: b == a+1, ["a", "b"])
>>> solutions = problem.getSolu... | [
"def",
"addConstraint",
"(",
"self",
",",
"constraint",
",",
"variables",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"constraint",
",",
"Constraint",
")",
":",
"if",
"callable",
"(",
"constraint",
")",
":",
"constraint",
"=",
"FunctionConstraint"... | Add a constraint to the problem
Example:
>>> problem = Problem()
>>> problem.addVariables(["a", "b"], [1, 2, 3])
>>> problem.addConstraint(lambda a, b: b == a+1, ["a", "b"])
>>> solutions = problem.getSolutions()
>>>
@param constraint: Constraint to be included... | [
"Add",
"a",
"constraint",
"to",
"the",
"problem"
] | e23fe9852cddddf1c3e258e03f2175df24b4c702 | https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L184-L210 |
6,312 | python-constraint/python-constraint | constraint/__init__.py | Problem.getSolution | def getSolution(self):
"""
Find and return a solution to the problem
Example:
>>> problem = Problem()
>>> problem.getSolution() is None
True
>>> problem.addVariables(["a"], [42])
>>> problem.getSolution()
{'a': 42}
@return: Solution for ... | python | def getSolution(self):
"""
Find and return a solution to the problem
Example:
>>> problem = Problem()
>>> problem.getSolution() is None
True
>>> problem.addVariables(["a"], [42])
>>> problem.getSolution()
{'a': 42}
@return: Solution for ... | [
"def",
"getSolution",
"(",
"self",
")",
":",
"domains",
",",
"constraints",
",",
"vconstraints",
"=",
"self",
".",
"_getArgs",
"(",
")",
"if",
"not",
"domains",
":",
"return",
"None",
"return",
"self",
".",
"_solver",
".",
"getSolution",
"(",
"domains",
... | Find and return a solution to the problem
Example:
>>> problem = Problem()
>>> problem.getSolution() is None
True
>>> problem.addVariables(["a"], [42])
>>> problem.getSolution()
{'a': 42}
@return: Solution for the problem
@rtype: dictionary mapp... | [
"Find",
"and",
"return",
"a",
"solution",
"to",
"the",
"problem"
] | e23fe9852cddddf1c3e258e03f2175df24b4c702 | https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L212-L231 |
6,313 | python-constraint/python-constraint | constraint/__init__.py | Problem.getSolutions | def getSolutions(self):
"""
Find and return all solutions to the problem
Example:
>>> problem = Problem()
>>> problem.getSolutions() == []
True
>>> problem.addVariables(["a"], [42])
>>> problem.getSolutions()
[{'a': 42}]
@return: All sol... | python | def getSolutions(self):
"""
Find and return all solutions to the problem
Example:
>>> problem = Problem()
>>> problem.getSolutions() == []
True
>>> problem.addVariables(["a"], [42])
>>> problem.getSolutions()
[{'a': 42}]
@return: All sol... | [
"def",
"getSolutions",
"(",
"self",
")",
":",
"domains",
",",
"constraints",
",",
"vconstraints",
"=",
"self",
".",
"_getArgs",
"(",
")",
"if",
"not",
"domains",
":",
"return",
"[",
"]",
"return",
"self",
".",
"_solver",
".",
"getSolutions",
"(",
"domain... | Find and return all solutions to the problem
Example:
>>> problem = Problem()
>>> problem.getSolutions() == []
True
>>> problem.addVariables(["a"], [42])
>>> problem.getSolutions()
[{'a': 42}]
@return: All solutions for the problem
@rtype: list ... | [
"Find",
"and",
"return",
"all",
"solutions",
"to",
"the",
"problem"
] | e23fe9852cddddf1c3e258e03f2175df24b4c702 | https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L233-L252 |
6,314 | python-constraint/python-constraint | constraint/__init__.py | Problem.getSolutionIter | def getSolutionIter(self):
"""
Return an iterator to the solutions of the problem
Example:
>>> problem = Problem()
>>> list(problem.getSolutionIter()) == []
True
>>> problem.addVariables(["a"], [42])
>>> iter = problem.getSolutionIter()
>>> next(... | python | def getSolutionIter(self):
"""
Return an iterator to the solutions of the problem
Example:
>>> problem = Problem()
>>> list(problem.getSolutionIter()) == []
True
>>> problem.addVariables(["a"], [42])
>>> iter = problem.getSolutionIter()
>>> next(... | [
"def",
"getSolutionIter",
"(",
"self",
")",
":",
"domains",
",",
"constraints",
",",
"vconstraints",
"=",
"self",
".",
"_getArgs",
"(",
")",
"if",
"not",
"domains",
":",
"return",
"iter",
"(",
"(",
")",
")",
"return",
"self",
".",
"_solver",
".",
"getS... | Return an iterator to the solutions of the problem
Example:
>>> problem = Problem()
>>> list(problem.getSolutionIter()) == []
True
>>> problem.addVariables(["a"], [42])
>>> iter = problem.getSolutionIter()
>>> next(iter)
{'a': 42}
>>> next(iter)
... | [
"Return",
"an",
"iterator",
"to",
"the",
"solutions",
"of",
"the",
"problem"
] | e23fe9852cddddf1c3e258e03f2175df24b4c702 | https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L254-L275 |
6,315 | python-constraint/python-constraint | constraint/__init__.py | Solver.getSolution | def getSolution(self, domains, constraints, vconstraints):
"""
Return one solution for the given problem
@param domains: Dictionary mapping variables to their domains
@type domains: dict
@param constraints: List of pairs of (constraint, variables)
@type constraints: li... | python | def getSolution(self, domains, constraints, vconstraints):
"""
Return one solution for the given problem
@param domains: Dictionary mapping variables to their domains
@type domains: dict
@param constraints: List of pairs of (constraint, variables)
@type constraints: li... | [
"def",
"getSolution",
"(",
"self",
",",
"domains",
",",
"constraints",
",",
"vconstraints",
")",
":",
"msg",
"=",
"\"%s is an abstract class\"",
"%",
"self",
".",
"__class__",
".",
"__name__",
"raise",
"NotImplementedError",
"(",
"msg",
")"
] | Return one solution for the given problem
@param domains: Dictionary mapping variables to their domains
@type domains: dict
@param constraints: List of pairs of (constraint, variables)
@type constraints: list
@param vconstraints: Dictionary mapping variables to a list of
... | [
"Return",
"one",
"solution",
"for",
"the",
"given",
"problem"
] | e23fe9852cddddf1c3e258e03f2175df24b4c702 | https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L373-L386 |
6,316 | python-constraint/python-constraint | constraint/__init__.py | Domain.resetState | def resetState(self):
"""
Reset to the original domain state, including all possible values
"""
self.extend(self._hidden)
del self._hidden[:]
del self._states[:] | python | def resetState(self):
"""
Reset to the original domain state, including all possible values
"""
self.extend(self._hidden)
del self._hidden[:]
del self._states[:] | [
"def",
"resetState",
"(",
"self",
")",
":",
"self",
".",
"extend",
"(",
"self",
".",
"_hidden",
")",
"del",
"self",
".",
"_hidden",
"[",
":",
"]",
"del",
"self",
".",
"_states",
"[",
":",
"]"
] | Reset to the original domain state, including all possible values | [
"Reset",
"to",
"the",
"original",
"domain",
"state",
"including",
"all",
"possible",
"values"
] | e23fe9852cddddf1c3e258e03f2175df24b4c702 | https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L770-L776 |
6,317 | python-constraint/python-constraint | constraint/__init__.py | Domain.popState | def popState(self):
"""
Restore domain state from the top of the stack
Variables hidden since the last popped state are then available
again.
"""
diff = self._states.pop() - len(self)
if diff:
self.extend(self._hidden[-diff:])
del self._hi... | python | def popState(self):
"""
Restore domain state from the top of the stack
Variables hidden since the last popped state are then available
again.
"""
diff = self._states.pop() - len(self)
if diff:
self.extend(self._hidden[-diff:])
del self._hi... | [
"def",
"popState",
"(",
"self",
")",
":",
"diff",
"=",
"self",
".",
"_states",
".",
"pop",
"(",
")",
"-",
"len",
"(",
"self",
")",
"if",
"diff",
":",
"self",
".",
"extend",
"(",
"self",
".",
"_hidden",
"[",
"-",
"diff",
":",
"]",
")",
"del",
... | Restore domain state from the top of the stack
Variables hidden since the last popped state are then available
again. | [
"Restore",
"domain",
"state",
"from",
"the",
"top",
"of",
"the",
"stack"
] | e23fe9852cddddf1c3e258e03f2175df24b4c702 | https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L787-L797 |
6,318 | python-constraint/python-constraint | constraint/__init__.py | Domain.hideValue | def hideValue(self, value):
"""
Hide the given value from the domain
After that call the given value won't be seen as a possible value
on that domain anymore. The hidden value will be restored when the
previous saved state is popped.
@param value: Object currently avail... | python | def hideValue(self, value):
"""
Hide the given value from the domain
After that call the given value won't be seen as a possible value
on that domain anymore. The hidden value will be restored when the
previous saved state is popped.
@param value: Object currently avail... | [
"def",
"hideValue",
"(",
"self",
",",
"value",
")",
":",
"list",
".",
"remove",
"(",
"self",
",",
"value",
")",
"self",
".",
"_hidden",
".",
"append",
"(",
"value",
")"
] | Hide the given value from the domain
After that call the given value won't be seen as a possible value
on that domain anymore. The hidden value will be restored when the
previous saved state is popped.
@param value: Object currently available in the domain | [
"Hide",
"the",
"given",
"value",
"from",
"the",
"domain"
] | e23fe9852cddddf1c3e258e03f2175df24b4c702 | https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L799-L810 |
6,319 | python-constraint/python-constraint | constraint/__init__.py | Constraint.preProcess | def preProcess(self, variables, domains, constraints, vconstraints):
"""
Preprocess variable domains
This method is called before starting to look for solutions,
and is used to prune domains with specific constraint logic
when possible. For instance, any constraints with a singl... | python | def preProcess(self, variables, domains, constraints, vconstraints):
"""
Preprocess variable domains
This method is called before starting to look for solutions,
and is used to prune domains with specific constraint logic
when possible. For instance, any constraints with a singl... | [
"def",
"preProcess",
"(",
"self",
",",
"variables",
",",
"domains",
",",
"constraints",
",",
"vconstraints",
")",
":",
"if",
"len",
"(",
"variables",
")",
"==",
"1",
":",
"variable",
"=",
"variables",
"[",
"0",
"]",
"domain",
"=",
"domains",
"[",
"vari... | Preprocess variable domains
This method is called before starting to look for solutions,
and is used to prune domains with specific constraint logic
when possible. For instance, any constraints with a single
variable may be applied on all possible values and removed,
since they ... | [
"Preprocess",
"variable",
"domains"
] | e23fe9852cddddf1c3e258e03f2175df24b4c702 | https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L849-L878 |
6,320 | python-constraint/python-constraint | constraint/__init__.py | Constraint.forwardCheck | def forwardCheck(self, variables, domains, assignments, _unassigned=Unassigned):
"""
Helper method for generic forward checking
Currently, this method acts only when there's a single
unassigned variable.
@param variables: Variables affected by that constraint, in the
... | python | def forwardCheck(self, variables, domains, assignments, _unassigned=Unassigned):
"""
Helper method for generic forward checking
Currently, this method acts only when there's a single
unassigned variable.
@param variables: Variables affected by that constraint, in the
... | [
"def",
"forwardCheck",
"(",
"self",
",",
"variables",
",",
"domains",
",",
"assignments",
",",
"_unassigned",
"=",
"Unassigned",
")",
":",
"unassignedvariable",
"=",
"_unassigned",
"for",
"variable",
"in",
"variables",
":",
"if",
"variable",
"not",
"in",
"assi... | Helper method for generic forward checking
Currently, this method acts only when there's a single
unassigned variable.
@param variables: Variables affected by that constraint, in the
same order provided by the user
@type variables: sequence
@param dom... | [
"Helper",
"method",
"for",
"generic",
"forward",
"checking"
] | e23fe9852cddddf1c3e258e03f2175df24b4c702 | https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L880-L919 |
6,321 | kencochrane/django-defender | defender/views.py | block_view | def block_view(request):
""" List the blocked IP and Usernames """
blocked_ip_list = get_blocked_ips()
blocked_username_list = get_blocked_usernames()
context = {'blocked_ip_list': blocked_ip_list,
'blocked_username_list': blocked_username_list}
return render(request, 'defender/admin... | python | def block_view(request):
""" List the blocked IP and Usernames """
blocked_ip_list = get_blocked_ips()
blocked_username_list = get_blocked_usernames()
context = {'blocked_ip_list': blocked_ip_list,
'blocked_username_list': blocked_username_list}
return render(request, 'defender/admin... | [
"def",
"block_view",
"(",
"request",
")",
":",
"blocked_ip_list",
"=",
"get_blocked_ips",
"(",
")",
"blocked_username_list",
"=",
"get_blocked_usernames",
"(",
")",
"context",
"=",
"{",
"'blocked_ip_list'",
":",
"blocked_ip_list",
",",
"'blocked_username_list'",
":",
... | List the blocked IP and Usernames | [
"List",
"the",
"blocked",
"IP",
"and",
"Usernames"
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/views.py#L14-L21 |
6,322 | kencochrane/django-defender | defender/utils.py | get_ip | def get_ip(request):
""" get the ip address from the request """
if config.BEHIND_REVERSE_PROXY:
ip_address = request.META.get(config.REVERSE_PROXY_HEADER, '')
ip_address = ip_address.split(",", 1)[0].strip()
if ip_address == '':
ip_address = get_ip_address_from_request(reque... | python | def get_ip(request):
""" get the ip address from the request """
if config.BEHIND_REVERSE_PROXY:
ip_address = request.META.get(config.REVERSE_PROXY_HEADER, '')
ip_address = ip_address.split(",", 1)[0].strip()
if ip_address == '':
ip_address = get_ip_address_from_request(reque... | [
"def",
"get_ip",
"(",
"request",
")",
":",
"if",
"config",
".",
"BEHIND_REVERSE_PROXY",
":",
"ip_address",
"=",
"request",
".",
"META",
".",
"get",
"(",
"config",
".",
"REVERSE_PROXY_HEADER",
",",
"''",
")",
"ip_address",
"=",
"ip_address",
".",
"split",
"... | get the ip address from the request | [
"get",
"the",
"ip",
"address",
"from",
"the",
"request"
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L41-L50 |
6,323 | kencochrane/django-defender | defender/utils.py | get_blocked_ips | def get_blocked_ips():
""" get a list of blocked ips from redis """
if config.DISABLE_IP_LOCKOUT:
# There are no blocked IP's since we disabled them.
return []
key = get_ip_blocked_cache_key("*")
key_list = [redis_key.decode('utf-8')
for redis_key in REDIS_SERVER.keys(key... | python | def get_blocked_ips():
""" get a list of blocked ips from redis """
if config.DISABLE_IP_LOCKOUT:
# There are no blocked IP's since we disabled them.
return []
key = get_ip_blocked_cache_key("*")
key_list = [redis_key.decode('utf-8')
for redis_key in REDIS_SERVER.keys(key... | [
"def",
"get_blocked_ips",
"(",
")",
":",
"if",
"config",
".",
"DISABLE_IP_LOCKOUT",
":",
"# There are no blocked IP's since we disabled them.",
"return",
"[",
"]",
"key",
"=",
"get_ip_blocked_cache_key",
"(",
"\"*\"",
")",
"key_list",
"=",
"[",
"redis_key",
".",
"de... | get a list of blocked ips from redis | [
"get",
"a",
"list",
"of",
"blocked",
"ips",
"from",
"redis"
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L101-L109 |
6,324 | kencochrane/django-defender | defender/utils.py | get_blocked_usernames | def get_blocked_usernames():
""" get a list of blocked usernames from redis """
if config.DISABLE_USERNAME_LOCKOUT:
# There are no blocked usernames since we disabled them.
return []
key = get_username_blocked_cache_key("*")
key_list = [redis_key.decode('utf-8')
for redis... | python | def get_blocked_usernames():
""" get a list of blocked usernames from redis """
if config.DISABLE_USERNAME_LOCKOUT:
# There are no blocked usernames since we disabled them.
return []
key = get_username_blocked_cache_key("*")
key_list = [redis_key.decode('utf-8')
for redis... | [
"def",
"get_blocked_usernames",
"(",
")",
":",
"if",
"config",
".",
"DISABLE_USERNAME_LOCKOUT",
":",
"# There are no blocked usernames since we disabled them.",
"return",
"[",
"]",
"key",
"=",
"get_username_blocked_cache_key",
"(",
"\"*\"",
")",
"key_list",
"=",
"[",
"r... | get a list of blocked usernames from redis | [
"get",
"a",
"list",
"of",
"blocked",
"usernames",
"from",
"redis"
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L112-L120 |
6,325 | kencochrane/django-defender | defender/utils.py | increment_key | def increment_key(key):
""" given a key increment the value """
pipe = REDIS_SERVER.pipeline()
pipe.incr(key, 1)
if config.COOLOFF_TIME:
pipe.expire(key, config.COOLOFF_TIME)
new_value = pipe.execute()[0]
return new_value | python | def increment_key(key):
""" given a key increment the value """
pipe = REDIS_SERVER.pipeline()
pipe.incr(key, 1)
if config.COOLOFF_TIME:
pipe.expire(key, config.COOLOFF_TIME)
new_value = pipe.execute()[0]
return new_value | [
"def",
"increment_key",
"(",
"key",
")",
":",
"pipe",
"=",
"REDIS_SERVER",
".",
"pipeline",
"(",
")",
"pipe",
".",
"incr",
"(",
"key",
",",
"1",
")",
"if",
"config",
".",
"COOLOFF_TIME",
":",
"pipe",
".",
"expire",
"(",
"key",
",",
"config",
".",
"... | given a key increment the value | [
"given",
"a",
"key",
"increment",
"the",
"value"
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L123-L130 |
6,326 | kencochrane/django-defender | defender/utils.py | username_from_request | def username_from_request(request):
""" unloads username from default POST request """
if config.USERNAME_FORM_FIELD in request.POST:
return request.POST[config.USERNAME_FORM_FIELD][:255]
return None | python | def username_from_request(request):
""" unloads username from default POST request """
if config.USERNAME_FORM_FIELD in request.POST:
return request.POST[config.USERNAME_FORM_FIELD][:255]
return None | [
"def",
"username_from_request",
"(",
"request",
")",
":",
"if",
"config",
".",
"USERNAME_FORM_FIELD",
"in",
"request",
".",
"POST",
":",
"return",
"request",
".",
"POST",
"[",
"config",
".",
"USERNAME_FORM_FIELD",
"]",
"[",
":",
"255",
"]",
"return",
"None"
... | unloads username from default POST request | [
"unloads",
"username",
"from",
"default",
"POST",
"request"
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L133-L137 |
6,327 | kencochrane/django-defender | defender/utils.py | get_user_attempts | def get_user_attempts(request, get_username=get_username_from_request, username=None):
""" Returns number of access attempts for this ip, username
"""
ip_address = get_ip(request)
username = lower_username(username or get_username(request))
# get by IP
ip_count = REDIS_SERVER.get(get_ip_attemp... | python | def get_user_attempts(request, get_username=get_username_from_request, username=None):
""" Returns number of access attempts for this ip, username
"""
ip_address = get_ip(request)
username = lower_username(username or get_username(request))
# get by IP
ip_count = REDIS_SERVER.get(get_ip_attemp... | [
"def",
"get_user_attempts",
"(",
"request",
",",
"get_username",
"=",
"get_username_from_request",
",",
"username",
"=",
"None",
")",
":",
"ip_address",
"=",
"get_ip",
"(",
"request",
")",
"username",
"=",
"lower_username",
"(",
"username",
"or",
"get_username",
... | Returns number of access attempts for this ip, username | [
"Returns",
"number",
"of",
"access",
"attempts",
"for",
"this",
"ip",
"username"
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L145-L165 |
6,328 | kencochrane/django-defender | defender/utils.py | block_ip | def block_ip(ip_address):
""" given the ip, block it """
if not ip_address:
# no reason to continue when there is no ip
return
if config.DISABLE_IP_LOCKOUT:
# no need to block, we disabled it.
return
key = get_ip_blocked_cache_key(ip_address)
if config.COOLOFF_TIME:
... | python | def block_ip(ip_address):
""" given the ip, block it """
if not ip_address:
# no reason to continue when there is no ip
return
if config.DISABLE_IP_LOCKOUT:
# no need to block, we disabled it.
return
key = get_ip_blocked_cache_key(ip_address)
if config.COOLOFF_TIME:
... | [
"def",
"block_ip",
"(",
"ip_address",
")",
":",
"if",
"not",
"ip_address",
":",
"# no reason to continue when there is no ip",
"return",
"if",
"config",
".",
"DISABLE_IP_LOCKOUT",
":",
"# no need to block, we disabled it.",
"return",
"key",
"=",
"get_ip_blocked_cache_key",
... | given the ip, block it | [
"given",
"the",
"ip",
"block",
"it"
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L168-L181 |
6,329 | kencochrane/django-defender | defender/utils.py | block_username | def block_username(username):
""" given the username block it. """
if not username:
# no reason to continue when there is no username
return
if config.DISABLE_USERNAME_LOCKOUT:
# no need to block, we disabled it.
return
key = get_username_blocked_cache_key(username)
i... | python | def block_username(username):
""" given the username block it. """
if not username:
# no reason to continue when there is no username
return
if config.DISABLE_USERNAME_LOCKOUT:
# no need to block, we disabled it.
return
key = get_username_blocked_cache_key(username)
i... | [
"def",
"block_username",
"(",
"username",
")",
":",
"if",
"not",
"username",
":",
"# no reason to continue when there is no username",
"return",
"if",
"config",
".",
"DISABLE_USERNAME_LOCKOUT",
":",
"# no need to block, we disabled it.",
"return",
"key",
"=",
"get_username_... | given the username block it. | [
"given",
"the",
"username",
"block",
"it",
"."
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L184-L197 |
6,330 | kencochrane/django-defender | defender/utils.py | record_failed_attempt | def record_failed_attempt(ip_address, username):
""" record the failed login attempt, if over limit return False,
if not over limit return True """
# increment the failed count, and get current number
ip_block = False
if not config.DISABLE_IP_LOCKOUT:
# we only want to increment the IP if th... | python | def record_failed_attempt(ip_address, username):
""" record the failed login attempt, if over limit return False,
if not over limit return True """
# increment the failed count, and get current number
ip_block = False
if not config.DISABLE_IP_LOCKOUT:
# we only want to increment the IP if th... | [
"def",
"record_failed_attempt",
"(",
"ip_address",
",",
"username",
")",
":",
"# increment the failed count, and get current number",
"ip_block",
"=",
"False",
"if",
"not",
"config",
".",
"DISABLE_IP_LOCKOUT",
":",
"# we only want to increment the IP if this is disabled.",
"ip_... | record the failed login attempt, if over limit return False,
if not over limit return True | [
"record",
"the",
"failed",
"login",
"attempt",
"if",
"over",
"limit",
"return",
"False",
"if",
"not",
"over",
"limit",
"return",
"True"
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L200-L243 |
6,331 | kencochrane/django-defender | defender/utils.py | unblock_ip | def unblock_ip(ip_address, pipe=None):
""" unblock the given IP """
do_commit = False
if not pipe:
pipe = REDIS_SERVER.pipeline()
do_commit = True
if ip_address:
pipe.delete(get_ip_attempt_cache_key(ip_address))
pipe.delete(get_ip_blocked_cache_key(ip_address))
if... | python | def unblock_ip(ip_address, pipe=None):
""" unblock the given IP """
do_commit = False
if not pipe:
pipe = REDIS_SERVER.pipeline()
do_commit = True
if ip_address:
pipe.delete(get_ip_attempt_cache_key(ip_address))
pipe.delete(get_ip_blocked_cache_key(ip_address))
if... | [
"def",
"unblock_ip",
"(",
"ip_address",
",",
"pipe",
"=",
"None",
")",
":",
"do_commit",
"=",
"False",
"if",
"not",
"pipe",
":",
"pipe",
"=",
"REDIS_SERVER",
".",
"pipeline",
"(",
")",
"do_commit",
"=",
"True",
"if",
"ip_address",
":",
"pipe",
".",
"de... | unblock the given IP | [
"unblock",
"the",
"given",
"IP"
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L246-L256 |
6,332 | kencochrane/django-defender | defender/utils.py | unblock_username | def unblock_username(username, pipe=None):
""" unblock the given Username """
do_commit = False
if not pipe:
pipe = REDIS_SERVER.pipeline()
do_commit = True
if username:
pipe.delete(get_username_attempt_cache_key(username))
pipe.delete(get_username_blocked_cache_key(usern... | python | def unblock_username(username, pipe=None):
""" unblock the given Username """
do_commit = False
if not pipe:
pipe = REDIS_SERVER.pipeline()
do_commit = True
if username:
pipe.delete(get_username_attempt_cache_key(username))
pipe.delete(get_username_blocked_cache_key(usern... | [
"def",
"unblock_username",
"(",
"username",
",",
"pipe",
"=",
"None",
")",
":",
"do_commit",
"=",
"False",
"if",
"not",
"pipe",
":",
"pipe",
"=",
"REDIS_SERVER",
".",
"pipeline",
"(",
")",
"do_commit",
"=",
"True",
"if",
"username",
":",
"pipe",
".",
"... | unblock the given Username | [
"unblock",
"the",
"given",
"Username"
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L259-L269 |
6,333 | kencochrane/django-defender | defender/utils.py | reset_failed_attempts | def reset_failed_attempts(ip_address=None, username=None):
""" reset the failed attempts for these ip's and usernames
"""
pipe = REDIS_SERVER.pipeline()
unblock_ip(ip_address, pipe=pipe)
unblock_username(username, pipe=pipe)
pipe.execute() | python | def reset_failed_attempts(ip_address=None, username=None):
""" reset the failed attempts for these ip's and usernames
"""
pipe = REDIS_SERVER.pipeline()
unblock_ip(ip_address, pipe=pipe)
unblock_username(username, pipe=pipe)
pipe.execute() | [
"def",
"reset_failed_attempts",
"(",
"ip_address",
"=",
"None",
",",
"username",
"=",
"None",
")",
":",
"pipe",
"=",
"REDIS_SERVER",
".",
"pipeline",
"(",
")",
"unblock_ip",
"(",
"ip_address",
",",
"pipe",
"=",
"pipe",
")",
"unblock_username",
"(",
"username... | reset the failed attempts for these ip's and usernames | [
"reset",
"the",
"failed",
"attempts",
"for",
"these",
"ip",
"s",
"and",
"usernames"
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L272-L280 |
6,334 | kencochrane/django-defender | defender/utils.py | lockout_response | def lockout_response(request):
""" if we are locked out, here is the response """
if config.LOCKOUT_TEMPLATE:
context = {
'cooloff_time_seconds': config.COOLOFF_TIME,
'cooloff_time_minutes': config.COOLOFF_TIME / 60,
'failure_limit': config.FAILURE_LIMIT,
}
... | python | def lockout_response(request):
""" if we are locked out, here is the response """
if config.LOCKOUT_TEMPLATE:
context = {
'cooloff_time_seconds': config.COOLOFF_TIME,
'cooloff_time_minutes': config.COOLOFF_TIME / 60,
'failure_limit': config.FAILURE_LIMIT,
}
... | [
"def",
"lockout_response",
"(",
"request",
")",
":",
"if",
"config",
".",
"LOCKOUT_TEMPLATE",
":",
"context",
"=",
"{",
"'cooloff_time_seconds'",
":",
"config",
".",
"COOLOFF_TIME",
",",
"'cooloff_time_minutes'",
":",
"config",
".",
"COOLOFF_TIME",
"/",
"60",
",... | if we are locked out, here is the response | [
"if",
"we",
"are",
"locked",
"out",
"here",
"is",
"the",
"response"
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L283-L301 |
6,335 | kencochrane/django-defender | defender/utils.py | is_user_already_locked | def is_user_already_locked(username):
"""Is this username already locked?"""
if username is None:
return False
if config.DISABLE_USERNAME_LOCKOUT:
return False
return REDIS_SERVER.get(get_username_blocked_cache_key(username)) | python | def is_user_already_locked(username):
"""Is this username already locked?"""
if username is None:
return False
if config.DISABLE_USERNAME_LOCKOUT:
return False
return REDIS_SERVER.get(get_username_blocked_cache_key(username)) | [
"def",
"is_user_already_locked",
"(",
"username",
")",
":",
"if",
"username",
"is",
"None",
":",
"return",
"False",
"if",
"config",
".",
"DISABLE_USERNAME_LOCKOUT",
":",
"return",
"False",
"return",
"REDIS_SERVER",
".",
"get",
"(",
"get_username_blocked_cache_key",
... | Is this username already locked? | [
"Is",
"this",
"username",
"already",
"locked?"
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L304-L310 |
6,336 | kencochrane/django-defender | defender/utils.py | is_source_ip_already_locked | def is_source_ip_already_locked(ip_address):
"""Is this IP already locked?"""
if ip_address is None:
return False
if config.DISABLE_IP_LOCKOUT:
return False
return REDIS_SERVER.get(get_ip_blocked_cache_key(ip_address)) | python | def is_source_ip_already_locked(ip_address):
"""Is this IP already locked?"""
if ip_address is None:
return False
if config.DISABLE_IP_LOCKOUT:
return False
return REDIS_SERVER.get(get_ip_blocked_cache_key(ip_address)) | [
"def",
"is_source_ip_already_locked",
"(",
"ip_address",
")",
":",
"if",
"ip_address",
"is",
"None",
":",
"return",
"False",
"if",
"config",
".",
"DISABLE_IP_LOCKOUT",
":",
"return",
"False",
"return",
"REDIS_SERVER",
".",
"get",
"(",
"get_ip_blocked_cache_key",
"... | Is this IP already locked? | [
"Is",
"this",
"IP",
"already",
"locked?"
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L313-L319 |
6,337 | kencochrane/django-defender | defender/utils.py | is_already_locked | def is_already_locked(request, get_username=get_username_from_request, username=None):
"""Parse the username & IP from the request, and see if it's
already locked."""
user_blocked = is_user_already_locked(username or get_username(request))
ip_blocked = is_source_ip_already_locked(get_ip(request))
i... | python | def is_already_locked(request, get_username=get_username_from_request, username=None):
"""Parse the username & IP from the request, and see if it's
already locked."""
user_blocked = is_user_already_locked(username or get_username(request))
ip_blocked = is_source_ip_already_locked(get_ip(request))
i... | [
"def",
"is_already_locked",
"(",
"request",
",",
"get_username",
"=",
"get_username_from_request",
",",
"username",
"=",
"None",
")",
":",
"user_blocked",
"=",
"is_user_already_locked",
"(",
"username",
"or",
"get_username",
"(",
"request",
")",
")",
"ip_blocked",
... | Parse the username & IP from the request, and see if it's
already locked. | [
"Parse",
"the",
"username",
"&",
"IP",
"from",
"the",
"request",
"and",
"see",
"if",
"it",
"s",
"already",
"locked",
"."
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L322-L332 |
6,338 | kencochrane/django-defender | defender/utils.py | check_request | def check_request(request, login_unsuccessful,
get_username=get_username_from_request,
username=None):
""" check the request, and process results"""
ip_address = get_ip(request)
username = username or get_username(request)
if not login_unsuccessful:
# user lo... | python | def check_request(request, login_unsuccessful,
get_username=get_username_from_request,
username=None):
""" check the request, and process results"""
ip_address = get_ip(request)
username = username or get_username(request)
if not login_unsuccessful:
# user lo... | [
"def",
"check_request",
"(",
"request",
",",
"login_unsuccessful",
",",
"get_username",
"=",
"get_username_from_request",
",",
"username",
"=",
"None",
")",
":",
"ip_address",
"=",
"get_ip",
"(",
"request",
")",
"username",
"=",
"username",
"or",
"get_username",
... | check the request, and process results | [
"check",
"the",
"request",
"and",
"process",
"results"
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L335-L348 |
6,339 | kencochrane/django-defender | defender/utils.py | add_login_attempt_to_db | def add_login_attempt_to_db(request, login_valid,
get_username=get_username_from_request,
username=None):
""" Create a record for the login attempt If using celery call celery
task, if not, call the method normally """
if not config.STORE_ACCESS_ATTEM... | python | def add_login_attempt_to_db(request, login_valid,
get_username=get_username_from_request,
username=None):
""" Create a record for the login attempt If using celery call celery
task, if not, call the method normally """
if not config.STORE_ACCESS_ATTEM... | [
"def",
"add_login_attempt_to_db",
"(",
"request",
",",
"login_valid",
",",
"get_username",
"=",
"get_username_from_request",
",",
"username",
"=",
"None",
")",
":",
"if",
"not",
"config",
".",
"STORE_ACCESS_ATTEMPTS",
":",
"# If we don't want to store in the database, the... | Create a record for the login attempt If using celery call celery
task, if not, call the method normally | [
"Create",
"a",
"record",
"for",
"the",
"login",
"attempt",
"If",
"using",
"celery",
"call",
"celery",
"task",
"if",
"not",
"call",
"the",
"method",
"normally"
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L351-L374 |
6,340 | kencochrane/django-defender | defender/tasks.py | add_login_attempt_task | def add_login_attempt_task(user_agent, ip_address, username,
http_accept, path_info, login_valid):
""" Create a record for the login attempt """
store_login_attempt(user_agent, ip_address, username,
http_accept, path_info, login_valid) | python | def add_login_attempt_task(user_agent, ip_address, username,
http_accept, path_info, login_valid):
""" Create a record for the login attempt """
store_login_attempt(user_agent, ip_address, username,
http_accept, path_info, login_valid) | [
"def",
"add_login_attempt_task",
"(",
"user_agent",
",",
"ip_address",
",",
"username",
",",
"http_accept",
",",
"path_info",
",",
"login_valid",
")",
":",
"store_login_attempt",
"(",
"user_agent",
",",
"ip_address",
",",
"username",
",",
"http_accept",
",",
"path... | Create a record for the login attempt | [
"Create",
"a",
"record",
"for",
"the",
"login",
"attempt"
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/tasks.py#L10-L14 |
6,341 | kencochrane/django-defender | defender/data.py | store_login_attempt | def store_login_attempt(user_agent, ip_address, username,
http_accept, path_info, login_valid):
""" Store the login attempt to the db. """
AccessAttempt.objects.create(
user_agent=user_agent,
ip_address=ip_address,
username=username,
http_accept=http_accep... | python | def store_login_attempt(user_agent, ip_address, username,
http_accept, path_info, login_valid):
""" Store the login attempt to the db. """
AccessAttempt.objects.create(
user_agent=user_agent,
ip_address=ip_address,
username=username,
http_accept=http_accep... | [
"def",
"store_login_attempt",
"(",
"user_agent",
",",
"ip_address",
",",
"username",
",",
"http_accept",
",",
"path_info",
",",
"login_valid",
")",
":",
"AccessAttempt",
".",
"objects",
".",
"create",
"(",
"user_agent",
"=",
"user_agent",
",",
"ip_address",
"=",... | Store the login attempt to the db. | [
"Store",
"the",
"login",
"attempt",
"to",
"the",
"db",
"."
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/data.py#L4-L14 |
6,342 | kencochrane/django-defender | defender/connection.py | get_redis_connection | def get_redis_connection():
""" Get the redis connection if not using mock """
if config.MOCK_REDIS: # pragma: no cover
import mockredis
return mockredis.mock_strict_redis_client() # pragma: no cover
elif config.DEFENDER_REDIS_NAME: # pragma: no cover
try:
cache = cach... | python | def get_redis_connection():
""" Get the redis connection if not using mock """
if config.MOCK_REDIS: # pragma: no cover
import mockredis
return mockredis.mock_strict_redis_client() # pragma: no cover
elif config.DEFENDER_REDIS_NAME: # pragma: no cover
try:
cache = cach... | [
"def",
"get_redis_connection",
"(",
")",
":",
"if",
"config",
".",
"MOCK_REDIS",
":",
"# pragma: no cover",
"import",
"mockredis",
"return",
"mockredis",
".",
"mock_strict_redis_client",
"(",
")",
"# pragma: no cover",
"elif",
"config",
".",
"DEFENDER_REDIS_NAME",
":"... | Get the redis connection if not using mock | [
"Get",
"the",
"redis",
"connection",
"if",
"not",
"using",
"mock"
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/connection.py#L19-L44 |
6,343 | kencochrane/django-defender | defender/connection.py | parse_redis_url | def parse_redis_url(url):
"""Parses a redis URL."""
# create config with some sane defaults
redis_config = {
"DB": 0,
"PASSWORD": None,
"HOST": "localhost",
"PORT": 6379,
"SSL": False
}
if not url:
return redis_config
url = urlparse.urlparse(url... | python | def parse_redis_url(url):
"""Parses a redis URL."""
# create config with some sane defaults
redis_config = {
"DB": 0,
"PASSWORD": None,
"HOST": "localhost",
"PORT": 6379,
"SSL": False
}
if not url:
return redis_config
url = urlparse.urlparse(url... | [
"def",
"parse_redis_url",
"(",
"url",
")",
":",
"# create config with some sane defaults",
"redis_config",
"=",
"{",
"\"DB\"",
":",
"0",
",",
"\"PASSWORD\"",
":",
"None",
",",
"\"HOST\"",
":",
"\"localhost\"",
",",
"\"PORT\"",
":",
"6379",
",",
"\"SSL\"",
":",
... | Parses a redis URL. | [
"Parses",
"a",
"redis",
"URL",
"."
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/connection.py#L48-L79 |
6,344 | kencochrane/django-defender | defender/management/commands/cleanup_django_defender.py | Command.handle | def handle(self, **options):
"""
Removes any entries in the AccessAttempt that are older
than your DEFENDER_ACCESS_ATTEMPT_EXPIRATION config, default 24 HOURS.
"""
print("Starting clean up of django-defender table")
now = timezone.now()
cleanup_delta = timedelta(h... | python | def handle(self, **options):
"""
Removes any entries in the AccessAttempt that are older
than your DEFENDER_ACCESS_ATTEMPT_EXPIRATION config, default 24 HOURS.
"""
print("Starting clean up of django-defender table")
now = timezone.now()
cleanup_delta = timedelta(h... | [
"def",
"handle",
"(",
"self",
",",
"*",
"*",
"options",
")",
":",
"print",
"(",
"\"Starting clean up of django-defender table\"",
")",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"cleanup_delta",
"=",
"timedelta",
"(",
"hours",
"=",
"config",
".",
"ACCESS_... | Removes any entries in the AccessAttempt that are older
than your DEFENDER_ACCESS_ATTEMPT_EXPIRATION config, default 24 HOURS. | [
"Removes",
"any",
"entries",
"in",
"the",
"AccessAttempt",
"that",
"are",
"older",
"than",
"your",
"DEFENDER_ACCESS_ATTEMPT_EXPIRATION",
"config",
"default",
"24",
"HOURS",
"."
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/management/commands/cleanup_django_defender.py#L15-L35 |
6,345 | Cito/DBUtils | DBUtils/PooledDB.py | PooledDB.connection | def connection(self, shareable=True):
"""Get a steady, cached DB-API 2 connection from the pool.
If shareable is set and the underlying DB-API 2 allows it,
then the connection may be shared with other threads.
"""
if shareable and self._maxshared:
self._lock.acquire... | python | def connection(self, shareable=True):
"""Get a steady, cached DB-API 2 connection from the pool.
If shareable is set and the underlying DB-API 2 allows it,
then the connection may be shared with other threads.
"""
if shareable and self._maxshared:
self._lock.acquire... | [
"def",
"connection",
"(",
"self",
",",
"shareable",
"=",
"True",
")",
":",
"if",
"shareable",
"and",
"self",
".",
"_maxshared",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"while",
"(",
"not",
"self",
".",
"_shared_cache",
"and",
... | Get a steady, cached DB-API 2 connection from the pool.
If shareable is set and the underlying DB-API 2 allows it,
then the connection may be shared with other threads. | [
"Get",
"a",
"steady",
"cached",
"DB",
"-",
"API",
"2",
"connection",
"from",
"the",
"pool",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledDB.py#L277-L334 |
6,346 | Cito/DBUtils | DBUtils/PooledDB.py | PooledDB.unshare | def unshare(self, con):
"""Decrease the share of a connection in the shared cache."""
self._lock.acquire()
try:
con.unshare()
shared = con.shared
if not shared: # connection is idle,
try: # so try to remove it
self._shared... | python | def unshare(self, con):
"""Decrease the share of a connection in the shared cache."""
self._lock.acquire()
try:
con.unshare()
shared = con.shared
if not shared: # connection is idle,
try: # so try to remove it
self._shared... | [
"def",
"unshare",
"(",
"self",
",",
"con",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"con",
".",
"unshare",
"(",
")",
"shared",
"=",
"con",
".",
"shared",
"if",
"not",
"shared",
":",
"# connection is idle,",
"try",
":",
... | Decrease the share of a connection in the shared cache. | [
"Decrease",
"the",
"share",
"of",
"a",
"connection",
"in",
"the",
"shared",
"cache",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledDB.py#L340-L354 |
6,347 | Cito/DBUtils | DBUtils/PooledDB.py | PooledSharedDBConnection.close | def close(self):
"""Close the pooled shared connection."""
# Instead of actually closing the connection,
# unshare it and/or return it to the pool.
if self._con:
self._pool.unshare(self._shared_con)
self._shared_con = self._con = None | python | def close(self):
"""Close the pooled shared connection."""
# Instead of actually closing the connection,
# unshare it and/or return it to the pool.
if self._con:
self._pool.unshare(self._shared_con)
self._shared_con = self._con = None | [
"def",
"close",
"(",
"self",
")",
":",
"# Instead of actually closing the connection,",
"# unshare it and/or return it to the pool.",
"if",
"self",
".",
"_con",
":",
"self",
".",
"_pool",
".",
"unshare",
"(",
"self",
".",
"_shared_con",
")",
"self",
".",
"_shared_co... | Close the pooled shared connection. | [
"Close",
"the",
"pooled",
"shared",
"connection",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledDB.py#L516-L522 |
6,348 | Cito/DBUtils | DBUtils/PersistentDB.py | PersistentDB.steady_connection | def steady_connection(self):
"""Get a steady, non-persistent DB-API 2 connection."""
return connect(
self._creator, self._maxusage, self._setsession,
self._failures, self._ping, self._closeable,
*self._args, **self._kwargs) | python | def steady_connection(self):
"""Get a steady, non-persistent DB-API 2 connection."""
return connect(
self._creator, self._maxusage, self._setsession,
self._failures, self._ping, self._closeable,
*self._args, **self._kwargs) | [
"def",
"steady_connection",
"(",
"self",
")",
":",
"return",
"connect",
"(",
"self",
".",
"_creator",
",",
"self",
".",
"_maxusage",
",",
"self",
".",
"_setsession",
",",
"self",
".",
"_failures",
",",
"self",
".",
"_ping",
",",
"self",
".",
"_closeable"... | Get a steady, non-persistent DB-API 2 connection. | [
"Get",
"a",
"steady",
"non",
"-",
"persistent",
"DB",
"-",
"API",
"2",
"connection",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PersistentDB.py#L201-L206 |
6,349 | Cito/DBUtils | DBUtils/PersistentDB.py | PersistentDB.connection | def connection(self, shareable=False):
"""Get a steady, persistent DB-API 2 connection.
The shareable parameter exists only for compatibility with the
PooledDB connection method. In reality, persistent connections
are of course never shared with other threads.
"""
try:... | python | def connection(self, shareable=False):
"""Get a steady, persistent DB-API 2 connection.
The shareable parameter exists only for compatibility with the
PooledDB connection method. In reality, persistent connections
are of course never shared with other threads.
"""
try:... | [
"def",
"connection",
"(",
"self",
",",
"shareable",
"=",
"False",
")",
":",
"try",
":",
"con",
"=",
"self",
".",
"thread",
".",
"connection",
"except",
"AttributeError",
":",
"con",
"=",
"self",
".",
"steady_connection",
"(",
")",
"if",
"not",
"con",
"... | Get a steady, persistent DB-API 2 connection.
The shareable parameter exists only for compatibility with the
PooledDB connection method. In reality, persistent connections
are of course never shared with other threads. | [
"Get",
"a",
"steady",
"persistent",
"DB",
"-",
"API",
"2",
"connection",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PersistentDB.py#L208-L224 |
6,350 | Cito/DBUtils | DBUtils/PersistentPg.py | PersistentPg.steady_connection | def steady_connection(self):
"""Get a steady, non-persistent PyGreSQL connection."""
return SteadyPgConnection(
self._maxusage, self._setsession, self._closeable,
*self._args, **self._kwargs) | python | def steady_connection(self):
"""Get a steady, non-persistent PyGreSQL connection."""
return SteadyPgConnection(
self._maxusage, self._setsession, self._closeable,
*self._args, **self._kwargs) | [
"def",
"steady_connection",
"(",
"self",
")",
":",
"return",
"SteadyPgConnection",
"(",
"self",
".",
"_maxusage",
",",
"self",
".",
"_setsession",
",",
"self",
".",
"_closeable",
",",
"*",
"self",
".",
"_args",
",",
"*",
"*",
"self",
".",
"_kwargs",
")"
... | Get a steady, non-persistent PyGreSQL connection. | [
"Get",
"a",
"steady",
"non",
"-",
"persistent",
"PyGreSQL",
"connection",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PersistentPg.py#L160-L164 |
6,351 | Cito/DBUtils | DBUtils/PersistentPg.py | PersistentPg.connection | def connection(self):
"""Get a steady, persistent PyGreSQL connection."""
try:
con = self.thread.connection
except AttributeError:
con = self.steady_connection()
self.thread.connection = con
return con | python | def connection(self):
"""Get a steady, persistent PyGreSQL connection."""
try:
con = self.thread.connection
except AttributeError:
con = self.steady_connection()
self.thread.connection = con
return con | [
"def",
"connection",
"(",
"self",
")",
":",
"try",
":",
"con",
"=",
"self",
".",
"thread",
".",
"connection",
"except",
"AttributeError",
":",
"con",
"=",
"self",
".",
"steady_connection",
"(",
")",
"self",
".",
"thread",
".",
"connection",
"=",
"con",
... | Get a steady, persistent PyGreSQL connection. | [
"Get",
"a",
"steady",
"persistent",
"PyGreSQL",
"connection",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PersistentPg.py#L166-L173 |
6,352 | Cito/DBUtils | setversion.py | versionString | def versionString(version):
"""Create version string.
For a sequence containing version information such as (2, 0, 0, 'pre'),
this returns a printable string such as '2.0pre'.
The micro version number is only excluded from the string if it is zero.
"""
ver = list(map(str, version))
numbers... | python | def versionString(version):
"""Create version string.
For a sequence containing version information such as (2, 0, 0, 'pre'),
this returns a printable string such as '2.0pre'.
The micro version number is only excluded from the string if it is zero.
"""
ver = list(map(str, version))
numbers... | [
"def",
"versionString",
"(",
"version",
")",
":",
"ver",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"version",
")",
")",
"numbers",
",",
"rest",
"=",
"ver",
"[",
":",
"2",
"if",
"ver",
"[",
"2",
"]",
"==",
"'0'",
"else",
"3",
"]",
",",
"ver",
... | Create version string.
For a sequence containing version information such as (2, 0, 0, 'pre'),
this returns a printable string such as '2.0pre'.
The micro version number is only excluded from the string if it is zero. | [
"Create",
"version",
"string",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/setversion.py#L37-L47 |
6,353 | Cito/DBUtils | DBUtils/PooledPg.py | PooledPg.steady_connection | def steady_connection(self):
"""Get a steady, unpooled PostgreSQL connection."""
return SteadyPgConnection(self._maxusage, self._setsession, True,
*self._args, **self._kwargs) | python | def steady_connection(self):
"""Get a steady, unpooled PostgreSQL connection."""
return SteadyPgConnection(self._maxusage, self._setsession, True,
*self._args, **self._kwargs) | [
"def",
"steady_connection",
"(",
"self",
")",
":",
"return",
"SteadyPgConnection",
"(",
"self",
".",
"_maxusage",
",",
"self",
".",
"_setsession",
",",
"True",
",",
"*",
"self",
".",
"_args",
",",
"*",
"*",
"self",
".",
"_kwargs",
")"
] | Get a steady, unpooled PostgreSQL connection. | [
"Get",
"a",
"steady",
"unpooled",
"PostgreSQL",
"connection",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledPg.py#L200-L203 |
6,354 | Cito/DBUtils | DBUtils/PooledPg.py | PooledPg.connection | def connection(self):
"""Get a steady, cached PostgreSQL connection from the pool."""
if self._connections:
if not self._connections.acquire(self._blocking):
raise TooManyConnections
try:
con = self._cache.get(0)
except Empty:
con = sel... | python | def connection(self):
"""Get a steady, cached PostgreSQL connection from the pool."""
if self._connections:
if not self._connections.acquire(self._blocking):
raise TooManyConnections
try:
con = self._cache.get(0)
except Empty:
con = sel... | [
"def",
"connection",
"(",
"self",
")",
":",
"if",
"self",
".",
"_connections",
":",
"if",
"not",
"self",
".",
"_connections",
".",
"acquire",
"(",
"self",
".",
"_blocking",
")",
":",
"raise",
"TooManyConnections",
"try",
":",
"con",
"=",
"self",
".",
"... | Get a steady, cached PostgreSQL connection from the pool. | [
"Get",
"a",
"steady",
"cached",
"PostgreSQL",
"connection",
"from",
"the",
"pool",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledPg.py#L205-L214 |
6,355 | Cito/DBUtils | DBUtils/PooledPg.py | PooledPg.cache | def cache(self, con):
"""Put a connection back into the pool cache."""
try:
if self._reset == 2:
con.reset() # reset the connection completely
else:
if self._reset or con._transaction:
try:
con.rollback(... | python | def cache(self, con):
"""Put a connection back into the pool cache."""
try:
if self._reset == 2:
con.reset() # reset the connection completely
else:
if self._reset or con._transaction:
try:
con.rollback(... | [
"def",
"cache",
"(",
"self",
",",
"con",
")",
":",
"try",
":",
"if",
"self",
".",
"_reset",
"==",
"2",
":",
"con",
".",
"reset",
"(",
")",
"# reset the connection completely",
"else",
":",
"if",
"self",
".",
"_reset",
"or",
"con",
".",
"_transaction",
... | Put a connection back into the pool cache. | [
"Put",
"a",
"connection",
"back",
"into",
"the",
"pool",
"cache",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledPg.py#L216-L231 |
6,356 | Cito/DBUtils | DBUtils/PooledPg.py | PooledPgConnection.reopen | def reopen(self):
"""Reopen the pooled connection."""
# If the connection is already back in the pool,
# get another connection from the pool,
# otherwise reopen the underlying connection.
if self._con:
self._con.reopen()
else:
self._con = self._po... | python | def reopen(self):
"""Reopen the pooled connection."""
# If the connection is already back in the pool,
# get another connection from the pool,
# otherwise reopen the underlying connection.
if self._con:
self._con.reopen()
else:
self._con = self._po... | [
"def",
"reopen",
"(",
"self",
")",
":",
"# If the connection is already back in the pool,",
"# get another connection from the pool,",
"# otherwise reopen the underlying connection.",
"if",
"self",
".",
"_con",
":",
"self",
".",
"_con",
".",
"reopen",
"(",
")",
"else",
":... | Reopen the pooled connection. | [
"Reopen",
"the",
"pooled",
"connection",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledPg.py#L278-L286 |
6,357 | Cito/DBUtils | DBUtils/SteadyPg.py | SteadyPgConnection.reopen | def reopen(self):
"""Reopen the tough connection.
It will not complain if the connection cannot be reopened.
"""
try:
self._con.reopen()
except Exception:
if self._transcation:
self._transaction = False
try:
... | python | def reopen(self):
"""Reopen the tough connection.
It will not complain if the connection cannot be reopened.
"""
try:
self._con.reopen()
except Exception:
if self._transcation:
self._transaction = False
try:
... | [
"def",
"reopen",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_con",
".",
"reopen",
"(",
")",
"except",
"Exception",
":",
"if",
"self",
".",
"_transcation",
":",
"self",
".",
"_transaction",
"=",
"False",
"try",
":",
"self",
".",
"_con",
".",
"... | Reopen the tough connection.
It will not complain if the connection cannot be reopened. | [
"Reopen",
"the",
"tough",
"connection",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyPg.py#L188-L207 |
6,358 | Cito/DBUtils | DBUtils/SteadyPg.py | SteadyPgConnection.reset | def reset(self):
"""Reset the tough connection.
If a reset is not possible, tries to reopen the connection.
It will not complain if the connection is already closed.
"""
try:
self._con.reset()
self._transaction = False
self._setsession()
... | python | def reset(self):
"""Reset the tough connection.
If a reset is not possible, tries to reopen the connection.
It will not complain if the connection is already closed.
"""
try:
self._con.reset()
self._transaction = False
self._setsession()
... | [
"def",
"reset",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_con",
".",
"reset",
"(",
")",
"self",
".",
"_transaction",
"=",
"False",
"self",
".",
"_setsession",
"(",
")",
"self",
".",
"_usage",
"=",
"0",
"except",
"Exception",
":",
"try",
":"... | Reset the tough connection.
If a reset is not possible, tries to reopen the connection.
It will not complain if the connection is already closed. | [
"Reset",
"the",
"tough",
"connection",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyPg.py#L209-L228 |
6,359 | Cito/DBUtils | DBUtils/SteadyPg.py | SteadyPgConnection._get_tough_method | def _get_tough_method(self, method):
"""Return a "tough" version of a connection class method.
The tough version checks whether the connection is bad (lost)
and automatically and transparently tries to reset the connection
if this is the case (for instance, the database has been restart... | python | def _get_tough_method(self, method):
"""Return a "tough" version of a connection class method.
The tough version checks whether the connection is bad (lost)
and automatically and transparently tries to reset the connection
if this is the case (for instance, the database has been restart... | [
"def",
"_get_tough_method",
"(",
"self",
",",
"method",
")",
":",
"def",
"tough_method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"transaction",
"=",
"self",
".",
"_transaction",
"if",
"not",
"transaction",
":",
"try",
":",
"# check whether con... | Return a "tough" version of a connection class method.
The tough version checks whether the connection is bad (lost)
and automatically and transparently tries to reset the connection
if this is the case (for instance, the database has been restarted). | [
"Return",
"a",
"tough",
"version",
"of",
"a",
"connection",
"class",
"method",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyPg.py#L283-L315 |
6,360 | Cito/DBUtils | DBUtils/SteadyDB.py | connect | def connect(
creator, maxusage=None, setsession=None,
failures=None, ping=1, closeable=True, *args, **kwargs):
"""A tough version of the connection constructor of a DB-API 2 module.
creator: either an arbitrary function returning new DB-API 2 compliant
connection objects or a DB-API 2 c... | python | def connect(
creator, maxusage=None, setsession=None,
failures=None, ping=1, closeable=True, *args, **kwargs):
"""A tough version of the connection constructor of a DB-API 2 module.
creator: either an arbitrary function returning new DB-API 2 compliant
connection objects or a DB-API 2 c... | [
"def",
"connect",
"(",
"creator",
",",
"maxusage",
"=",
"None",
",",
"setsession",
"=",
"None",
",",
"failures",
"=",
"None",
",",
"ping",
"=",
"1",
",",
"closeable",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Stea... | A tough version of the connection constructor of a DB-API 2 module.
creator: either an arbitrary function returning new DB-API 2 compliant
connection objects or a DB-API 2 compliant database module
maxusage: maximum usage limit for the underlying DB-API 2 connection
(number of database operatio... | [
"A",
"tough",
"version",
"of",
"the",
"connection",
"constructor",
"of",
"a",
"DB",
"-",
"API",
"2",
"module",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L111-L139 |
6,361 | Cito/DBUtils | DBUtils/SteadyDB.py | SteadyDBConnection._create | def _create(self):
"""Create a new connection using the creator function."""
con = self._creator(*self._args, **self._kwargs)
try:
try:
if self._dbapi.connect != self._creator:
raise AttributeError
except AttributeError:
... | python | def _create(self):
"""Create a new connection using the creator function."""
con = self._creator(*self._args, **self._kwargs)
try:
try:
if self._dbapi.connect != self._creator:
raise AttributeError
except AttributeError:
... | [
"def",
"_create",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"_creator",
"(",
"*",
"self",
".",
"_args",
",",
"*",
"*",
"self",
".",
"_kwargs",
")",
"try",
":",
"try",
":",
"if",
"self",
".",
"_dbapi",
".",
"connect",
"!=",
"self",
".",
"_... | Create a new connection using the creator function. | [
"Create",
"a",
"new",
"connection",
"using",
"the",
"creator",
"function",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L209-L296 |
6,362 | Cito/DBUtils | DBUtils/SteadyDB.py | SteadyDBConnection._store | def _store(self, con):
"""Store a database connection for subsequent use."""
self._con = con
self._transaction = False
self._closed = False
self._usage = 0 | python | def _store(self, con):
"""Store a database connection for subsequent use."""
self._con = con
self._transaction = False
self._closed = False
self._usage = 0 | [
"def",
"_store",
"(",
"self",
",",
"con",
")",
":",
"self",
".",
"_con",
"=",
"con",
"self",
".",
"_transaction",
"=",
"False",
"self",
".",
"_closed",
"=",
"False",
"self",
".",
"_usage",
"=",
"0"
] | Store a database connection for subsequent use. | [
"Store",
"a",
"database",
"connection",
"for",
"subsequent",
"use",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L308-L313 |
6,363 | Cito/DBUtils | DBUtils/SteadyDB.py | SteadyDBConnection._reset | def _reset(self, force=False):
"""Reset a tough connection.
Rollback if forced or the connection was in a transaction.
"""
if not self._closed and (force or self._transaction):
try:
self.rollback()
except Exception:
pass | python | def _reset(self, force=False):
"""Reset a tough connection.
Rollback if forced or the connection was in a transaction.
"""
if not self._closed and (force or self._transaction):
try:
self.rollback()
except Exception:
pass | [
"def",
"_reset",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"_closed",
"and",
"(",
"force",
"or",
"self",
".",
"_transaction",
")",
":",
"try",
":",
"self",
".",
"rollback",
"(",
")",
"except",
"Exception",
":",
"p... | Reset a tough connection.
Rollback if forced or the connection was in a transaction. | [
"Reset",
"a",
"tough",
"connection",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L330-L340 |
6,364 | Cito/DBUtils | DBUtils/SteadyDB.py | SteadyDBConnection.begin | def begin(self, *args, **kwargs):
"""Indicate the beginning of a transaction.
During a transaction, connections won't be transparently
replaced, and all errors will be raised to the application.
If the underlying driver supports this method, it will be called
with the given par... | python | def begin(self, *args, **kwargs):
"""Indicate the beginning of a transaction.
During a transaction, connections won't be transparently
replaced, and all errors will be raised to the application.
If the underlying driver supports this method, it will be called
with the given par... | [
"def",
"begin",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_transaction",
"=",
"True",
"try",
":",
"begin",
"=",
"self",
".",
"_con",
".",
"begin",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"begin",
... | Indicate the beginning of a transaction.
During a transaction, connections won't be transparently
replaced, and all errors will be raised to the application.
If the underlying driver supports this method, it will be called
with the given parameters (e.g. for distributed transactions). | [
"Indicate",
"the",
"beginning",
"of",
"a",
"transaction",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L409-L425 |
6,365 | Cito/DBUtils | DBUtils/SteadyDB.py | SteadyDBConnection.commit | def commit(self):
"""Commit any pending transaction."""
self._transaction = False
try:
self._con.commit()
except self._failures as error: # cannot commit
try: # try to reopen the connection
con = self._create()
except Exception:
... | python | def commit(self):
"""Commit any pending transaction."""
self._transaction = False
try:
self._con.commit()
except self._failures as error: # cannot commit
try: # try to reopen the connection
con = self._create()
except Exception:
... | [
"def",
"commit",
"(",
"self",
")",
":",
"self",
".",
"_transaction",
"=",
"False",
"try",
":",
"self",
".",
"_con",
".",
"commit",
"(",
")",
"except",
"self",
".",
"_failures",
"as",
"error",
":",
"# cannot commit",
"try",
":",
"# try to reopen the connect... | Commit any pending transaction. | [
"Commit",
"any",
"pending",
"transaction",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L427-L440 |
6,366 | Cito/DBUtils | DBUtils/SteadyDB.py | SteadyDBConnection.cancel | def cancel(self):
"""Cancel a long-running transaction.
If the underlying driver supports this method, it will be called.
"""
self._transaction = False
try:
cancel = self._con.cancel
except AttributeError:
pass
else:
cancel() | python | def cancel(self):
"""Cancel a long-running transaction.
If the underlying driver supports this method, it will be called.
"""
self._transaction = False
try:
cancel = self._con.cancel
except AttributeError:
pass
else:
cancel() | [
"def",
"cancel",
"(",
"self",
")",
":",
"self",
".",
"_transaction",
"=",
"False",
"try",
":",
"cancel",
"=",
"self",
".",
"_con",
".",
"cancel",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"cancel",
"(",
")"
] | Cancel a long-running transaction.
If the underlying driver supports this method, it will be called. | [
"Cancel",
"a",
"long",
"-",
"running",
"transaction",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L457-L469 |
6,367 | Cito/DBUtils | DBUtils/SteadyDB.py | SteadyDBCursor._setsizes | def _setsizes(self, cursor=None):
"""Set stored input and output sizes for cursor execution."""
if cursor is None:
cursor = self._cursor
if self._inputsizes:
cursor.setinputsizes(self._inputsizes)
for column, size in self._outputsizes.items():
if colum... | python | def _setsizes(self, cursor=None):
"""Set stored input and output sizes for cursor execution."""
if cursor is None:
cursor = self._cursor
if self._inputsizes:
cursor.setinputsizes(self._inputsizes)
for column, size in self._outputsizes.items():
if colum... | [
"def",
"_setsizes",
"(",
"self",
",",
"cursor",
"=",
"None",
")",
":",
"if",
"cursor",
"is",
"None",
":",
"cursor",
"=",
"self",
".",
"_cursor",
"if",
"self",
".",
"_inputsizes",
":",
"cursor",
".",
"setinputsizes",
"(",
"self",
".",
"_inputsizes",
")"... | Set stored input and output sizes for cursor execution. | [
"Set",
"stored",
"input",
"and",
"output",
"sizes",
"for",
"cursor",
"execution",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L564-L574 |
6,368 | Cito/DBUtils | DBUtils/SteadyDB.py | SteadyDBCursor.close | def close(self):
"""Close the tough cursor.
It will not complain if you close it more than once.
"""
if not self._closed:
try:
self._cursor.close()
except Exception:
pass
self._closed = True | python | def close(self):
"""Close the tough cursor.
It will not complain if you close it more than once.
"""
if not self._closed:
try:
self._cursor.close()
except Exception:
pass
self._closed = True | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_closed",
":",
"try",
":",
"self",
".",
"_cursor",
".",
"close",
"(",
")",
"except",
"Exception",
":",
"pass",
"self",
".",
"_closed",
"=",
"True"
] | Close the tough cursor.
It will not complain if you close it more than once. | [
"Close",
"the",
"tough",
"cursor",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L576-L587 |
6,369 | Cito/DBUtils | DBUtils/SteadyDB.py | SteadyDBCursor._get_tough_method | def _get_tough_method(self, name):
"""Return a "tough" version of the given cursor method."""
def tough_method(*args, **kwargs):
execute = name.startswith('execute')
con = self._con
transaction = con._transaction
if not transaction:
con._pi... | python | def _get_tough_method(self, name):
"""Return a "tough" version of the given cursor method."""
def tough_method(*args, **kwargs):
execute = name.startswith('execute')
con = self._con
transaction = con._transaction
if not transaction:
con._pi... | [
"def",
"_get_tough_method",
"(",
"self",
",",
"name",
")",
":",
"def",
"tough_method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"execute",
"=",
"name",
".",
"startswith",
"(",
"'execute'",
")",
"con",
"=",
"self",
".",
"_con",
"transaction"... | Return a "tough" version of the given cursor method. | [
"Return",
"a",
"tough",
"version",
"of",
"the",
"given",
"cursor",
"method",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L589-L690 |
6,370 | mcs07/ChemDataExtractor | chemdataextractor/cli/tokenize.py | train_punkt | def train_punkt(ctx, input, output, abbr, colloc):
"""Train Punkt sentence splitter using sentences in input."""
click.echo('chemdataextractor.tokenize.train_punkt')
import pickle
from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktTrainer
punkt = PunktTrainer()
# Set these to true to i... | python | def train_punkt(ctx, input, output, abbr, colloc):
"""Train Punkt sentence splitter using sentences in input."""
click.echo('chemdataextractor.tokenize.train_punkt')
import pickle
from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktTrainer
punkt = PunktTrainer()
# Set these to true to i... | [
"def",
"train_punkt",
"(",
"ctx",
",",
"input",
",",
"output",
",",
"abbr",
",",
"colloc",
")",
":",
"click",
".",
"echo",
"(",
"'chemdataextractor.tokenize.train_punkt'",
")",
"import",
"pickle",
"from",
"nltk",
".",
"tokenize",
".",
"punkt",
"import",
"Pun... | Train Punkt sentence splitter using sentences in input. | [
"Train",
"Punkt",
"sentence",
"splitter",
"using",
"sentences",
"in",
"input",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/tokenize.py#L36-L61 |
6,371 | mcs07/ChemDataExtractor | chemdataextractor/cli/tokenize.py | sentences | def sentences(ctx, input, output):
"""Read input document, and output sentences."""
log.info('chemdataextractor.read.elements')
log.info('Reading %s' % input.name)
doc = Document.from_file(input)
for element in doc.elements:
if isinstance(element, Text):
for raw_sentence in eleme... | python | def sentences(ctx, input, output):
"""Read input document, and output sentences."""
log.info('chemdataextractor.read.elements')
log.info('Reading %s' % input.name)
doc = Document.from_file(input)
for element in doc.elements:
if isinstance(element, Text):
for raw_sentence in eleme... | [
"def",
"sentences",
"(",
"ctx",
",",
"input",
",",
"output",
")",
":",
"log",
".",
"info",
"(",
"'chemdataextractor.read.elements'",
")",
"log",
".",
"info",
"(",
"'Reading %s'",
"%",
"input",
".",
"name",
")",
"doc",
"=",
"Document",
".",
"from_file",
"... | Read input document, and output sentences. | [
"Read",
"input",
"document",
"and",
"output",
"sentences",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/tokenize.py#L68-L77 |
6,372 | mcs07/ChemDataExtractor | chemdataextractor/cli/tokenize.py | words | def words(ctx, input, output):
"""Read input document, and output words."""
log.info('chemdataextractor.read.elements')
log.info('Reading %s' % input.name)
doc = Document.from_file(input)
for element in doc.elements:
if isinstance(element, Text):
for sentence in element.sentences... | python | def words(ctx, input, output):
"""Read input document, and output words."""
log.info('chemdataextractor.read.elements')
log.info('Reading %s' % input.name)
doc = Document.from_file(input)
for element in doc.elements:
if isinstance(element, Text):
for sentence in element.sentences... | [
"def",
"words",
"(",
"ctx",
",",
"input",
",",
"output",
")",
":",
"log",
".",
"info",
"(",
"'chemdataextractor.read.elements'",
")",
"log",
".",
"info",
"(",
"'Reading %s'",
"%",
"input",
".",
"name",
")",
"doc",
"=",
"Document",
".",
"from_file",
"(",
... | Read input document, and output words. | [
"Read",
"input",
"document",
"and",
"output",
"words",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/tokenize.py#L84-L93 |
6,373 | mcs07/ChemDataExtractor | chemdataextractor/nlp/cem.py | CemTagger._in_stoplist | def _in_stoplist(self, entity):
"""Return True if the entity is in the stoplist."""
start = 0
end = len(entity)
# Adjust boundaries to exclude disallowed prefixes/suffixes
for prefix in IGNORE_PREFIX:
if entity.startswith(prefix):
# print('%s removing ... | python | def _in_stoplist(self, entity):
"""Return True if the entity is in the stoplist."""
start = 0
end = len(entity)
# Adjust boundaries to exclude disallowed prefixes/suffixes
for prefix in IGNORE_PREFIX:
if entity.startswith(prefix):
# print('%s removing ... | [
"def",
"_in_stoplist",
"(",
"self",
",",
"entity",
")",
":",
"start",
"=",
"0",
"end",
"=",
"len",
"(",
"entity",
")",
"# Adjust boundaries to exclude disallowed prefixes/suffixes",
"for",
"prefix",
"in",
"IGNORE_PREFIX",
":",
"if",
"entity",
".",
"startswith",
... | Return True if the entity is in the stoplist. | [
"Return",
"True",
"if",
"the",
"entity",
"is",
"in",
"the",
"stoplist",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/cem.py#L518-L544 |
6,374 | mcs07/ChemDataExtractor | chemdataextractor/cli/dict.py | _process_name | def _process_name(name):
"""Fix issues with Jochem names."""
# Unescape HTML entities
name = unescape(name)
# Remove bracketed stuff on the end
name = NG_RE.sub('', name).strip() # Nomenclature groups
name = END_RE.sub('', name).strip(', ') # Words
name = RATIO_RE.sub('', name).strip(', ... | python | def _process_name(name):
"""Fix issues with Jochem names."""
# Unescape HTML entities
name = unescape(name)
# Remove bracketed stuff on the end
name = NG_RE.sub('', name).strip() # Nomenclature groups
name = END_RE.sub('', name).strip(', ') # Words
name = RATIO_RE.sub('', name).strip(', ... | [
"def",
"_process_name",
"(",
"name",
")",
":",
"# Unescape HTML entities",
"name",
"=",
"unescape",
"(",
"name",
")",
"# Remove bracketed stuff on the end",
"name",
"=",
"NG_RE",
".",
"sub",
"(",
"''",
",",
"name",
")",
".",
"strip",
"(",
")",
"# Nomenclature ... | Fix issues with Jochem names. | [
"Fix",
"issues",
"with",
"Jochem",
"names",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/dict.py#L124-L154 |
6,375 | mcs07/ChemDataExtractor | chemdataextractor/cli/dict.py | _get_variants | def _get_variants(name):
"""Return variants of chemical name."""
names = [name]
oldname = name
# Map greek words to unicode characters
if DOT_GREEK_RE.search(name):
wordname = name
while True:
m = DOT_GREEK_RE.search(wordname)
if m:
wordname = ... | python | def _get_variants(name):
"""Return variants of chemical name."""
names = [name]
oldname = name
# Map greek words to unicode characters
if DOT_GREEK_RE.search(name):
wordname = name
while True:
m = DOT_GREEK_RE.search(wordname)
if m:
wordname = ... | [
"def",
"_get_variants",
"(",
"name",
")",
":",
"names",
"=",
"[",
"name",
"]",
"oldname",
"=",
"name",
"# Map greek words to unicode characters",
"if",
"DOT_GREEK_RE",
".",
"search",
"(",
"name",
")",
":",
"wordname",
"=",
"name",
"while",
"True",
":",
"m",
... | Return variants of chemical name. | [
"Return",
"variants",
"of",
"chemical",
"name",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/dict.py#L206-L252 |
6,376 | mcs07/ChemDataExtractor | chemdataextractor/cli/dict.py | prepare_jochem | def prepare_jochem(ctx, jochem, output, csoutput):
"""Process and filter jochem file to produce list of names for dictionary."""
click.echo('chemdataextractor.dict.prepare_jochem')
for i, line in enumerate(jochem):
print('JC%s' % i)
if line.startswith('TM '):
if line.endswith(' @... | python | def prepare_jochem(ctx, jochem, output, csoutput):
"""Process and filter jochem file to produce list of names for dictionary."""
click.echo('chemdataextractor.dict.prepare_jochem')
for i, line in enumerate(jochem):
print('JC%s' % i)
if line.startswith('TM '):
if line.endswith(' @... | [
"def",
"prepare_jochem",
"(",
"ctx",
",",
"jochem",
",",
"output",
",",
"csoutput",
")",
":",
"click",
".",
"echo",
"(",
"'chemdataextractor.dict.prepare_jochem'",
")",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"jochem",
")",
":",
"print",
"(",
"'JC... | Process and filter jochem file to produce list of names for dictionary. | [
"Process",
"and",
"filter",
"jochem",
"file",
"to",
"produce",
"list",
"of",
"names",
"for",
"dictionary",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/dict.py#L277-L290 |
6,377 | mcs07/ChemDataExtractor | chemdataextractor/cli/dict.py | prepare_include | def prepare_include(ctx, include, output):
"""Process and filter include file to produce list of names for dictionary."""
click.echo('chemdataextractor.dict.prepare_include')
for i, line in enumerate(include):
print('IN%s' % i)
for tokens in _make_tokens(line.strip()):
output.wri... | python | def prepare_include(ctx, include, output):
"""Process and filter include file to produce list of names for dictionary."""
click.echo('chemdataextractor.dict.prepare_include')
for i, line in enumerate(include):
print('IN%s' % i)
for tokens in _make_tokens(line.strip()):
output.wri... | [
"def",
"prepare_include",
"(",
"ctx",
",",
"include",
",",
"output",
")",
":",
"click",
".",
"echo",
"(",
"'chemdataextractor.dict.prepare_include'",
")",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"include",
")",
":",
"print",
"(",
"'IN%s'",
"%",
"i... | Process and filter include file to produce list of names for dictionary. | [
"Process",
"and",
"filter",
"include",
"file",
"to",
"produce",
"list",
"of",
"names",
"for",
"dictionary",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/dict.py#L297-L304 |
6,378 | mcs07/ChemDataExtractor | chemdataextractor/cli/dict.py | build | def build(ctx, inputs, output, cs):
"""Build chemical name dictionary."""
click.echo('chemdataextractor.dict.build')
dt = DictionaryTagger(lexicon=ChemLexicon(), case_sensitive=cs)
names = []
for input in inputs:
for line in input:
tokens = line.split()
names.append(t... | python | def build(ctx, inputs, output, cs):
"""Build chemical name dictionary."""
click.echo('chemdataextractor.dict.build')
dt = DictionaryTagger(lexicon=ChemLexicon(), case_sensitive=cs)
names = []
for input in inputs:
for line in input:
tokens = line.split()
names.append(t... | [
"def",
"build",
"(",
"ctx",
",",
"inputs",
",",
"output",
",",
"cs",
")",
":",
"click",
".",
"echo",
"(",
"'chemdataextractor.dict.build'",
")",
"dt",
"=",
"DictionaryTagger",
"(",
"lexicon",
"=",
"ChemLexicon",
"(",
")",
",",
"case_sensitive",
"=",
"cs",
... | Build chemical name dictionary. | [
"Build",
"chemical",
"name",
"dictionary",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/dict.py#L312-L322 |
6,379 | mcs07/ChemDataExtractor | chemdataextractor/reader/rsc.py | RscHtmlReader._parse_table_footnotes | def _parse_table_footnotes(self, fns, refs, specials):
"""Override to account for awkward RSC table footnotes."""
footnotes = []
for fn in fns:
footnote = self._parse_text(fn, refs=refs, specials=specials, element_cls=Footnote)[0]
footnote += Footnote('', id=fn.getpreviou... | python | def _parse_table_footnotes(self, fns, refs, specials):
"""Override to account for awkward RSC table footnotes."""
footnotes = []
for fn in fns:
footnote = self._parse_text(fn, refs=refs, specials=specials, element_cls=Footnote)[0]
footnote += Footnote('', id=fn.getpreviou... | [
"def",
"_parse_table_footnotes",
"(",
"self",
",",
"fns",
",",
"refs",
",",
"specials",
")",
":",
"footnotes",
"=",
"[",
"]",
"for",
"fn",
"in",
"fns",
":",
"footnote",
"=",
"self",
".",
"_parse_text",
"(",
"fn",
",",
"refs",
"=",
"refs",
",",
"speci... | Override to account for awkward RSC table footnotes. | [
"Override",
"to",
"account",
"for",
"awkward",
"RSC",
"table",
"footnotes",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/reader/rsc.py#L44-L51 |
6,380 | mcs07/ChemDataExtractor | scripts/melting_points.py | extract | def extract():
"""Extract melting points from patents."""
Paragraph.parsers = [CompoundParser(), ChemicalLabelParser(), MpParser()]
Table.parsers = []
patents = []
for root, dirs, files in os.walk('../examples/mp/grants'):
for filename in files:
if not filename.endswith('.xml'):
... | python | def extract():
"""Extract melting points from patents."""
Paragraph.parsers = [CompoundParser(), ChemicalLabelParser(), MpParser()]
Table.parsers = []
patents = []
for root, dirs, files in os.walk('../examples/mp/grants'):
for filename in files:
if not filename.endswith('.xml'):
... | [
"def",
"extract",
"(",
")",
":",
"Paragraph",
".",
"parsers",
"=",
"[",
"CompoundParser",
"(",
")",
",",
"ChemicalLabelParser",
"(",
")",
",",
"MpParser",
"(",
")",
"]",
"Table",
".",
"parsers",
"=",
"[",
"]",
"patents",
"=",
"[",
"]",
"for",
"root",... | Extract melting points from patents. | [
"Extract",
"melting",
"points",
"from",
"patents",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/scripts/melting_points.py#L40-L64 |
6,381 | mcs07/ChemDataExtractor | scripts/melting_points.py | make_sdf | def make_sdf():
"""Produce SDF of ChemDataExtractor and Tetko sample melting points."""
# import numpy as np
# my_results_by_inchikey = defaultdict(list)
# result_dir = '../examples/mp/standardized_results'
# fout = open('../examples/mp/sdf/chemdataextractor-melting-points.sdf', 'w')
# writer = ... | python | def make_sdf():
"""Produce SDF of ChemDataExtractor and Tetko sample melting points."""
# import numpy as np
# my_results_by_inchikey = defaultdict(list)
# result_dir = '../examples/mp/standardized_results'
# fout = open('../examples/mp/sdf/chemdataextractor-melting-points.sdf', 'w')
# writer = ... | [
"def",
"make_sdf",
"(",
")",
":",
"# import numpy as np",
"# my_results_by_inchikey = defaultdict(list)",
"# result_dir = '../examples/mp/standardized_results'",
"# fout = open('../examples/mp/sdf/chemdataextractor-melting-points.sdf', 'w')",
"# writer = Chem.SDWriter(fout)",
"# for filename in ... | Produce SDF of ChemDataExtractor and Tetko sample melting points. | [
"Produce",
"SDF",
"of",
"ChemDataExtractor",
"and",
"Tetko",
"sample",
"melting",
"points",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/scripts/melting_points.py#L555-L620 |
6,382 | mcs07/ChemDataExtractor | chemdataextractor/cli/__init__.py | cli | def cli(ctx, verbose):
"""ChemDataExtractor command line interface."""
log.debug('ChemDataExtractor v%s' % __version__)
logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO)
logging.getLogger('requests').setLevel(logging.WARN)
ctx.obj = {} | python | def cli(ctx, verbose):
"""ChemDataExtractor command line interface."""
log.debug('ChemDataExtractor v%s' % __version__)
logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO)
logging.getLogger('requests').setLevel(logging.WARN)
ctx.obj = {} | [
"def",
"cli",
"(",
"ctx",
",",
"verbose",
")",
":",
"log",
".",
"debug",
"(",
"'ChemDataExtractor v%s'",
"%",
"__version__",
")",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
"if",
"verbose",
"else",
"logging",
".",
"INFO",
... | ChemDataExtractor command line interface. | [
"ChemDataExtractor",
"command",
"line",
"interface",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/__init__.py#L34-L39 |
6,383 | mcs07/ChemDataExtractor | chemdataextractor/cli/__init__.py | extract | def extract(ctx, input, output):
"""Run ChemDataExtractor on a document."""
log.info('chemdataextractor.extract')
log.info('Reading %s' % input.name)
doc = Document.from_file(input, fname=input.name)
records = [record.serialize(primitive=True) for record in doc.records]
jsonstring = json.dumps(r... | python | def extract(ctx, input, output):
"""Run ChemDataExtractor on a document."""
log.info('chemdataextractor.extract')
log.info('Reading %s' % input.name)
doc = Document.from_file(input, fname=input.name)
records = [record.serialize(primitive=True) for record in doc.records]
jsonstring = json.dumps(r... | [
"def",
"extract",
"(",
"ctx",
",",
"input",
",",
"output",
")",
":",
"log",
".",
"info",
"(",
"'chemdataextractor.extract'",
")",
"log",
".",
"info",
"(",
"'Reading %s'",
"%",
"input",
".",
"name",
")",
"doc",
"=",
"Document",
".",
"from_file",
"(",
"i... | Run ChemDataExtractor on a document. | [
"Run",
"ChemDataExtractor",
"on",
"a",
"document",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/__init__.py#L46-L53 |
6,384 | mcs07/ChemDataExtractor | chemdataextractor/cli/__init__.py | read | def read(ctx, input, output):
"""Output processed document elements."""
log.info('chemdataextractor.read')
log.info('Reading %s' % input.name)
doc = Document.from_file(input)
for element in doc.elements:
output.write(u'%s : %s\n=====\n' % (element.__class__.__name__, six.text_type(element))) | python | def read(ctx, input, output):
"""Output processed document elements."""
log.info('chemdataextractor.read')
log.info('Reading %s' % input.name)
doc = Document.from_file(input)
for element in doc.elements:
output.write(u'%s : %s\n=====\n' % (element.__class__.__name__, six.text_type(element))) | [
"def",
"read",
"(",
"ctx",
",",
"input",
",",
"output",
")",
":",
"log",
".",
"info",
"(",
"'chemdataextractor.read'",
")",
"log",
".",
"info",
"(",
"'Reading %s'",
"%",
"input",
".",
"name",
")",
"doc",
"=",
"Document",
".",
"from_file",
"(",
"input",... | Output processed document elements. | [
"Output",
"processed",
"document",
"elements",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/__init__.py#L60-L66 |
6,385 | mcs07/ChemDataExtractor | chemdataextractor/text/chem.py | extract_smiles | def extract_smiles(s):
"""Return a list of SMILES identifiers extracted from the string."""
# TODO: This still gets a lot of false positives.
smiles = []
for t in s.split():
if len(t) > 2 and SMILES_RE.match(t) and not t.endswith('.') and bracket_level(t) == 0:
smiles.append(t)
r... | python | def extract_smiles(s):
"""Return a list of SMILES identifiers extracted from the string."""
# TODO: This still gets a lot of false positives.
smiles = []
for t in s.split():
if len(t) > 2 and SMILES_RE.match(t) and not t.endswith('.') and bracket_level(t) == 0:
smiles.append(t)
r... | [
"def",
"extract_smiles",
"(",
"s",
")",
":",
"# TODO: This still gets a lot of false positives.",
"smiles",
"=",
"[",
"]",
"for",
"t",
"in",
"s",
".",
"split",
"(",
")",
":",
"if",
"len",
"(",
"t",
")",
">",
"2",
"and",
"SMILES_RE",
".",
"match",
"(",
... | Return a list of SMILES identifiers extracted from the string. | [
"Return",
"a",
"list",
"of",
"SMILES",
"identifiers",
"extracted",
"from",
"the",
"string",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/text/chem.py#L155-L162 |
6,386 | mcs07/ChemDataExtractor | chemdataextractor/biblio/person.py | PersonName.could_be | def could_be(self, other):
"""Return True if the other PersonName is not explicitly inconsistent."""
# TODO: Some suffix and title differences should be allowed
if type(other) is not type(self):
return NotImplemented
if self == other:
return True
for attr ... | python | def could_be(self, other):
"""Return True if the other PersonName is not explicitly inconsistent."""
# TODO: Some suffix and title differences should be allowed
if type(other) is not type(self):
return NotImplemented
if self == other:
return True
for attr ... | [
"def",
"could_be",
"(",
"self",
",",
"other",
")",
":",
"# TODO: Some suffix and title differences should be allowed",
"if",
"type",
"(",
"other",
")",
"is",
"not",
"type",
"(",
"self",
")",
":",
"return",
"NotImplemented",
"if",
"self",
"==",
"other",
":",
"r... | Return True if the other PersonName is not explicitly inconsistent. | [
"Return",
"True",
"if",
"the",
"other",
"PersonName",
"is",
"not",
"explicitly",
"inconsistent",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/person.py#L125-L145 |
6,387 | mcs07/ChemDataExtractor | chemdataextractor/biblio/person.py | PersonName._is_suffix | def _is_suffix(self, t):
"""Return true if t is a suffix."""
return t not in NOT_SUFFIX and (t.replace('.', '') in SUFFIXES or t.replace('.', '') in SUFFIXES_LOWER) | python | def _is_suffix(self, t):
"""Return true if t is a suffix."""
return t not in NOT_SUFFIX and (t.replace('.', '') in SUFFIXES or t.replace('.', '') in SUFFIXES_LOWER) | [
"def",
"_is_suffix",
"(",
"self",
",",
"t",
")",
":",
"return",
"t",
"not",
"in",
"NOT_SUFFIX",
"and",
"(",
"t",
".",
"replace",
"(",
"'.'",
",",
"''",
")",
"in",
"SUFFIXES",
"or",
"t",
".",
"replace",
"(",
"'.'",
",",
"''",
")",
"in",
"SUFFIXES_... | Return true if t is a suffix. | [
"Return",
"true",
"if",
"t",
"is",
"a",
"suffix",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/person.py#L170-L172 |
6,388 | mcs07/ChemDataExtractor | chemdataextractor/biblio/person.py | PersonName._tokenize | def _tokenize(self, comps):
"""Split name on spaces, unless inside curly brackets or quotes."""
ps = []
for comp in comps:
ps.extend([c.strip(' ,') for c in re.split(r'\s+(?=[^{}]*(?:\{|$))', comp)])
return [p for p in ps if p] | python | def _tokenize(self, comps):
"""Split name on spaces, unless inside curly brackets or quotes."""
ps = []
for comp in comps:
ps.extend([c.strip(' ,') for c in re.split(r'\s+(?=[^{}]*(?:\{|$))', comp)])
return [p for p in ps if p] | [
"def",
"_tokenize",
"(",
"self",
",",
"comps",
")",
":",
"ps",
"=",
"[",
"]",
"for",
"comp",
"in",
"comps",
":",
"ps",
".",
"extend",
"(",
"[",
"c",
".",
"strip",
"(",
"' ,'",
")",
"for",
"c",
"in",
"re",
".",
"split",
"(",
"r'\\s+(?=[^{}]*(?:\\{... | Split name on spaces, unless inside curly brackets or quotes. | [
"Split",
"name",
"on",
"spaces",
"unless",
"inside",
"curly",
"brackets",
"or",
"quotes",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/person.py#L174-L179 |
6,389 | mcs07/ChemDataExtractor | chemdataextractor/biblio/person.py | PersonName._clean | def _clean(self, t, capitalize=None):
"""Convert to normalized unicode and strip trailing full stops."""
if self._from_bibtex:
t = latex_to_unicode(t, capitalize=capitalize)
t = ' '.join([el.rstrip('.') if el.count('.') == 1 else el for el in t.split()])
return t | python | def _clean(self, t, capitalize=None):
"""Convert to normalized unicode and strip trailing full stops."""
if self._from_bibtex:
t = latex_to_unicode(t, capitalize=capitalize)
t = ' '.join([el.rstrip('.') if el.count('.') == 1 else el for el in t.split()])
return t | [
"def",
"_clean",
"(",
"self",
",",
"t",
",",
"capitalize",
"=",
"None",
")",
":",
"if",
"self",
".",
"_from_bibtex",
":",
"t",
"=",
"latex_to_unicode",
"(",
"t",
",",
"capitalize",
"=",
"capitalize",
")",
"t",
"=",
"' '",
".",
"join",
"(",
"[",
"el... | Convert to normalized unicode and strip trailing full stops. | [
"Convert",
"to",
"normalized",
"unicode",
"and",
"strip",
"trailing",
"full",
"stops",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/person.py#L181-L186 |
6,390 | mcs07/ChemDataExtractor | chemdataextractor/biblio/person.py | PersonName._strip | def _strip(self, tokens, criteria, prop, rev=False):
"""Strip off contiguous tokens from the start or end of the list that meet the criteria."""
num = len(tokens)
res = []
for i, token in enumerate(reversed(tokens) if rev else tokens):
if criteria(token) and num > i + 1:
... | python | def _strip(self, tokens, criteria, prop, rev=False):
"""Strip off contiguous tokens from the start or end of the list that meet the criteria."""
num = len(tokens)
res = []
for i, token in enumerate(reversed(tokens) if rev else tokens):
if criteria(token) and num > i + 1:
... | [
"def",
"_strip",
"(",
"self",
",",
"tokens",
",",
"criteria",
",",
"prop",
",",
"rev",
"=",
"False",
")",
":",
"num",
"=",
"len",
"(",
"tokens",
")",
"res",
"=",
"[",
"]",
"for",
"i",
",",
"token",
"in",
"enumerate",
"(",
"reversed",
"(",
"tokens... | Strip off contiguous tokens from the start or end of the list that meet the criteria. | [
"Strip",
"off",
"contiguous",
"tokens",
"from",
"the",
"start",
"or",
"end",
"of",
"the",
"list",
"that",
"meet",
"the",
"criteria",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/person.py#L188-L199 |
6,391 | mcs07/ChemDataExtractor | chemdataextractor/reader/markup.py | LxmlReader._parse_text | def _parse_text(self, el, refs=None, specials=None, element_cls=Paragraph):
"""Like _parse_element but ensure a single element."""
if specials is None:
specials = {}
if refs is None:
refs = {}
elements = self._parse_element_r(el, specials=specials, refs=refs, ele... | python | def _parse_text(self, el, refs=None, specials=None, element_cls=Paragraph):
"""Like _parse_element but ensure a single element."""
if specials is None:
specials = {}
if refs is None:
refs = {}
elements = self._parse_element_r(el, specials=specials, refs=refs, ele... | [
"def",
"_parse_text",
"(",
"self",
",",
"el",
",",
"refs",
"=",
"None",
",",
"specials",
"=",
"None",
",",
"element_cls",
"=",
"Paragraph",
")",
":",
"if",
"specials",
"is",
"None",
":",
"specials",
"=",
"{",
"}",
"if",
"refs",
"is",
"None",
":",
"... | Like _parse_element but ensure a single element. | [
"Like",
"_parse_element",
"but",
"ensure",
"a",
"single",
"element",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/reader/markup.py#L112-L125 |
6,392 | mcs07/ChemDataExtractor | chemdataextractor/reader/markup.py | LxmlReader._parse_reference | def _parse_reference(self, el):
"""Return reference ID from href or text content."""
if '#' in el.get('href', ''):
return [el.get('href').split('#', 1)[1]]
elif 'rid' in el.attrib:
return [el.attrib['rid']]
elif 'idref' in el.attrib:
return [el.attrib[... | python | def _parse_reference(self, el):
"""Return reference ID from href or text content."""
if '#' in el.get('href', ''):
return [el.get('href').split('#', 1)[1]]
elif 'rid' in el.attrib:
return [el.attrib['rid']]
elif 'idref' in el.attrib:
return [el.attrib[... | [
"def",
"_parse_reference",
"(",
"self",
",",
"el",
")",
":",
"if",
"'#'",
"in",
"el",
".",
"get",
"(",
"'href'",
",",
"''",
")",
":",
"return",
"[",
"el",
".",
"get",
"(",
"'href'",
")",
".",
"split",
"(",
"'#'",
",",
"1",
")",
"[",
"1",
"]",... | Return reference ID from href or text content. | [
"Return",
"reference",
"ID",
"from",
"href",
"or",
"text",
"content",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/reader/markup.py#L163-L172 |
6,393 | mcs07/ChemDataExtractor | chemdataextractor/reader/markup.py | LxmlReader._is_inline | def _is_inline(self, element):
"""Return True if an element is inline."""
if element.tag not in {etree.Comment, etree.ProcessingInstruction} and element.tag.lower() in self.inline_elements:
return True
return False | python | def _is_inline(self, element):
"""Return True if an element is inline."""
if element.tag not in {etree.Comment, etree.ProcessingInstruction} and element.tag.lower() in self.inline_elements:
return True
return False | [
"def",
"_is_inline",
"(",
"self",
",",
"element",
")",
":",
"if",
"element",
".",
"tag",
"not",
"in",
"{",
"etree",
".",
"Comment",
",",
"etree",
".",
"ProcessingInstruction",
"}",
"and",
"element",
".",
"tag",
".",
"lower",
"(",
")",
"in",
"self",
"... | Return True if an element is inline. | [
"Return",
"True",
"if",
"an",
"element",
"is",
"inline",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/reader/markup.py#L193-L197 |
6,394 | mcs07/ChemDataExtractor | chemdataextractor/biblio/bibtex.py | BibtexParser._next_token | def _next_token(self, skipws=True):
"""Increment _token to the next token and return it."""
self._token = next(self._tokens).group(0)
return self._next_token() if skipws and self._token.isspace() else self._token | python | def _next_token(self, skipws=True):
"""Increment _token to the next token and return it."""
self._token = next(self._tokens).group(0)
return self._next_token() if skipws and self._token.isspace() else self._token | [
"def",
"_next_token",
"(",
"self",
",",
"skipws",
"=",
"True",
")",
":",
"self",
".",
"_token",
"=",
"next",
"(",
"self",
".",
"_tokens",
")",
".",
"group",
"(",
"0",
")",
"return",
"self",
".",
"_next_token",
"(",
")",
"if",
"skipws",
"and",
"self... | Increment _token to the next token and return it. | [
"Increment",
"_token",
"to",
"the",
"next",
"token",
"and",
"return",
"it",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L65-L68 |
6,395 | mcs07/ChemDataExtractor | chemdataextractor/biblio/bibtex.py | BibtexParser._parse_entry | def _parse_entry(self):
"""Parse an entry."""
entry_type = self._next_token().lower()
if entry_type == 'string':
self._parse_string()
elif entry_type not in ['comment', 'preamble']:
self._parse_record(entry_type) | python | def _parse_entry(self):
"""Parse an entry."""
entry_type = self._next_token().lower()
if entry_type == 'string':
self._parse_string()
elif entry_type not in ['comment', 'preamble']:
self._parse_record(entry_type) | [
"def",
"_parse_entry",
"(",
"self",
")",
":",
"entry_type",
"=",
"self",
".",
"_next_token",
"(",
")",
".",
"lower",
"(",
")",
"if",
"entry_type",
"==",
"'string'",
":",
"self",
".",
"_parse_string",
"(",
")",
"elif",
"entry_type",
"not",
"in",
"[",
"'... | Parse an entry. | [
"Parse",
"an",
"entry",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L80-L86 |
6,396 | mcs07/ChemDataExtractor | chemdataextractor/biblio/bibtex.py | BibtexParser._parse_string | def _parse_string(self):
"""Parse a string entry and store the definition."""
if self._next_token() in ['{', '(']:
field = self._parse_field()
if field:
self.definitions[field[0]] = field[1] | python | def _parse_string(self):
"""Parse a string entry and store the definition."""
if self._next_token() in ['{', '(']:
field = self._parse_field()
if field:
self.definitions[field[0]] = field[1] | [
"def",
"_parse_string",
"(",
"self",
")",
":",
"if",
"self",
".",
"_next_token",
"(",
")",
"in",
"[",
"'{'",
",",
"'('",
"]",
":",
"field",
"=",
"self",
".",
"_parse_field",
"(",
")",
"if",
"field",
":",
"self",
".",
"definitions",
"[",
"field",
"[... | Parse a string entry and store the definition. | [
"Parse",
"a",
"string",
"entry",
"and",
"store",
"the",
"definition",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L88-L93 |
6,397 | mcs07/ChemDataExtractor | chemdataextractor/biblio/bibtex.py | BibtexParser._parse_record | def _parse_record(self, record_type):
"""Parse a record."""
if self._next_token() in ['{', '(']:
key = self._next_token()
self.records[key] = {
u'id': key,
u'type': record_type.lower()
}
if self._next_token() == ',':
... | python | def _parse_record(self, record_type):
"""Parse a record."""
if self._next_token() in ['{', '(']:
key = self._next_token()
self.records[key] = {
u'id': key,
u'type': record_type.lower()
}
if self._next_token() == ',':
... | [
"def",
"_parse_record",
"(",
"self",
",",
"record_type",
")",
":",
"if",
"self",
".",
"_next_token",
"(",
")",
"in",
"[",
"'{'",
",",
"'('",
"]",
":",
"key",
"=",
"self",
".",
"_next_token",
"(",
")",
"self",
".",
"records",
"[",
"key",
"]",
"=",
... | Parse a record. | [
"Parse",
"a",
"record",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L95-L121 |
6,398 | mcs07/ChemDataExtractor | chemdataextractor/biblio/bibtex.py | BibtexParser._parse_field | def _parse_field(self):
"""Parse a Field."""
name = self._next_token()
if self._next_token() == '=':
value = self._parse_value()
return name, value | python | def _parse_field(self):
"""Parse a Field."""
name = self._next_token()
if self._next_token() == '=':
value = self._parse_value()
return name, value | [
"def",
"_parse_field",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"_next_token",
"(",
")",
"if",
"self",
".",
"_next_token",
"(",
")",
"==",
"'='",
":",
"value",
"=",
"self",
".",
"_parse_value",
"(",
")",
"return",
"name",
",",
"value"
] | Parse a Field. | [
"Parse",
"a",
"Field",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L123-L128 |
6,399 | mcs07/ChemDataExtractor | chemdataextractor/biblio/bibtex.py | BibtexParser._parse_value | def _parse_value(self):
"""Parse a value. Digits, definitions, and the contents of double quotes or curly brackets."""
val = []
while True:
t = self._next_token()
if t == '"':
brac_counter = 0
while True:
t = self._next_... | python | def _parse_value(self):
"""Parse a value. Digits, definitions, and the contents of double quotes or curly brackets."""
val = []
while True:
t = self._next_token()
if t == '"':
brac_counter = 0
while True:
t = self._next_... | [
"def",
"_parse_value",
"(",
"self",
")",
":",
"val",
"=",
"[",
"]",
"while",
"True",
":",
"t",
"=",
"self",
".",
"_next_token",
"(",
")",
"if",
"t",
"==",
"'\"'",
":",
"brac_counter",
"=",
"0",
"while",
"True",
":",
"t",
"=",
"self",
".",
"_next_... | Parse a value. Digits, definitions, and the contents of double quotes or curly brackets. | [
"Parse",
"a",
"value",
".",
"Digits",
"definitions",
"and",
"the",
"contents",
"of",
"double",
"quotes",
"or",
"curly",
"brackets",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L130-L169 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.