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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
39,900 | kgaughan/dbkit | dbkit.py | _make_connect | def _make_connect(module, args, kwargs):
"""
Returns a function capable of making connections with a particular
driver given the supplied credentials.
"""
# pylint: disable-msg=W0142
return functools.partial(module.connect, *args, **kwargs) | python | def _make_connect(module, args, kwargs):
"""
Returns a function capable of making connections with a particular
driver given the supplied credentials.
"""
# pylint: disable-msg=W0142
return functools.partial(module.connect, *args, **kwargs) | [
"def",
"_make_connect",
"(",
"module",
",",
"args",
",",
"kwargs",
")",
":",
"# pylint: disable-msg=W0142",
"return",
"functools",
".",
"partial",
"(",
"module",
".",
"connect",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Returns a function capable of making connections with a particular
driver given the supplied credentials. | [
"Returns",
"a",
"function",
"capable",
"of",
"making",
"connections",
"with",
"a",
"particular",
"driver",
"given",
"the",
"supplied",
"credentials",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L565-L571 |
39,901 | kgaughan/dbkit | dbkit.py | create_pool | def create_pool(module, max_conns, *args, **kwargs):
"""
Create a connection pool appropriate to the driver module's capabilities.
"""
if not hasattr(module, 'threadsafety'):
raise NotSupported("Cannot determine driver threadsafety.")
if max_conns < 1:
raise ValueError("Minimum numbe... | python | def create_pool(module, max_conns, *args, **kwargs):
"""
Create a connection pool appropriate to the driver module's capabilities.
"""
if not hasattr(module, 'threadsafety'):
raise NotSupported("Cannot determine driver threadsafety.")
if max_conns < 1:
raise ValueError("Minimum numbe... | [
"def",
"create_pool",
"(",
"module",
",",
"max_conns",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"hasattr",
"(",
"module",
",",
"'threadsafety'",
")",
":",
"raise",
"NotSupported",
"(",
"\"Cannot determine driver threadsafety.\"",
")",
... | Create a connection pool appropriate to the driver module's capabilities. | [
"Create",
"a",
"connection",
"pool",
"appropriate",
"to",
"the",
"driver",
"module",
"s",
"capabilities",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L585-L597 |
39,902 | kgaughan/dbkit | dbkit.py | transactional | def transactional(wrapped):
"""
A decorator to denote that the content of the decorated function or
method is to be ran in a transaction.
The following code is equivalent to the example for
:py:func:`dbkit.transaction`::
import sqlite3
import sys
from dbkit import connect, ... | python | def transactional(wrapped):
"""
A decorator to denote that the content of the decorated function or
method is to be ran in a transaction.
The following code is equivalent to the example for
:py:func:`dbkit.transaction`::
import sqlite3
import sys
from dbkit import connect, ... | [
"def",
"transactional",
"(",
"wrapped",
")",
":",
"# pylint: disable-msg=C0111",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"Context",
".",
"current",
"(",
")",
".",
"transaction",
"(",
")",
":",
"return",
"wrapped",
"... | A decorator to denote that the content of the decorated function or
method is to be ran in a transaction.
The following code is equivalent to the example for
:py:func:`dbkit.transaction`::
import sqlite3
import sys
from dbkit import connect, transactional, query_value, execute
... | [
"A",
"decorator",
"to",
"denote",
"that",
"the",
"content",
"of",
"the",
"decorated",
"function",
"or",
"method",
"is",
"to",
"be",
"ran",
"in",
"a",
"transaction",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L644-L683 |
39,903 | kgaughan/dbkit | dbkit.py | execute | def execute(stmt, args=()):
"""
Execute an SQL statement. Returns the number of affected rows.
"""
ctx = Context.current()
with ctx.mdr:
cursor = ctx.execute(stmt, args)
row_count = cursor.rowcount
_safe_close(cursor)
return row_count | python | def execute(stmt, args=()):
"""
Execute an SQL statement. Returns the number of affected rows.
"""
ctx = Context.current()
with ctx.mdr:
cursor = ctx.execute(stmt, args)
row_count = cursor.rowcount
_safe_close(cursor)
return row_count | [
"def",
"execute",
"(",
"stmt",
",",
"args",
"=",
"(",
")",
")",
":",
"ctx",
"=",
"Context",
".",
"current",
"(",
")",
"with",
"ctx",
".",
"mdr",
":",
"cursor",
"=",
"ctx",
".",
"execute",
"(",
"stmt",
",",
"args",
")",
"row_count",
"=",
"cursor",... | Execute an SQL statement. Returns the number of affected rows. | [
"Execute",
"an",
"SQL",
"statement",
".",
"Returns",
"the",
"number",
"of",
"affected",
"rows",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L693-L702 |
39,904 | kgaughan/dbkit | dbkit.py | query | def query(stmt, args=(), factory=None):
"""
Execute a query. This returns an iterator of the result set.
"""
ctx = Context.current()
factory = ctx.default_factory if factory is None else factory
with ctx.mdr:
return factory(ctx.execute(stmt, args), ctx.mdr) | python | def query(stmt, args=(), factory=None):
"""
Execute a query. This returns an iterator of the result set.
"""
ctx = Context.current()
factory = ctx.default_factory if factory is None else factory
with ctx.mdr:
return factory(ctx.execute(stmt, args), ctx.mdr) | [
"def",
"query",
"(",
"stmt",
",",
"args",
"=",
"(",
")",
",",
"factory",
"=",
"None",
")",
":",
"ctx",
"=",
"Context",
".",
"current",
"(",
")",
"factory",
"=",
"ctx",
".",
"default_factory",
"if",
"factory",
"is",
"None",
"else",
"factory",
"with",
... | Execute a query. This returns an iterator of the result set. | [
"Execute",
"a",
"query",
".",
"This",
"returns",
"an",
"iterator",
"of",
"the",
"result",
"set",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L705-L712 |
39,905 | kgaughan/dbkit | dbkit.py | query_row | def query_row(stmt, args=(), factory=None):
"""
Execute a query. Returns the first row of the result set, or `None`.
"""
for row in query(stmt, args, factory):
return row
return None | python | def query_row(stmt, args=(), factory=None):
"""
Execute a query. Returns the first row of the result set, or `None`.
"""
for row in query(stmt, args, factory):
return row
return None | [
"def",
"query_row",
"(",
"stmt",
",",
"args",
"=",
"(",
")",
",",
"factory",
"=",
"None",
")",
":",
"for",
"row",
"in",
"query",
"(",
"stmt",
",",
"args",
",",
"factory",
")",
":",
"return",
"row",
"return",
"None"
] | Execute a query. Returns the first row of the result set, or `None`. | [
"Execute",
"a",
"query",
".",
"Returns",
"the",
"first",
"row",
"of",
"the",
"result",
"set",
"or",
"None",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L715-L721 |
39,906 | kgaughan/dbkit | dbkit.py | query_value | def query_value(stmt, args=(), default=None):
"""
Execute a query, returning the first value in the first row of the
result set. If the query returns no result set, a default value is
returned, which is `None` by default.
"""
for row in query(stmt, args, TupleFactory):
return row[0]
... | python | def query_value(stmt, args=(), default=None):
"""
Execute a query, returning the first value in the first row of the
result set. If the query returns no result set, a default value is
returned, which is `None` by default.
"""
for row in query(stmt, args, TupleFactory):
return row[0]
... | [
"def",
"query_value",
"(",
"stmt",
",",
"args",
"=",
"(",
")",
",",
"default",
"=",
"None",
")",
":",
"for",
"row",
"in",
"query",
"(",
"stmt",
",",
"args",
",",
"TupleFactory",
")",
":",
"return",
"row",
"[",
"0",
"]",
"return",
"default"
] | Execute a query, returning the first value in the first row of the
result set. If the query returns no result set, a default value is
returned, which is `None` by default. | [
"Execute",
"a",
"query",
"returning",
"the",
"first",
"value",
"in",
"the",
"first",
"row",
"of",
"the",
"result",
"set",
".",
"If",
"the",
"query",
"returns",
"no",
"result",
"set",
"a",
"default",
"value",
"is",
"returned",
"which",
"is",
"None",
"by",... | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L724-L732 |
39,907 | kgaughan/dbkit | dbkit.py | execute_proc | def execute_proc(procname, args=()):
"""
Execute a stored procedure. Returns the number of affected rows.
"""
ctx = Context.current()
with ctx.mdr:
cursor = ctx.execute_proc(procname, args)
row_count = cursor.rowcount
_safe_close(cursor)
return row_count | python | def execute_proc(procname, args=()):
"""
Execute a stored procedure. Returns the number of affected rows.
"""
ctx = Context.current()
with ctx.mdr:
cursor = ctx.execute_proc(procname, args)
row_count = cursor.rowcount
_safe_close(cursor)
return row_count | [
"def",
"execute_proc",
"(",
"procname",
",",
"args",
"=",
"(",
")",
")",
":",
"ctx",
"=",
"Context",
".",
"current",
"(",
")",
"with",
"ctx",
".",
"mdr",
":",
"cursor",
"=",
"ctx",
".",
"execute_proc",
"(",
"procname",
",",
"args",
")",
"row_count",
... | Execute a stored procedure. Returns the number of affected rows. | [
"Execute",
"a",
"stored",
"procedure",
".",
"Returns",
"the",
"number",
"of",
"affected",
"rows",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L742-L751 |
39,908 | kgaughan/dbkit | dbkit.py | query_proc | def query_proc(procname, args=(), factory=None):
"""
Execute a stored procedure. This returns an iterator of the result set.
"""
ctx = Context.current()
factory = ctx.default_factory if factory is None else factory
with ctx.mdr:
return factory(ctx.execute_proc(procname, args), ctx.mdr) | python | def query_proc(procname, args=(), factory=None):
"""
Execute a stored procedure. This returns an iterator of the result set.
"""
ctx = Context.current()
factory = ctx.default_factory if factory is None else factory
with ctx.mdr:
return factory(ctx.execute_proc(procname, args), ctx.mdr) | [
"def",
"query_proc",
"(",
"procname",
",",
"args",
"=",
"(",
")",
",",
"factory",
"=",
"None",
")",
":",
"ctx",
"=",
"Context",
".",
"current",
"(",
")",
"factory",
"=",
"ctx",
".",
"default_factory",
"if",
"factory",
"is",
"None",
"else",
"factory",
... | Execute a stored procedure. This returns an iterator of the result set. | [
"Execute",
"a",
"stored",
"procedure",
".",
"This",
"returns",
"an",
"iterator",
"of",
"the",
"result",
"set",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L754-L761 |
39,909 | kgaughan/dbkit | dbkit.py | query_proc_row | def query_proc_row(procname, args=(), factory=None):
"""
Execute a stored procedure. Returns the first row of the result set,
or `None`.
"""
for row in query_proc(procname, args, factory):
return row
return None | python | def query_proc_row(procname, args=(), factory=None):
"""
Execute a stored procedure. Returns the first row of the result set,
or `None`.
"""
for row in query_proc(procname, args, factory):
return row
return None | [
"def",
"query_proc_row",
"(",
"procname",
",",
"args",
"=",
"(",
")",
",",
"factory",
"=",
"None",
")",
":",
"for",
"row",
"in",
"query_proc",
"(",
"procname",
",",
"args",
",",
"factory",
")",
":",
"return",
"row",
"return",
"None"
] | Execute a stored procedure. Returns the first row of the result set,
or `None`. | [
"Execute",
"a",
"stored",
"procedure",
".",
"Returns",
"the",
"first",
"row",
"of",
"the",
"result",
"set",
"or",
"None",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L764-L771 |
39,910 | kgaughan/dbkit | dbkit.py | query_proc_value | def query_proc_value(procname, args=(), default=None):
"""
Execute a stored procedure, returning the first value in the first row
of the result set. If it returns no result set, a default value is
returned, which is `None` by default.
"""
for row in query_proc(procname, args, TupleFactory):
... | python | def query_proc_value(procname, args=(), default=None):
"""
Execute a stored procedure, returning the first value in the first row
of the result set. If it returns no result set, a default value is
returned, which is `None` by default.
"""
for row in query_proc(procname, args, TupleFactory):
... | [
"def",
"query_proc_value",
"(",
"procname",
",",
"args",
"=",
"(",
")",
",",
"default",
"=",
"None",
")",
":",
"for",
"row",
"in",
"query_proc",
"(",
"procname",
",",
"args",
",",
"TupleFactory",
")",
":",
"return",
"row",
"[",
"0",
"]",
"return",
"d... | Execute a stored procedure, returning the first value in the first row
of the result set. If it returns no result set, a default value is
returned, which is `None` by default. | [
"Execute",
"a",
"stored",
"procedure",
"returning",
"the",
"first",
"value",
"in",
"the",
"first",
"row",
"of",
"the",
"result",
"set",
".",
"If",
"it",
"returns",
"no",
"result",
"set",
"a",
"default",
"value",
"is",
"returned",
"which",
"is",
"None",
"... | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L774-L782 |
39,911 | kgaughan/dbkit | dbkit.py | make_placeholders | def make_placeholders(seq, start=1):
"""
Generate placeholders for the given sequence.
"""
if len(seq) == 0:
raise ValueError('Sequence must have at least one element.')
param_style = Context.current().param_style
placeholders = None
if isinstance(seq, dict):
if param_style i... | python | def make_placeholders(seq, start=1):
"""
Generate placeholders for the given sequence.
"""
if len(seq) == 0:
raise ValueError('Sequence must have at least one element.')
param_style = Context.current().param_style
placeholders = None
if isinstance(seq, dict):
if param_style i... | [
"def",
"make_placeholders",
"(",
"seq",
",",
"start",
"=",
"1",
")",
":",
"if",
"len",
"(",
"seq",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'Sequence must have at least one element.'",
")",
"param_style",
"=",
"Context",
".",
"current",
"(",
")",
... | Generate placeholders for the given sequence. | [
"Generate",
"placeholders",
"for",
"the",
"given",
"sequence",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L957-L982 |
39,912 | kgaughan/dbkit | dbkit.py | make_file_object_logger | def make_file_object_logger(fh):
"""
Make a logger that logs to the given file object.
"""
def logger_func(stmt, args, fh=fh):
"""
A logger that logs everything sent to a file object.
"""
now = datetime.datetime.now()
six.print_("Executing (%s):" % now.isoformat()... | python | def make_file_object_logger(fh):
"""
Make a logger that logs to the given file object.
"""
def logger_func(stmt, args, fh=fh):
"""
A logger that logs everything sent to a file object.
"""
now = datetime.datetime.now()
six.print_("Executing (%s):" % now.isoformat()... | [
"def",
"make_file_object_logger",
"(",
"fh",
")",
":",
"def",
"logger_func",
"(",
"stmt",
",",
"args",
",",
"fh",
"=",
"fh",
")",
":",
"\"\"\"\n A logger that logs everything sent to a file object.\n \"\"\"",
"now",
"=",
"datetime",
".",
"datetime",
".",... | Make a logger that logs to the given file object. | [
"Make",
"a",
"logger",
"that",
"logs",
"to",
"the",
"given",
"file",
"object",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L992-L1005 |
39,913 | kgaughan/dbkit | dbkit.py | Context.current | def current(cls, with_exception=True):
"""
Returns the current database context.
"""
if with_exception and len(cls.stack) == 0:
raise NoContext()
return cls.stack.top() | python | def current(cls, with_exception=True):
"""
Returns the current database context.
"""
if with_exception and len(cls.stack) == 0:
raise NoContext()
return cls.stack.top() | [
"def",
"current",
"(",
"cls",
",",
"with_exception",
"=",
"True",
")",
":",
"if",
"with_exception",
"and",
"len",
"(",
"cls",
".",
"stack",
")",
"==",
"0",
":",
"raise",
"NoContext",
"(",
")",
"return",
"cls",
".",
"stack",
".",
"top",
"(",
")"
] | Returns the current database context. | [
"Returns",
"the",
"current",
"database",
"context",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L146-L152 |
39,914 | kgaughan/dbkit | dbkit.py | Context.transaction | def transaction(self):
"""
Sets up a context where all the statements within it are ran within
a single database transaction. For internal use only.
"""
# The idea here is to fake the nesting of transactions. Only when
# we've gotten back to the topmost transaction contex... | python | def transaction(self):
"""
Sets up a context where all the statements within it are ran within
a single database transaction. For internal use only.
"""
# The idea here is to fake the nesting of transactions. Only when
# we've gotten back to the topmost transaction contex... | [
"def",
"transaction",
"(",
"self",
")",
":",
"# The idea here is to fake the nesting of transactions. Only when",
"# we've gotten back to the topmost transaction context do we actually",
"# commit or rollback.",
"with",
"self",
".",
"mdr",
":",
"try",
":",
"self",
".",
"_depth",
... | Sets up a context where all the statements within it are ran within
a single database transaction. For internal use only. | [
"Sets",
"up",
"a",
"context",
"where",
"all",
"the",
"statements",
"within",
"it",
"are",
"ran",
"within",
"a",
"single",
"database",
"transaction",
".",
"For",
"internal",
"use",
"only",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L155-L179 |
39,915 | kgaughan/dbkit | dbkit.py | Context.cursor | def cursor(self):
"""
Get a cursor for the current connection. For internal use only.
"""
cursor = self.mdr.cursor()
with self.transaction():
try:
yield cursor
if cursor.rowcount != -1:
self.last_row_count = cursor.r... | python | def cursor(self):
"""
Get a cursor for the current connection. For internal use only.
"""
cursor = self.mdr.cursor()
with self.transaction():
try:
yield cursor
if cursor.rowcount != -1:
self.last_row_count = cursor.r... | [
"def",
"cursor",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"mdr",
".",
"cursor",
"(",
")",
"with",
"self",
".",
"transaction",
"(",
")",
":",
"try",
":",
"yield",
"cursor",
"if",
"cursor",
".",
"rowcount",
"!=",
"-",
"1",
":",
"self",
".... | Get a cursor for the current connection. For internal use only. | [
"Get",
"a",
"cursor",
"for",
"the",
"current",
"connection",
".",
"For",
"internal",
"use",
"only",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L182-L197 |
39,916 | kgaughan/dbkit | dbkit.py | Context.execute | def execute(self, stmt, args):
"""
Execute a statement, returning a cursor. For internal use only.
"""
self.logger(stmt, args)
with self.cursor() as cursor:
cursor.execute(stmt, args)
return cursor | python | def execute(self, stmt, args):
"""
Execute a statement, returning a cursor. For internal use only.
"""
self.logger(stmt, args)
with self.cursor() as cursor:
cursor.execute(stmt, args)
return cursor | [
"def",
"execute",
"(",
"self",
",",
"stmt",
",",
"args",
")",
":",
"self",
".",
"logger",
"(",
"stmt",
",",
"args",
")",
"with",
"self",
".",
"cursor",
"(",
")",
"as",
"cursor",
":",
"cursor",
".",
"execute",
"(",
"stmt",
",",
"args",
")",
"retur... | Execute a statement, returning a cursor. For internal use only. | [
"Execute",
"a",
"statement",
"returning",
"a",
"cursor",
".",
"For",
"internal",
"use",
"only",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L199-L206 |
39,917 | kgaughan/dbkit | dbkit.py | Context.execute_proc | def execute_proc(self, procname, args):
"""
Execute a stored procedure, returning a cursor. For internal use
only.
"""
self.logger(procname, args)
with self.cursor() as cursor:
cursor.callproc(procname, args)
return cursor | python | def execute_proc(self, procname, args):
"""
Execute a stored procedure, returning a cursor. For internal use
only.
"""
self.logger(procname, args)
with self.cursor() as cursor:
cursor.callproc(procname, args)
return cursor | [
"def",
"execute_proc",
"(",
"self",
",",
"procname",
",",
"args",
")",
":",
"self",
".",
"logger",
"(",
"procname",
",",
"args",
")",
"with",
"self",
".",
"cursor",
"(",
")",
"as",
"cursor",
":",
"cursor",
".",
"callproc",
"(",
"procname",
",",
"args... | Execute a stored procedure, returning a cursor. For internal use
only. | [
"Execute",
"a",
"stored",
"procedure",
"returning",
"a",
"cursor",
".",
"For",
"internal",
"use",
"only",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L208-L216 |
39,918 | kgaughan/dbkit | dbkit.py | Context.close | def close(self):
"""
Close the connection this context wraps.
"""
self.logger = None
for exc in _EXCEPTIONS:
setattr(self, exc, None)
try:
self.mdr.close()
finally:
self.mdr = None | python | def close(self):
"""
Close the connection this context wraps.
"""
self.logger = None
for exc in _EXCEPTIONS:
setattr(self, exc, None)
try:
self.mdr.close()
finally:
self.mdr = None | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"logger",
"=",
"None",
"for",
"exc",
"in",
"_EXCEPTIONS",
":",
"setattr",
"(",
"self",
",",
"exc",
",",
"None",
")",
"try",
":",
"self",
".",
"mdr",
".",
"close",
"(",
")",
"finally",
":",
"self... | Close the connection this context wraps. | [
"Close",
"the",
"connection",
"this",
"context",
"wraps",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L218-L228 |
39,919 | kgaughan/dbkit | dbkit.py | PoolBase.connect | def connect(self):
"""
Returns a context that uses this pool as a connection source.
"""
ctx = Context(self.module, self.create_mediator())
ctx.logger = self.logger
ctx.default_factory = self.default_factory
return ctx | python | def connect(self):
"""
Returns a context that uses this pool as a connection source.
"""
ctx = Context(self.module, self.create_mediator())
ctx.logger = self.logger
ctx.default_factory = self.default_factory
return ctx | [
"def",
"connect",
"(",
"self",
")",
":",
"ctx",
"=",
"Context",
"(",
"self",
".",
"module",
",",
"self",
".",
"create_mediator",
"(",
")",
")",
"ctx",
".",
"logger",
"=",
"self",
".",
"logger",
"ctx",
".",
"default_factory",
"=",
"self",
".",
"defaul... | Returns a context that uses this pool as a connection source. | [
"Returns",
"a",
"context",
"that",
"uses",
"this",
"pool",
"as",
"a",
"connection",
"source",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L452-L459 |
39,920 | kgaughan/dbkit | dbkit.py | FactoryBase.close | def close(self):
"""
Release all resources associated with this factory.
"""
if self.mdr is None:
return
exc = (None, None, None)
try:
self.cursor.close()
except:
exc = sys.exc_info()
try:
if self.mdr.__exit_... | python | def close(self):
"""
Release all resources associated with this factory.
"""
if self.mdr is None:
return
exc = (None, None, None)
try:
self.cursor.close()
except:
exc = sys.exc_info()
try:
if self.mdr.__exit_... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"mdr",
"is",
"None",
":",
"return",
"exc",
"=",
"(",
"None",
",",
"None",
",",
"None",
")",
"try",
":",
"self",
".",
"cursor",
".",
"close",
"(",
")",
"except",
":",
"exc",
"=",
"sys",
... | Release all resources associated with this factory. | [
"Release",
"all",
"resources",
"associated",
"with",
"this",
"factory",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L811-L830 |
39,921 | tradenity/python-sdk | tradenity/resources/shopping_cart.py | ShoppingCart.add_item | def add_item(cls, item, **kwargs):
"""Add item.
Add new item to the shopping cart.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.add_item(item, async=True)
>>> result = thread.get()
... | python | def add_item(cls, item, **kwargs):
"""Add item.
Add new item to the shopping cart.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.add_item(item, async=True)
>>> result = thread.get()
... | [
"def",
"add_item",
"(",
"cls",
",",
"item",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_add_item_with_http_info",
"(",
"item... | Add item.
Add new item to the shopping cart.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.add_item(item, async=True)
>>> result = thread.get()
:param async bool
:param Line... | [
"Add",
"item",
"."
] | d13fbe23f4d6ff22554c6d8d2deaf209371adaf1 | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/shopping_cart.py#L318-L338 |
39,922 | tradenity/python-sdk | tradenity/resources/shopping_cart.py | ShoppingCart.checkout | def checkout(cls, order, **kwargs):
"""Checkout cart.
Checkout cart, Making an order.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.checkout(order, async=True)
>>> result = thread.ge... | python | def checkout(cls, order, **kwargs):
"""Checkout cart.
Checkout cart, Making an order.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.checkout(order, async=True)
>>> result = thread.ge... | [
"def",
"checkout",
"(",
"cls",
",",
"order",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_checkout_with_http_info",
"(",
"ord... | Checkout cart.
Checkout cart, Making an order.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.checkout(order, async=True)
>>> result = thread.get()
:param async bool
:param O... | [
"Checkout",
"cart",
"."
] | d13fbe23f4d6ff22554c6d8d2deaf209371adaf1 | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/shopping_cart.py#L417-L437 |
39,923 | tradenity/python-sdk | tradenity/resources/shopping_cart.py | ShoppingCart.delete_item | def delete_item(cls, item_id, **kwargs):
"""Remove item.
Remove item from shopping cart
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_item(item_id, async=True)
>>> result = th... | python | def delete_item(cls, item_id, **kwargs):
"""Remove item.
Remove item from shopping cart
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_item(item_id, async=True)
>>> result = th... | [
"def",
"delete_item",
"(",
"cls",
",",
"item_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_delete_item_with_http_info",
"("... | Remove item.
Remove item from shopping cart
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_item(item_id, async=True)
>>> result = thread.get()
:param async bool
:param... | [
"Remove",
"item",
"."
] | d13fbe23f4d6ff22554c6d8d2deaf209371adaf1 | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/shopping_cart.py#L516-L536 |
39,924 | tradenity/python-sdk | tradenity/resources/shopping_cart.py | ShoppingCart.empty | def empty(cls, **kwargs):
"""Empty cart.
Empty the shopping cart.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.empty(async=True)
>>> result = thread.get()
:param async bool... | python | def empty(cls, **kwargs):
"""Empty cart.
Empty the shopping cart.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.empty(async=True)
>>> result = thread.get()
:param async bool... | [
"def",
"empty",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_empty_with_http_info",
"(",
"*",
"*",
"kwargs",
")... | Empty cart.
Empty the shopping cart.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.empty(async=True)
>>> result = thread.get()
:param async bool
:return: ShoppingCart
... | [
"Empty",
"cart",
"."
] | d13fbe23f4d6ff22554c6d8d2deaf209371adaf1 | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/shopping_cart.py#L615-L634 |
39,925 | tradenity/python-sdk | tradenity/resources/shopping_cart.py | ShoppingCart.get | def get(cls, **kwargs):
"""Get cart.
Retrieve the shopping cart of the current session.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get(async=True)
>>> result = thread.get()
... | python | def get(cls, **kwargs):
"""Get cart.
Retrieve the shopping cart of the current session.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get(async=True)
>>> result = thread.get()
... | [
"def",
"get",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_get_with_http_info",
"(",
"*",
"*",
"kwargs",
")",
... | Get cart.
Retrieve the shopping cart of the current session.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get(async=True)
>>> result = thread.get()
:param async bool
:retur... | [
"Get",
"cart",
"."
] | d13fbe23f4d6ff22554c6d8d2deaf209371adaf1 | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/shopping_cart.py#L706-L725 |
39,926 | tradenity/python-sdk | tradenity/resources/shopping_cart.py | ShoppingCart.update_item | def update_item(cls, item_id, item, **kwargs):
"""Update cart.
Update cart item.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_item(item_id, item, async=True)
>>> result = thr... | python | def update_item(cls, item_id, item, **kwargs):
"""Update cart.
Update cart item.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_item(item_id, item, async=True)
>>> result = thr... | [
"def",
"update_item",
"(",
"cls",
",",
"item_id",
",",
"item",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_update_item_with_... | Update cart.
Update cart item.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_item(item_id, item, async=True)
>>> result = thread.get()
:param async bool
:param str it... | [
"Update",
"cart",
"."
] | d13fbe23f4d6ff22554c6d8d2deaf209371adaf1 | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/shopping_cart.py#L797-L818 |
39,927 | wuher/devil | devil/perm/acl.py | PermissionController.get_perm_names | def get_perm_names(cls, resource):
""" Return all permissions supported by the resource.
This is used for auto-generating missing permissions rows into
database in syncdb.
"""
return [cls.get_perm_name(resource, method) for method in cls.METHODS] | python | def get_perm_names(cls, resource):
""" Return all permissions supported by the resource.
This is used for auto-generating missing permissions rows into
database in syncdb.
"""
return [cls.get_perm_name(resource, method) for method in cls.METHODS] | [
"def",
"get_perm_names",
"(",
"cls",
",",
"resource",
")",
":",
"return",
"[",
"cls",
".",
"get_perm_name",
"(",
"resource",
",",
"method",
")",
"for",
"method",
"in",
"cls",
".",
"METHODS",
"]"
] | Return all permissions supported by the resource.
This is used for auto-generating missing permissions rows into
database in syncdb. | [
"Return",
"all",
"permissions",
"supported",
"by",
"the",
"resource",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/perm/acl.py#L19-L26 |
39,928 | wuher/devil | devil/perm/acl.py | PermissionController.get_perm_name | def get_perm_name(cls, resource, method):
""" Compose permission name
@param resource the resource
@param method the request method (case doesn't matter).
"""
return '%s_%s_%s' % (
cls.PREFIX,
cls._get_resource_name(resource),
method.lower()) | python | def get_perm_name(cls, resource, method):
""" Compose permission name
@param resource the resource
@param method the request method (case doesn't matter).
"""
return '%s_%s_%s' % (
cls.PREFIX,
cls._get_resource_name(resource),
method.lower()) | [
"def",
"get_perm_name",
"(",
"cls",
",",
"resource",
",",
"method",
")",
":",
"return",
"'%s_%s_%s'",
"%",
"(",
"cls",
".",
"PREFIX",
",",
"cls",
".",
"_get_resource_name",
"(",
"resource",
")",
",",
"method",
".",
"lower",
"(",
")",
")"
] | Compose permission name
@param resource the resource
@param method the request method (case doesn't matter). | [
"Compose",
"permission",
"name"
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/perm/acl.py#L29-L39 |
39,929 | wuher/devil | devil/perm/acl.py | PermissionController._has_perm | def _has_perm(self, user, permission):
""" Check whether the user has the given permission
@return True if user is granted with access, False if not.
"""
if user.is_superuser:
return True
if user.is_active:
perms = [perm.split('.')[1] for perm in user.ge... | python | def _has_perm(self, user, permission):
""" Check whether the user has the given permission
@return True if user is granted with access, False if not.
"""
if user.is_superuser:
return True
if user.is_active:
perms = [perm.split('.')[1] for perm in user.ge... | [
"def",
"_has_perm",
"(",
"self",
",",
"user",
",",
"permission",
")",
":",
"if",
"user",
".",
"is_superuser",
":",
"return",
"True",
"if",
"user",
".",
"is_active",
":",
"perms",
"=",
"[",
"perm",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
"]",
"for"... | Check whether the user has the given permission
@return True if user is granted with access, False if not. | [
"Check",
"whether",
"the",
"user",
"has",
"the",
"given",
"permission"
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/perm/acl.py#L53-L64 |
39,930 | inveniosoftware-attic/invenio-utils | invenio_utils/url.py | is_local_url | def is_local_url(target):
"""Determine if URL is a local."""
ref_url = urlparse(cfg.get('CFG_SITE_SECURE_URL'))
test_url = urlparse(urljoin(cfg.get('CFG_SITE_SECURE_URL'), target))
return test_url.scheme in ('http', 'https') and \
ref_url.netloc == test_url.netloc | python | def is_local_url(target):
"""Determine if URL is a local."""
ref_url = urlparse(cfg.get('CFG_SITE_SECURE_URL'))
test_url = urlparse(urljoin(cfg.get('CFG_SITE_SECURE_URL'), target))
return test_url.scheme in ('http', 'https') and \
ref_url.netloc == test_url.netloc | [
"def",
"is_local_url",
"(",
"target",
")",
":",
"ref_url",
"=",
"urlparse",
"(",
"cfg",
".",
"get",
"(",
"'CFG_SITE_SECURE_URL'",
")",
")",
"test_url",
"=",
"urlparse",
"(",
"urljoin",
"(",
"cfg",
".",
"get",
"(",
"'CFG_SITE_SECURE_URL'",
")",
",",
"target... | Determine if URL is a local. | [
"Determine",
"if",
"URL",
"is",
"a",
"local",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/url.py#L115-L120 |
39,931 | inveniosoftware-attic/invenio-utils | invenio_utils/url.py | rewrite_to_secure_url | def rewrite_to_secure_url(url, secure_base=None):
"""
Rewrite URL to a Secure URL
@param url URL to be rewritten to a secure URL.
@param secure_base: Base URL of secure site (defaults to CFG_SITE_SECURE_URL).
"""
if secure_base is None:
secure_base = cfg.get('CFG_SITE_SECURE_URL')
u... | python | def rewrite_to_secure_url(url, secure_base=None):
"""
Rewrite URL to a Secure URL
@param url URL to be rewritten to a secure URL.
@param secure_base: Base URL of secure site (defaults to CFG_SITE_SECURE_URL).
"""
if secure_base is None:
secure_base = cfg.get('CFG_SITE_SECURE_URL')
u... | [
"def",
"rewrite_to_secure_url",
"(",
"url",
",",
"secure_base",
"=",
"None",
")",
":",
"if",
"secure_base",
"is",
"None",
":",
"secure_base",
"=",
"cfg",
".",
"get",
"(",
"'CFG_SITE_SECURE_URL'",
")",
"url_parts",
"=",
"list",
"(",
"urlparse",
"(",
"url",
... | Rewrite URL to a Secure URL
@param url URL to be rewritten to a secure URL.
@param secure_base: Base URL of secure site (defaults to CFG_SITE_SECURE_URL). | [
"Rewrite",
"URL",
"to",
"a",
"Secure",
"URL"
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/url.py#L207-L220 |
39,932 | inveniosoftware-attic/invenio-utils | invenio_utils/url.py | create_html_link | def create_html_link(urlbase, urlargd, link_label, linkattrd=None,
escape_urlargd=True, escape_linkattrd=True,
urlhash=None):
"""Creates a W3C compliant link.
@param urlbase: base url (e.g. config.CFG_SITE_URL/search)
@param urlargd: dictionary of parameters. (e.g. ... | python | def create_html_link(urlbase, urlargd, link_label, linkattrd=None,
escape_urlargd=True, escape_linkattrd=True,
urlhash=None):
"""Creates a W3C compliant link.
@param urlbase: base url (e.g. config.CFG_SITE_URL/search)
@param urlargd: dictionary of parameters. (e.g. ... | [
"def",
"create_html_link",
"(",
"urlbase",
",",
"urlargd",
",",
"link_label",
",",
"linkattrd",
"=",
"None",
",",
"escape_urlargd",
"=",
"True",
",",
"escape_linkattrd",
"=",
"True",
",",
"urlhash",
"=",
"None",
")",
":",
"attributes_separator",
"=",
"' '",
... | Creates a W3C compliant link.
@param urlbase: base url (e.g. config.CFG_SITE_URL/search)
@param urlargd: dictionary of parameters. (e.g. p={'recid':3, 'of'='hb'})
@param link_label: text displayed in a browser (has to be already escaped)
@param linkattrd: dictionary of attributes (e.g. a={'class': 'img'... | [
"Creates",
"a",
"W3C",
"compliant",
"link",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/url.py#L291-L320 |
39,933 | inveniosoftware-attic/invenio-utils | invenio_utils/url.py | get_canonical_and_alternates_urls | def get_canonical_and_alternates_urls(
url,
drop_ln=True,
washed_argd=None,
quote_path=False):
"""
Given an Invenio URL returns a tuple with two elements. The first is the
canonical URL, that is the original URL with CFG_SITE_URL prefix, and
where the ln= argument strippe... | python | def get_canonical_and_alternates_urls(
url,
drop_ln=True,
washed_argd=None,
quote_path=False):
"""
Given an Invenio URL returns a tuple with two elements. The first is the
canonical URL, that is the original URL with CFG_SITE_URL prefix, and
where the ln= argument strippe... | [
"def",
"get_canonical_and_alternates_urls",
"(",
"url",
",",
"drop_ln",
"=",
"True",
",",
"washed_argd",
"=",
"None",
",",
"quote_path",
"=",
"False",
")",
":",
"dummy_scheme",
",",
"dummy_netloc",
",",
"path",
",",
"dummy_params",
",",
"query",
",",
"fragment... | Given an Invenio URL returns a tuple with two elements. The first is the
canonical URL, that is the original URL with CFG_SITE_URL prefix, and
where the ln= argument stripped. The second element element is mapping,
language code -> alternate URL
@param quote_path: if True, the path section of the given... | [
"Given",
"an",
"Invenio",
"URL",
"returns",
"a",
"tuple",
"with",
"two",
"elements",
".",
"The",
"first",
"is",
"the",
"canonical",
"URL",
"that",
"is",
"the",
"original",
"URL",
"with",
"CFG_SITE_URL",
"prefix",
"and",
"where",
"the",
"ln",
"=",
"argument... | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/url.py#L470-L515 |
39,934 | inveniosoftware-attic/invenio-utils | invenio_utils/url.py | same_urls_p | def same_urls_p(a, b):
""" Compare two URLs, ignoring reorganizing of query arguments """
ua = list(urlparse(a))
ub = list(urlparse(b))
ua[4] = parse_qs(ua[4])
ub[4] = parse_qs(ub[4])
return ua == ub | python | def same_urls_p(a, b):
""" Compare two URLs, ignoring reorganizing of query arguments """
ua = list(urlparse(a))
ub = list(urlparse(b))
ua[4] = parse_qs(ua[4])
ub[4] = parse_qs(ub[4])
return ua == ub | [
"def",
"same_urls_p",
"(",
"a",
",",
"b",
")",
":",
"ua",
"=",
"list",
"(",
"urlparse",
"(",
"a",
")",
")",
"ub",
"=",
"list",
"(",
"urlparse",
"(",
"b",
")",
")",
"ua",
"[",
"4",
"]",
"=",
"parse_qs",
"(",
"ua",
"[",
"4",
"]",
")",
"ub",
... | Compare two URLs, ignoring reorganizing of query arguments | [
"Compare",
"two",
"URLs",
"ignoring",
"reorganizing",
"of",
"query",
"arguments"
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/url.py#L544-L553 |
39,935 | inveniosoftware-attic/invenio-utils | invenio_utils/url.py | make_user_agent_string | def make_user_agent_string(component=None):
"""
Return a nice and uniform user-agent string to be used when Invenio
act as a client in HTTP requests.
"""
ret = "Invenio-%s (+%s; \"%s\")" % (cfg.get('CFG_VERSION'),
cfg.get('CFG_SITE_URL'), cfg.get('CFG_SITE_NAM... | python | def make_user_agent_string(component=None):
"""
Return a nice and uniform user-agent string to be used when Invenio
act as a client in HTTP requests.
"""
ret = "Invenio-%s (+%s; \"%s\")" % (cfg.get('CFG_VERSION'),
cfg.get('CFG_SITE_URL'), cfg.get('CFG_SITE_NAM... | [
"def",
"make_user_agent_string",
"(",
"component",
"=",
"None",
")",
":",
"ret",
"=",
"\"Invenio-%s (+%s; \\\"%s\\\")\"",
"%",
"(",
"cfg",
".",
"get",
"(",
"'CFG_VERSION'",
")",
",",
"cfg",
".",
"get",
"(",
"'CFG_SITE_URL'",
")",
",",
"cfg",
".",
"get",
"(... | Return a nice and uniform user-agent string to be used when Invenio
act as a client in HTTP requests. | [
"Return",
"a",
"nice",
"and",
"uniform",
"user",
"-",
"agent",
"string",
"to",
"be",
"used",
"when",
"Invenio",
"act",
"as",
"a",
"client",
"in",
"HTTP",
"requests",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/url.py#L605-L614 |
39,936 | inveniosoftware-attic/invenio-utils | invenio_utils/url.py | make_invenio_opener | def make_invenio_opener(component=None):
"""
Return an urllib2 opener with the useragent already set in the appropriate
way.
"""
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', make_user_agent_string(component))]
return opener | python | def make_invenio_opener(component=None):
"""
Return an urllib2 opener with the useragent already set in the appropriate
way.
"""
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', make_user_agent_string(component))]
return opener | [
"def",
"make_invenio_opener",
"(",
"component",
"=",
"None",
")",
":",
"opener",
"=",
"urllib2",
".",
"build_opener",
"(",
")",
"opener",
".",
"addheaders",
"=",
"[",
"(",
"'User-agent'",
",",
"make_user_agent_string",
"(",
"component",
")",
")",
"]",
"retur... | Return an urllib2 opener with the useragent already set in the appropriate
way. | [
"Return",
"an",
"urllib2",
"opener",
"with",
"the",
"useragent",
"already",
"set",
"in",
"the",
"appropriate",
"way",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/url.py#L633-L640 |
39,937 | inveniosoftware-attic/invenio-utils | invenio_utils/url.py | create_Indico_request_url | def create_Indico_request_url(
base_url,
indico_what,
indico_loc,
indico_id,
indico_type,
indico_params,
indico_key,
indico_sig,
_timestamp=None):
"""
Create a signed Indico request URL to access Indico HTTP Export APIs.
See U{http://i... | python | def create_Indico_request_url(
base_url,
indico_what,
indico_loc,
indico_id,
indico_type,
indico_params,
indico_key,
indico_sig,
_timestamp=None):
"""
Create a signed Indico request URL to access Indico HTTP Export APIs.
See U{http://i... | [
"def",
"create_Indico_request_url",
"(",
"base_url",
",",
"indico_what",
",",
"indico_loc",
",",
"indico_id",
",",
"indico_type",
",",
"indico_params",
",",
"indico_key",
",",
"indico_sig",
",",
"_timestamp",
"=",
"None",
")",
":",
"url",
"=",
"'/export/'",
"+",... | Create a signed Indico request URL to access Indico HTTP Export APIs.
See U{http://indico.cern.ch/ihelp/html/ExportAPI/index.html} for more
information.
Example:
>> create_Indico_request_url("https://indico.cern.ch",
"categ",
"",
... | [
"Create",
"a",
"signed",
"Indico",
"request",
"URL",
"to",
"access",
"Indico",
"HTTP",
"Export",
"APIs",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/url.py#L770-L852 |
39,938 | inveniosoftware-attic/invenio-utils | invenio_utils/url.py | auto_version_url | def auto_version_url(file_path):
""" Appends modification time of the file to the request URL in order for the
browser to refresh the cache when file changes
@param file_path: path to the file, e.g js/foo.js
@return: file_path with modification time appended to URL
"""
file_md5 = ""... | python | def auto_version_url(file_path):
""" Appends modification time of the file to the request URL in order for the
browser to refresh the cache when file changes
@param file_path: path to the file, e.g js/foo.js
@return: file_path with modification time appended to URL
"""
file_md5 = ""... | [
"def",
"auto_version_url",
"(",
"file_path",
")",
":",
"file_md5",
"=",
"\"\"",
"try",
":",
"file_md5",
"=",
"md5",
"(",
"open",
"(",
"cfg",
".",
"get",
"(",
"'CFG_WEBDIR'",
")",
"+",
"os",
".",
"sep",
"+",
"file_path",
")",
".",
"read",
"(",
")",
... | Appends modification time of the file to the request URL in order for the
browser to refresh the cache when file changes
@param file_path: path to the file, e.g js/foo.js
@return: file_path with modification time appended to URL | [
"Appends",
"modification",
"time",
"of",
"the",
"file",
"to",
"the",
"request",
"URL",
"in",
"order",
"for",
"the",
"browser",
"to",
"refresh",
"the",
"cache",
"when",
"file",
"changes"
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/url.py#L922-L935 |
39,939 | CodyKochmann/generators | generators/map.py | function_arg_count | def function_arg_count(fn):
""" returns how many arguments a funciton has """
assert callable(fn), 'function_arg_count needed a callable function, not {0}'.format(repr(fn))
if hasattr(fn, '__code__') and hasattr(fn.__code__, 'co_argcount'):
return fn.__code__.co_argcount
else:
return 1 | python | def function_arg_count(fn):
""" returns how many arguments a funciton has """
assert callable(fn), 'function_arg_count needed a callable function, not {0}'.format(repr(fn))
if hasattr(fn, '__code__') and hasattr(fn.__code__, 'co_argcount'):
return fn.__code__.co_argcount
else:
return 1 | [
"def",
"function_arg_count",
"(",
"fn",
")",
":",
"assert",
"callable",
"(",
"fn",
")",
",",
"'function_arg_count needed a callable function, not {0}'",
".",
"format",
"(",
"repr",
"(",
"fn",
")",
")",
"if",
"hasattr",
"(",
"fn",
",",
"'__code__'",
")",
"and",... | returns how many arguments a funciton has | [
"returns",
"how",
"many",
"arguments",
"a",
"funciton",
"has"
] | e4ca4dd25d5023a94b0349c69d6224070cc2526f | https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/map.py#L20-L26 |
39,940 | soaxelbrooke/join | join/_core.py | merge | def merge(left, right, how='inner', key=None, left_key=None, right_key=None,
left_as='left', right_as='right'):
""" Performs a join using the union join function. """
return join(left, right, how, key, left_key, right_key,
join_fn=make_union_join(left_as, right_as)) | python | def merge(left, right, how='inner', key=None, left_key=None, right_key=None,
left_as='left', right_as='right'):
""" Performs a join using the union join function. """
return join(left, right, how, key, left_key, right_key,
join_fn=make_union_join(left_as, right_as)) | [
"def",
"merge",
"(",
"left",
",",
"right",
",",
"how",
"=",
"'inner'",
",",
"key",
"=",
"None",
",",
"left_key",
"=",
"None",
",",
"right_key",
"=",
"None",
",",
"left_as",
"=",
"'left'",
",",
"right_as",
"=",
"'right'",
")",
":",
"return",
"join",
... | Performs a join using the union join function. | [
"Performs",
"a",
"join",
"using",
"the",
"union",
"join",
"function",
"."
] | c84fca68ab6a52b1cee526065dc9f5a691764e69 | https://github.com/soaxelbrooke/join/blob/c84fca68ab6a52b1cee526065dc9f5a691764e69/join/_core.py#L7-L11 |
39,941 | soaxelbrooke/join | join/_core.py | _inner_join | def _inner_join(left, right, left_key_fn, right_key_fn, join_fn=union_join):
""" Inner join using left and right key functions
:param left: left iterable to be joined
:param right: right iterable to be joined
:param function left_key_fn: function that produces hashable value from left objects
:para... | python | def _inner_join(left, right, left_key_fn, right_key_fn, join_fn=union_join):
""" Inner join using left and right key functions
:param left: left iterable to be joined
:param right: right iterable to be joined
:param function left_key_fn: function that produces hashable value from left objects
:para... | [
"def",
"_inner_join",
"(",
"left",
",",
"right",
",",
"left_key_fn",
",",
"right_key_fn",
",",
"join_fn",
"=",
"union_join",
")",
":",
"joiner",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"ele",
"in",
"right",
":",
"joiner",
"[",
"right_key_fn",
"(",
"... | Inner join using left and right key functions
:param left: left iterable to be joined
:param right: right iterable to be joined
:param function left_key_fn: function that produces hashable value from left objects
:param function right_key_fn: function that produces hashable value from right objects
... | [
"Inner",
"join",
"using",
"left",
"and",
"right",
"key",
"functions"
] | c84fca68ab6a52b1cee526065dc9f5a691764e69 | https://github.com/soaxelbrooke/join/blob/c84fca68ab6a52b1cee526065dc9f5a691764e69/join/_core.py#L47-L64 |
39,942 | soaxelbrooke/join | join/_core.py | group | def group(iterable, key=lambda ele: ele):
""" Groups an iterable by a specified attribute, or using a specified key access function. Returns tuples of grouped elements.
>>> dogs = [Dog('gatsby', 'Rruff!', 15), Dog('william', 'roof', 12), Dog('edward', 'hi', 15)]
>>> groupby(dogs, 'weight')
[(Dog('gats... | python | def group(iterable, key=lambda ele: ele):
""" Groups an iterable by a specified attribute, or using a specified key access function. Returns tuples of grouped elements.
>>> dogs = [Dog('gatsby', 'Rruff!', 15), Dog('william', 'roof', 12), Dog('edward', 'hi', 15)]
>>> groupby(dogs, 'weight')
[(Dog('gats... | [
"def",
"group",
"(",
"iterable",
",",
"key",
"=",
"lambda",
"ele",
":",
"ele",
")",
":",
"if",
"callable",
"(",
"key",
")",
":",
"return",
"_group",
"(",
"iterable",
",",
"key",
")",
"else",
":",
"return",
"_group",
"(",
"iterable",
",",
"make_key_fn... | Groups an iterable by a specified attribute, or using a specified key access function. Returns tuples of grouped elements.
>>> dogs = [Dog('gatsby', 'Rruff!', 15), Dog('william', 'roof', 12), Dog('edward', 'hi', 15)]
>>> groupby(dogs, 'weight')
[(Dog('gatsby', 'Rruff!', 15), Dog('edward', 'hi', 15)), (Dog... | [
"Groups",
"an",
"iterable",
"by",
"a",
"specified",
"attribute",
"or",
"using",
"a",
"specified",
"key",
"access",
"function",
".",
"Returns",
"tuples",
"of",
"grouped",
"elements",
"."
] | c84fca68ab6a52b1cee526065dc9f5a691764e69 | https://github.com/soaxelbrooke/join/blob/c84fca68ab6a52b1cee526065dc9f5a691764e69/join/_core.py#L125-L138 |
39,943 | wdbm/megaparsex | megaparsex.py | trigger_keyphrases | def trigger_keyphrases(
text = None, # input text to parse
keyphrases = None, # keyphrases for parsing input text
response = None, # optional text response on trigger
function = None, # optional function on trigger... | python | def trigger_keyphrases(
text = None, # input text to parse
keyphrases = None, # keyphrases for parsing input text
response = None, # optional text response on trigger
function = None, # optional function on trigger... | [
"def",
"trigger_keyphrases",
"(",
"text",
"=",
"None",
",",
"# input text to parse",
"keyphrases",
"=",
"None",
",",
"# keyphrases for parsing input text",
"response",
"=",
"None",
",",
"# optional text response on trigger",
"function",
"=",
"None",
",",
"# optional funct... | Parse input text for keyphrases. If any keyphrases are found, respond with
text or by seeking confirmation or by engaging a function with optional
keyword arguments. Return text or True if triggered and return False if not
triggered. If confirmation is required, a confirmation object is returned,
encaps... | [
"Parse",
"input",
"text",
"for",
"keyphrases",
".",
"If",
"any",
"keyphrases",
"are",
"found",
"respond",
"with",
"text",
"or",
"by",
"seeking",
"confirmation",
"or",
"by",
"engaging",
"a",
"function",
"with",
"optional",
"keyword",
"arguments",
".",
"Return",... | 59da05410aa1cf8682dcee2bf0bd0572fa42bd29 | https://github.com/wdbm/megaparsex/blob/59da05410aa1cf8682dcee2bf0bd0572fa42bd29/megaparsex.py#L51-L91 |
39,944 | wdbm/megaparsex | megaparsex.py | parse | def parse(
text = None,
humour = 75
):
"""
Parse input text using various triggers, some returning text and some for
engaging functions. If triggered, a trigger returns text or True if and if
not triggered, returns False. If no triggers are triggered, return False, if
one trigger is tr... | python | def parse(
text = None,
humour = 75
):
"""
Parse input text using various triggers, some returning text and some for
engaging functions. If triggered, a trigger returns text or True if and if
not triggered, returns False. If no triggers are triggered, return False, if
one trigger is tr... | [
"def",
"parse",
"(",
"text",
"=",
"None",
",",
"humour",
"=",
"75",
")",
":",
"triggers",
"=",
"[",
"]",
"# general",
"if",
"humour",
">=",
"75",
":",
"triggers",
".",
"extend",
"(",
"[",
"trigger_keyphrases",
"(",
"text",
"=",
"text",
",",
"keyphras... | Parse input text using various triggers, some returning text and some for
engaging functions. If triggered, a trigger returns text or True if and if
not triggered, returns False. If no triggers are triggered, return False, if
one trigger is triggered, return the value returned by that trigger, and if
mu... | [
"Parse",
"input",
"text",
"using",
"various",
"triggers",
"some",
"returning",
"text",
"and",
"some",
"for",
"engaging",
"functions",
".",
"If",
"triggered",
"a",
"trigger",
"returns",
"text",
"or",
"True",
"if",
"and",
"if",
"not",
"triggered",
"returns",
"... | 59da05410aa1cf8682dcee2bf0bd0572fa42bd29 | https://github.com/wdbm/megaparsex/blob/59da05410aa1cf8682dcee2bf0bd0572fa42bd29/megaparsex.py#L93-L230 |
39,945 | wdbm/megaparsex | megaparsex.py | multiparse | def multiparse(
text = None,
parsers = [parse],
help_message = None
):
"""
Parse input text by looping over a list of multiple parsers. If one trigger
is triggered, return the value returned by that trigger, if multiple
triggers are triggered, return a list of the values ret... | python | def multiparse(
text = None,
parsers = [parse],
help_message = None
):
"""
Parse input text by looping over a list of multiple parsers. If one trigger
is triggered, return the value returned by that trigger, if multiple
triggers are triggered, return a list of the values ret... | [
"def",
"multiparse",
"(",
"text",
"=",
"None",
",",
"parsers",
"=",
"[",
"parse",
"]",
",",
"help_message",
"=",
"None",
")",
":",
"responses",
"=",
"[",
"]",
"for",
"_parser",
"in",
"parsers",
":",
"response",
"=",
"_parser",
"(",
"text",
"=",
"text... | Parse input text by looping over a list of multiple parsers. If one trigger
is triggered, return the value returned by that trigger, if multiple
triggers are triggered, return a list of the values returned by those
triggers. If no triggers are triggered, return False or an optional help
message. | [
"Parse",
"input",
"text",
"by",
"looping",
"over",
"a",
"list",
"of",
"multiple",
"parsers",
".",
"If",
"one",
"trigger",
"is",
"triggered",
"return",
"the",
"value",
"returned",
"by",
"that",
"trigger",
"if",
"multiple",
"triggers",
"are",
"triggered",
"ret... | 59da05410aa1cf8682dcee2bf0bd0572fa42bd29 | https://github.com/wdbm/megaparsex/blob/59da05410aa1cf8682dcee2bf0bd0572fa42bd29/megaparsex.py#L273-L299 |
39,946 | wdbm/megaparsex | megaparsex.py | confirmation.run | def run(
self
):
"""
Engage contained function with optional keyword arguments.
"""
if self._function and not self._kwargs:
return self._function()
if self._function and self._kwargs:
return self._function(**self._kwargs) | python | def run(
self
):
"""
Engage contained function with optional keyword arguments.
"""
if self._function and not self._kwargs:
return self._function()
if self._function and self._kwargs:
return self._function(**self._kwargs) | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"self",
".",
"_function",
"and",
"not",
"self",
".",
"_kwargs",
":",
"return",
"self",
".",
"_function",
"(",
")",
"if",
"self",
".",
"_function",
"and",
"self",
".",
"_kwargs",
":",
"return",
"self",
".",
... | Engage contained function with optional keyword arguments. | [
"Engage",
"contained",
"function",
"with",
"optional",
"keyword",
"arguments",
"."
] | 59da05410aa1cf8682dcee2bf0bd0572fa42bd29 | https://github.com/wdbm/megaparsex/blob/59da05410aa1cf8682dcee2bf0bd0572fa42bd29/megaparsex.py#L373-L382 |
39,947 | tradenity/python-sdk | tradenity/resources/tax_settings.py | TaxSettings.tax_class_based_on | def tax_class_based_on(self, tax_class_based_on):
"""Sets the tax_class_based_on of this TaxSettings.
:param tax_class_based_on: The tax_class_based_on of this TaxSettings.
:type: str
"""
allowed_values = ["shippingAddress", "billingAddress"] # noqa: E501
if tax_class_... | python | def tax_class_based_on(self, tax_class_based_on):
"""Sets the tax_class_based_on of this TaxSettings.
:param tax_class_based_on: The tax_class_based_on of this TaxSettings.
:type: str
"""
allowed_values = ["shippingAddress", "billingAddress"] # noqa: E501
if tax_class_... | [
"def",
"tax_class_based_on",
"(",
"self",
",",
"tax_class_based_on",
")",
":",
"allowed_values",
"=",
"[",
"\"shippingAddress\"",
",",
"\"billingAddress\"",
"]",
"# noqa: E501",
"if",
"tax_class_based_on",
"is",
"not",
"None",
"and",
"tax_class_based_on",
"not",
"in",... | Sets the tax_class_based_on of this TaxSettings.
:param tax_class_based_on: The tax_class_based_on of this TaxSettings.
:type: str | [
"Sets",
"the",
"tax_class_based_on",
"of",
"this",
"TaxSettings",
"."
] | d13fbe23f4d6ff22554c6d8d2deaf209371adaf1 | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/tax_settings.py#L78-L92 |
39,948 | alexcepoi/cake | cake/lib.py | recurse_up | def recurse_up(directory, filename):
"""
Recursive walk a directory up to root until it contains `filename`
"""
directory = osp.abspath(directory)
while True:
searchfile = osp.join(directory, filename)
if osp.isfile(searchfile):
return directory
if directory == '/': break
else: directory = osp.dirna... | python | def recurse_up(directory, filename):
"""
Recursive walk a directory up to root until it contains `filename`
"""
directory = osp.abspath(directory)
while True:
searchfile = osp.join(directory, filename)
if osp.isfile(searchfile):
return directory
if directory == '/': break
else: directory = osp.dirna... | [
"def",
"recurse_up",
"(",
"directory",
",",
"filename",
")",
":",
"directory",
"=",
"osp",
".",
"abspath",
"(",
"directory",
")",
"while",
"True",
":",
"searchfile",
"=",
"osp",
".",
"join",
"(",
"directory",
",",
"filename",
")",
"if",
"osp",
".",
"is... | Recursive walk a directory up to root until it contains `filename` | [
"Recursive",
"walk",
"a",
"directory",
"up",
"to",
"root",
"until",
"it",
"contains",
"filename"
] | 0fde58dfea1fdbfd632816d5850b47cb0f9ece64 | https://github.com/alexcepoi/cake/blob/0fde58dfea1fdbfd632816d5850b47cb0f9ece64/cake/lib.py#L73-L88 |
39,949 | inveniosoftware-attic/invenio-utils | invenio_utils/xmlhelpers.py | etree_to_dict | def etree_to_dict(tree):
"""Translate etree into dictionary.
:param tree: etree dictionary object
:type tree: <http://lxml.de/api/lxml.etree-module.html>
"""
d = {tree.tag.split('}')[1]: map(
etree_to_dict, tree.iterchildren()
) or tree.text}
return d | python | def etree_to_dict(tree):
"""Translate etree into dictionary.
:param tree: etree dictionary object
:type tree: <http://lxml.de/api/lxml.etree-module.html>
"""
d = {tree.tag.split('}')[1]: map(
etree_to_dict, tree.iterchildren()
) or tree.text}
return d | [
"def",
"etree_to_dict",
"(",
"tree",
")",
":",
"d",
"=",
"{",
"tree",
".",
"tag",
".",
"split",
"(",
"'}'",
")",
"[",
"1",
"]",
":",
"map",
"(",
"etree_to_dict",
",",
"tree",
".",
"iterchildren",
"(",
")",
")",
"or",
"tree",
".",
"text",
"}",
"... | Translate etree into dictionary.
:param tree: etree dictionary object
:type tree: <http://lxml.de/api/lxml.etree-module.html> | [
"Translate",
"etree",
"into",
"dictionary",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/xmlhelpers.py#L23-L34 |
39,950 | inveniosoftware-attic/invenio-utils | invenio_utils/filedownload.py | finalize_download | def finalize_download(url, download_to_file, content_type, request):
"""
Finalizes the download operation by doing various checks, such as format
type, size check etc.
"""
# If format is given, a format check is performed.
if content_type and content_type not in request.headers['content-type']:
... | python | def finalize_download(url, download_to_file, content_type, request):
"""
Finalizes the download operation by doing various checks, such as format
type, size check etc.
"""
# If format is given, a format check is performed.
if content_type and content_type not in request.headers['content-type']:
... | [
"def",
"finalize_download",
"(",
"url",
",",
"download_to_file",
",",
"content_type",
",",
"request",
")",
":",
"# If format is given, a format check is performed.",
"if",
"content_type",
"and",
"content_type",
"not",
"in",
"request",
".",
"headers",
"[",
"'content-type... | Finalizes the download operation by doing various checks, such as format
type, size check etc. | [
"Finalizes",
"the",
"download",
"operation",
"by",
"doing",
"various",
"checks",
"such",
"as",
"format",
"type",
"size",
"check",
"etc",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/filedownload.py#L218-L250 |
39,951 | inveniosoftware-attic/invenio-utils | invenio_utils/filedownload.py | download_local_file | def download_local_file(filename, download_to_file):
"""
Copies a local file to Invenio's temporary directory.
@param filename: the name of the file to copy
@type filename: string
@param download_to_file: the path to save the file to
@type download_to_file: string
@return: the path of the... | python | def download_local_file(filename, download_to_file):
"""
Copies a local file to Invenio's temporary directory.
@param filename: the name of the file to copy
@type filename: string
@param download_to_file: the path to save the file to
@type download_to_file: string
@return: the path of the... | [
"def",
"download_local_file",
"(",
"filename",
",",
"download_to_file",
")",
":",
"# Try to copy.",
"try",
":",
"path",
"=",
"urllib2",
".",
"urlparse",
".",
"urlsplit",
"(",
"urllib",
".",
"unquote",
"(",
"filename",
")",
")",
"[",
"2",
"]",
"if",
"os",
... | Copies a local file to Invenio's temporary directory.
@param filename: the name of the file to copy
@type filename: string
@param download_to_file: the path to save the file to
@type download_to_file: string
@return: the path of the temporary file created
@rtype: string
@raise StandardErr... | [
"Copies",
"a",
"local",
"file",
"to",
"Invenio",
"s",
"temporary",
"directory",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/filedownload.py#L253-L295 |
39,952 | inveniosoftware-attic/invenio-utils | invenio_utils/filedownload.py | safe_mkstemp | def safe_mkstemp(suffix, prefix='filedownloadutils_'):
"""Create a temporary filename that don't have any '.' inside a part
from the suffix."""
tmpfd, tmppath = tempfile.mkstemp(
suffix=suffix,
prefix=prefix,
dir=current_app.config['CFG_TMPSHAREDDIR']
)
# Close the file and l... | python | def safe_mkstemp(suffix, prefix='filedownloadutils_'):
"""Create a temporary filename that don't have any '.' inside a part
from the suffix."""
tmpfd, tmppath = tempfile.mkstemp(
suffix=suffix,
prefix=prefix,
dir=current_app.config['CFG_TMPSHAREDDIR']
)
# Close the file and l... | [
"def",
"safe_mkstemp",
"(",
"suffix",
",",
"prefix",
"=",
"'filedownloadutils_'",
")",
":",
"tmpfd",
",",
"tmppath",
"=",
"tempfile",
".",
"mkstemp",
"(",
"suffix",
"=",
"suffix",
",",
"prefix",
"=",
"prefix",
",",
"dir",
"=",
"current_app",
".",
"config",... | Create a temporary filename that don't have any '.' inside a part
from the suffix. | [
"Create",
"a",
"temporary",
"filename",
"that",
"don",
"t",
"have",
"any",
".",
"inside",
"a",
"part",
"from",
"the",
"suffix",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/filedownload.py#L304-L327 |
39,953 | inveniosoftware-attic/invenio-utils | invenio_utils/filedownload.py | open_url | def open_url(url, headers=None):
"""
Opens a URL. If headers are passed as argument, no check is performed and
the URL will be opened.
@param url: the URL to open
@type url: string
@param headers: the headers to use
@type headers: dictionary
@return: a file-like object as returned by ... | python | def open_url(url, headers=None):
"""
Opens a URL. If headers are passed as argument, no check is performed and
the URL will be opened.
@param url: the URL to open
@type url: string
@param headers: the headers to use
@type headers: dictionary
@return: a file-like object as returned by ... | [
"def",
"open_url",
"(",
"url",
",",
"headers",
"=",
"None",
")",
":",
"request",
"=",
"urllib2",
".",
"Request",
"(",
"url",
")",
"if",
"headers",
":",
"for",
"key",
",",
"value",
"in",
"headers",
".",
"items",
"(",
")",
":",
"request",
".",
"add_h... | Opens a URL. If headers are passed as argument, no check is performed and
the URL will be opened.
@param url: the URL to open
@type url: string
@param headers: the headers to use
@type headers: dictionary
@return: a file-like object as returned by urllib2.urlopen. | [
"Opens",
"a",
"URL",
".",
"If",
"headers",
"are",
"passed",
"as",
"argument",
"no",
"check",
"is",
"performed",
"and",
"the",
"URL",
"will",
"be",
"opened",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/filedownload.py#L330-L347 |
39,954 | kellerza/pyqwikswitch | pyqwikswitch/async_.py | QSUsb.get_json | async def get_json(self, url, timeout=30, astext=False, exceptions=False):
"""Get URL and parse JSON from text."""
try:
with async_timeout.timeout(timeout):
res = await self._aio_session.get(url)
if res.status != 200:
_LOGGER.error("QSUSB r... | python | async def get_json(self, url, timeout=30, astext=False, exceptions=False):
"""Get URL and parse JSON from text."""
try:
with async_timeout.timeout(timeout):
res = await self._aio_session.get(url)
if res.status != 200:
_LOGGER.error("QSUSB r... | [
"async",
"def",
"get_json",
"(",
"self",
",",
"url",
",",
"timeout",
"=",
"30",
",",
"astext",
"=",
"False",
",",
"exceptions",
"=",
"False",
")",
":",
"try",
":",
"with",
"async_timeout",
".",
"timeout",
"(",
"timeout",
")",
":",
"res",
"=",
"await"... | Get URL and parse JSON from text. | [
"Get",
"URL",
"and",
"parse",
"JSON",
"from",
"text",
"."
] | 9d4f080048221eaee93e3eefcf641919ff1af586 | https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/async_.py#L38-L61 |
39,955 | kellerza/pyqwikswitch | pyqwikswitch/async_.py | QSUsb.stop | def stop(self):
"""Stop listening."""
self._running = False
if self._sleep_task:
self._sleep_task.cancel()
self._sleep_task = None | python | def stop(self):
"""Stop listening."""
self._running = False
if self._sleep_task:
self._sleep_task.cancel()
self._sleep_task = None | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_running",
"=",
"False",
"if",
"self",
".",
"_sleep_task",
":",
"self",
".",
"_sleep_task",
".",
"cancel",
"(",
")",
"self",
".",
"_sleep_task",
"=",
"None"
] | Stop listening. | [
"Stop",
"listening",
"."
] | 9d4f080048221eaee93e3eefcf641919ff1af586 | https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/async_.py#L63-L68 |
39,956 | kellerza/pyqwikswitch | pyqwikswitch/async_.py | QSUsb._async_listen | async def _async_listen(self, callback=None):
"""Listen loop."""
while True:
if not self._running:
return
try:
packet = await self.get_json(
URL_LISTEN.format(self._url), timeout=30, exceptions=True)
except asyncio.... | python | async def _async_listen(self, callback=None):
"""Listen loop."""
while True:
if not self._running:
return
try:
packet = await self.get_json(
URL_LISTEN.format(self._url), timeout=30, exceptions=True)
except asyncio.... | [
"async",
"def",
"_async_listen",
"(",
"self",
",",
"callback",
"=",
"None",
")",
":",
"while",
"True",
":",
"if",
"not",
"self",
".",
"_running",
":",
"return",
"try",
":",
"packet",
"=",
"await",
"self",
".",
"get_json",
"(",
"URL_LISTEN",
".",
"forma... | Listen loop. | [
"Listen",
"loop",
"."
] | 9d4f080048221eaee93e3eefcf641919ff1af586 | https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/async_.py#L79-L108 |
39,957 | ThomasChiroux/attowiki | src/attowiki/tools.py | attowiki_distro_path | def attowiki_distro_path():
"""return the absolute complete path where attowiki is located
.. todo:: use pkg_resources ?
"""
attowiki_path = os.path.abspath(__file__)
if attowiki_path[-1] != '/':
attowiki_path = attowiki_path[:attowiki_path.rfind('/')]
else:
attowiki_path = atto... | python | def attowiki_distro_path():
"""return the absolute complete path where attowiki is located
.. todo:: use pkg_resources ?
"""
attowiki_path = os.path.abspath(__file__)
if attowiki_path[-1] != '/':
attowiki_path = attowiki_path[:attowiki_path.rfind('/')]
else:
attowiki_path = atto... | [
"def",
"attowiki_distro_path",
"(",
")",
":",
"attowiki_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
"if",
"attowiki_path",
"[",
"-",
"1",
"]",
"!=",
"'/'",
":",
"attowiki_path",
"=",
"attowiki_path",
"[",
":",
"attowiki_path",
".",... | return the absolute complete path where attowiki is located
.. todo:: use pkg_resources ? | [
"return",
"the",
"absolute",
"complete",
"path",
"where",
"attowiki",
"is",
"located"
] | 6c93c420305490d324fdc95a7b40b2283a222183 | https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/tools.py#L30-L40 |
39,958 | claymcleod/celcius | lib/celcius/unix/commands/crontab.py | crontab.build_command | def build_command(self):
"""Build out the crontab command"""
return cron_utils.cronify("crontab -l | {{ cat; echo \"{} {} {} {} {} CJOBID='{}' MAILTO='' {}\"; }} | crontab - > /dev/null".format(self._minute, self._hour, self._day_of_month, self._month_of_year, self._day_of_week, self._jobid, self._comma... | python | def build_command(self):
"""Build out the crontab command"""
return cron_utils.cronify("crontab -l | {{ cat; echo \"{} {} {} {} {} CJOBID='{}' MAILTO='' {}\"; }} | crontab - > /dev/null".format(self._minute, self._hour, self._day_of_month, self._month_of_year, self._day_of_week, self._jobid, self._comma... | [
"def",
"build_command",
"(",
"self",
")",
":",
"return",
"cron_utils",
".",
"cronify",
"(",
"\"crontab -l | {{ cat; echo \\\"{} {} {} {} {} CJOBID='{}' MAILTO='' {}\\\"; }} | crontab - > /dev/null\"",
".",
"format",
"(",
"self",
".",
"_minute",
",",
"self",
".",
"_hour",
... | Build out the crontab command | [
"Build",
"out",
"the",
"crontab",
"command"
] | e46a3c1ba112af9de23360d1455ab1e037a38ea1 | https://github.com/claymcleod/celcius/blob/e46a3c1ba112af9de23360d1455ab1e037a38ea1/lib/celcius/unix/commands/crontab.py#L37-L39 |
39,959 | Aluriak/bubble-tools | bubbletools/utils.py | infer_format | def infer_format(filename:str) -> str:
"""Return extension identifying format of given filename"""
_, ext = os.path.splitext(filename)
return ext | python | def infer_format(filename:str) -> str:
"""Return extension identifying format of given filename"""
_, ext = os.path.splitext(filename)
return ext | [
"def",
"infer_format",
"(",
"filename",
":",
"str",
")",
"->",
"str",
":",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"return",
"ext"
] | Return extension identifying format of given filename | [
"Return",
"extension",
"identifying",
"format",
"of",
"given",
"filename"
] | f014f4a1986abefc80dc418feaa05ed258c2221a | https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/utils.py#L19-L22 |
39,960 | Aluriak/bubble-tools | bubbletools/utils.py | reversed_graph | def reversed_graph(graph:dict) -> dict:
"""Return given graph reversed"""
ret = defaultdict(set)
for node, succs in graph.items():
for succ in succs:
ret[succ].add(node)
return dict(ret) | python | def reversed_graph(graph:dict) -> dict:
"""Return given graph reversed"""
ret = defaultdict(set)
for node, succs in graph.items():
for succ in succs:
ret[succ].add(node)
return dict(ret) | [
"def",
"reversed_graph",
"(",
"graph",
":",
"dict",
")",
"->",
"dict",
":",
"ret",
"=",
"defaultdict",
"(",
"set",
")",
"for",
"node",
",",
"succs",
"in",
"graph",
".",
"items",
"(",
")",
":",
"for",
"succ",
"in",
"succs",
":",
"ret",
"[",
"succ",
... | Return given graph reversed | [
"Return",
"given",
"graph",
"reversed"
] | f014f4a1986abefc80dc418feaa05ed258c2221a | https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/utils.py#L25-L31 |
39,961 | Aluriak/bubble-tools | bubbletools/utils.py | have_cycle | def have_cycle(graph:dict) -> frozenset:
"""Perform a topologic sort to detect any cycle.
Return the set of unsortable nodes. If at least one item,
then there is cycle in given graph.
"""
# topological sort
walked = set() # walked nodes
nodes = frozenset(it.chain(it.chain.from_iterable(gr... | python | def have_cycle(graph:dict) -> frozenset:
"""Perform a topologic sort to detect any cycle.
Return the set of unsortable nodes. If at least one item,
then there is cycle in given graph.
"""
# topological sort
walked = set() # walked nodes
nodes = frozenset(it.chain(it.chain.from_iterable(gr... | [
"def",
"have_cycle",
"(",
"graph",
":",
"dict",
")",
"->",
"frozenset",
":",
"# topological sort",
"walked",
"=",
"set",
"(",
")",
"# walked nodes",
"nodes",
"=",
"frozenset",
"(",
"it",
".",
"chain",
"(",
"it",
".",
"chain",
".",
"from_iterable",
"(",
"... | Perform a topologic sort to detect any cycle.
Return the set of unsortable nodes. If at least one item,
then there is cycle in given graph. | [
"Perform",
"a",
"topologic",
"sort",
"to",
"detect",
"any",
"cycle",
"."
] | f014f4a1986abefc80dc418feaa05ed258c2221a | https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/utils.py#L64-L81 |
39,962 | Aluriak/bubble-tools | bubbletools/utils.py | file_lines | def file_lines(bblfile:str) -> iter:
"""Yield lines found in given file"""
with open(bblfile) as fd:
yield from (line.rstrip() for line in fd if line.rstrip()) | python | def file_lines(bblfile:str) -> iter:
"""Yield lines found in given file"""
with open(bblfile) as fd:
yield from (line.rstrip() for line in fd if line.rstrip()) | [
"def",
"file_lines",
"(",
"bblfile",
":",
"str",
")",
"->",
"iter",
":",
"with",
"open",
"(",
"bblfile",
")",
"as",
"fd",
":",
"yield",
"from",
"(",
"line",
".",
"rstrip",
"(",
")",
"for",
"line",
"in",
"fd",
"if",
"line",
".",
"rstrip",
"(",
")"... | Yield lines found in given file | [
"Yield",
"lines",
"found",
"in",
"given",
"file"
] | f014f4a1986abefc80dc418feaa05ed258c2221a | https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/utils.py#L84-L87 |
39,963 | Aluriak/bubble-tools | bubbletools/utils.py | line_type | def line_type(line:str) -> str:
"""Give type of input line, as defined in LINE_TYPES
>>> line_type('IN\\ta\\tb')
'IN'
>>> line_type('')
'EMPTY'
"""
for regex, ltype in LINE_TYPES.items():
if re.fullmatch(regex, line):
return ltype
raise ValueError("Input line \"{}\"... | python | def line_type(line:str) -> str:
"""Give type of input line, as defined in LINE_TYPES
>>> line_type('IN\\ta\\tb')
'IN'
>>> line_type('')
'EMPTY'
"""
for regex, ltype in LINE_TYPES.items():
if re.fullmatch(regex, line):
return ltype
raise ValueError("Input line \"{}\"... | [
"def",
"line_type",
"(",
"line",
":",
"str",
")",
"->",
"str",
":",
"for",
"regex",
",",
"ltype",
"in",
"LINE_TYPES",
".",
"items",
"(",
")",
":",
"if",
"re",
".",
"fullmatch",
"(",
"regex",
",",
"line",
")",
":",
"return",
"ltype",
"raise",
"Value... | Give type of input line, as defined in LINE_TYPES
>>> line_type('IN\\ta\\tb')
'IN'
>>> line_type('')
'EMPTY' | [
"Give",
"type",
"of",
"input",
"line",
"as",
"defined",
"in",
"LINE_TYPES"
] | f014f4a1986abefc80dc418feaa05ed258c2221a | https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/utils.py#L90-L102 |
39,964 | Aluriak/bubble-tools | bubbletools/utils.py | line_data | def line_data(line:str) -> tuple:
"""Return groups found in given line
>>> line_data('IN\\ta\\tb')
('IN', 'a', 'b')
>>> line_data('')
()
"""
for regex, _ in LINE_TYPES.items():
match = re.fullmatch(regex, line)
if match:
return match.groups()
raise ValueErro... | python | def line_data(line:str) -> tuple:
"""Return groups found in given line
>>> line_data('IN\\ta\\tb')
('IN', 'a', 'b')
>>> line_data('')
()
"""
for regex, _ in LINE_TYPES.items():
match = re.fullmatch(regex, line)
if match:
return match.groups()
raise ValueErro... | [
"def",
"line_data",
"(",
"line",
":",
"str",
")",
"->",
"tuple",
":",
"for",
"regex",
",",
"_",
"in",
"LINE_TYPES",
".",
"items",
"(",
")",
":",
"match",
"=",
"re",
".",
"fullmatch",
"(",
"regex",
",",
"line",
")",
"if",
"match",
":",
"return",
"... | Return groups found in given line
>>> line_data('IN\\ta\\tb')
('IN', 'a', 'b')
>>> line_data('')
() | [
"Return",
"groups",
"found",
"in",
"given",
"line"
] | f014f4a1986abefc80dc418feaa05ed258c2221a | https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/utils.py#L105-L118 |
39,965 | mobinrg/rpi_spark_drives | JMRPiSpark/Drives/Screen/SSPILScreen.py | SSPILScreen._initBuffer | def _initBuffer(self, bufferColorMode, bufferSize):
"""!
\~english
Initialize the buffer object instance, use PIL Image as for buffer
@param bufferColorMode: "RGB" or "1"
@param bufferSize: (width, height)
\~chinese
初始化缓冲区对象实例,使用PIL Image作为缓冲区
@param buffe... | python | def _initBuffer(self, bufferColorMode, bufferSize):
"""!
\~english
Initialize the buffer object instance, use PIL Image as for buffer
@param bufferColorMode: "RGB" or "1"
@param bufferSize: (width, height)
\~chinese
初始化缓冲区对象实例,使用PIL Image作为缓冲区
@param buffe... | [
"def",
"_initBuffer",
"(",
"self",
",",
"bufferColorMode",
",",
"bufferSize",
")",
":",
"# super(SSScreenBase)._initBuffer(bufferColorMode, bufferSize)",
"self",
".",
"_buffer_color_mode",
"=",
"bufferColorMode",
"#create screen image buffer and canvas",
"if",
"bufferSize",
"==... | !
\~english
Initialize the buffer object instance, use PIL Image as for buffer
@param bufferColorMode: "RGB" or "1"
@param bufferSize: (width, height)
\~chinese
初始化缓冲区对象实例,使用PIL Image作为缓冲区
@param bufferColorMode: 色彩模式, 取值: "RGB" 或 "1"
@param bufferSize: 缓存... | [
"!",
"\\",
"~english",
"Initialize",
"the",
"buffer",
"object",
"instance",
"use",
"PIL",
"Image",
"as",
"for",
"buffer"
] | e1602d8268a5ef48e9e0a8b37de89e0233f946ea | https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Screen/SSPILScreen.py#L88-L110 |
39,966 | mobinrg/rpi_spark_drives | JMRPiSpark/Drives/Screen/SSPILScreen.py | SSPILScreen.clearCanvas | def clearCanvas(self, fillColor = 0 ):
"""!
\~engliash
Clear up canvas and fill color at same time
@param fillColor: a color value
@note
The fillColor value range depends on the setting of _buffer_color_mode.
* If it is SS_COLOR_MODE_MONO ("1") monochrom... | python | def clearCanvas(self, fillColor = 0 ):
"""!
\~engliash
Clear up canvas and fill color at same time
@param fillColor: a color value
@note
The fillColor value range depends on the setting of _buffer_color_mode.
* If it is SS_COLOR_MODE_MONO ("1") monochrom... | [
"def",
"clearCanvas",
"(",
"self",
",",
"fillColor",
"=",
"0",
")",
":",
"self",
".",
"Canvas",
".",
"rectangle",
"(",
"(",
"0",
",",
"0",
",",
"self",
".",
"_display_size",
"[",
"0",
"]",
",",
"self",
".",
"_display_size",
"[",
"1",
"]",
")",
",... | !
\~engliash
Clear up canvas and fill color at same time
@param fillColor: a color value
@note
The fillColor value range depends on the setting of _buffer_color_mode.
* If it is SS_COLOR_MODE_MONO ("1") monochrome mode, it can only select 0: black and 1: white
... | [
"!",
"\\",
"~engliash",
"Clear",
"up",
"canvas",
"and",
"fill",
"color",
"at",
"same",
"time"
] | e1602d8268a5ef48e9e0a8b37de89e0233f946ea | https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Screen/SSPILScreen.py#L120-L137 |
39,967 | mobinrg/rpi_spark_drives | JMRPiSpark/Drives/Screen/SScreen.py | SSRect.resize | def resize(self, newWidth = 0, newHeight = 0):
"""!
\~english
Resize width and height of rectangles
@param newWidth: new width value
@param newHeight: new height value
\~chinese
重新设定矩形高宽
@param newWidth: 新宽度
@param newHeight: 新高度
"""
... | python | def resize(self, newWidth = 0, newHeight = 0):
"""!
\~english
Resize width and height of rectangles
@param newWidth: new width value
@param newHeight: new height value
\~chinese
重新设定矩形高宽
@param newWidth: 新宽度
@param newHeight: 新高度
"""
... | [
"def",
"resize",
"(",
"self",
",",
"newWidth",
"=",
"0",
",",
"newHeight",
"=",
"0",
")",
":",
"self",
".",
"height",
"=",
"newHeight",
"self",
".",
"width",
"=",
"newWidth"
] | !
\~english
Resize width and height of rectangles
@param newWidth: new width value
@param newHeight: new height value
\~chinese
重新设定矩形高宽
@param newWidth: 新宽度
@param newHeight: 新高度 | [
"!",
"\\",
"~english",
"Resize",
"width",
"and",
"height",
"of",
"rectangles"
] | e1602d8268a5ef48e9e0a8b37de89e0233f946ea | https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Screen/SScreen.py#L67-L79 |
39,968 | mobinrg/rpi_spark_drives | JMRPiSpark/Drives/Screen/SScreen.py | SScreenBase.rotateDirection | def rotateDirection(self, displayDirection):
"""!
\~english rotate screen direction
@param displayDirection: Screen Direction. value can be chosen: 0, 90, 180, 270
\~chinese 旋转显示屏方向
@param displayDirection: 显示屏方向。可选值: 0, 90, 180, 270
\~
@note
\~en... | python | def rotateDirection(self, displayDirection):
"""!
\~english rotate screen direction
@param displayDirection: Screen Direction. value can be chosen: 0, 90, 180, 270
\~chinese 旋转显示屏方向
@param displayDirection: 显示屏方向。可选值: 0, 90, 180, 270
\~
@note
\~en... | [
"def",
"rotateDirection",
"(",
"self",
",",
"displayDirection",
")",
":",
"if",
"self",
".",
"_needSwapWH",
"(",
"self",
".",
"_display_direction",
",",
"displayDirection",
")",
":",
"self",
".",
"_display_size",
"=",
"(",
"self",
".",
"_display_size",
"[",
... | !
\~english rotate screen direction
@param displayDirection: Screen Direction. value can be chosen: 0, 90, 180, 270
\~chinese 旋转显示屏方向
@param displayDirection: 显示屏方向。可选值: 0, 90, 180, 270
\~
@note
\~english after rotate the View resize to screen size
... | [
"!",
"\\",
"~english",
"rotate",
"screen",
"direction"
] | e1602d8268a5ef48e9e0a8b37de89e0233f946ea | https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Screen/SScreen.py#L261-L278 |
39,969 | inveniosoftware-attic/invenio-utils | invenio_utils/autodiscovery/__init__.py | autodiscover_modules | def autodiscover_modules(packages, related_name_re='.+',
ignore_exceptions=False):
"""Autodiscover function follows the pattern used by Celery.
:param packages: List of package names to auto discover modules in.
:type packages: list of str
:param related_name_re: Regular expres... | python | def autodiscover_modules(packages, related_name_re='.+',
ignore_exceptions=False):
"""Autodiscover function follows the pattern used by Celery.
:param packages: List of package names to auto discover modules in.
:type packages: list of str
:param related_name_re: Regular expres... | [
"def",
"autodiscover_modules",
"(",
"packages",
",",
"related_name_re",
"=",
"'.+'",
",",
"ignore_exceptions",
"=",
"False",
")",
":",
"warnings",
".",
"warn",
"(",
"'autodiscover_modules has been deprecated. '",
"'Use Flask-Registry instead.'",
",",
"DeprecationWarning",
... | Autodiscover function follows the pattern used by Celery.
:param packages: List of package names to auto discover modules in.
:type packages: list of str
:param related_name_re: Regular expression used to match modules names.
:type related_name_re: str
:param ignore_exceptions: Ignore exception whe... | [
"Autodiscover",
"function",
"follows",
"the",
"pattern",
"used",
"by",
"Celery",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/autodiscovery/__init__.py#L41-L73 |
39,970 | inveniosoftware-attic/invenio-utils | invenio_utils/autodiscovery/__init__.py | find_related_modules | def find_related_modules(package, related_name_re='.+',
ignore_exceptions=False):
"""Find matching modules using a package and a module name pattern."""
warnings.warn('find_related_modules has been deprecated.',
DeprecationWarning)
package_elements = package.rsplit... | python | def find_related_modules(package, related_name_re='.+',
ignore_exceptions=False):
"""Find matching modules using a package and a module name pattern."""
warnings.warn('find_related_modules has been deprecated.',
DeprecationWarning)
package_elements = package.rsplit... | [
"def",
"find_related_modules",
"(",
"package",
",",
"related_name_re",
"=",
"'.+'",
",",
"ignore_exceptions",
"=",
"False",
")",
":",
"warnings",
".",
"warn",
"(",
"'find_related_modules has been deprecated.'",
",",
"DeprecationWarning",
")",
"package_elements",
"=",
... | Find matching modules using a package and a module name pattern. | [
"Find",
"matching",
"modules",
"using",
"a",
"package",
"and",
"a",
"module",
"name",
"pattern",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/autodiscovery/__init__.py#L76-L105 |
39,971 | inveniosoftware-attic/invenio-utils | invenio_utils/autodiscovery/__init__.py | import_related_module | def import_related_module(package, pkg_path, related_name,
ignore_exceptions=False):
"""Import module from given path."""
try:
imp.find_module(related_name, pkg_path)
except ImportError:
return
try:
return getattr(
__import__('%s' % (package... | python | def import_related_module(package, pkg_path, related_name,
ignore_exceptions=False):
"""Import module from given path."""
try:
imp.find_module(related_name, pkg_path)
except ImportError:
return
try:
return getattr(
__import__('%s' % (package... | [
"def",
"import_related_module",
"(",
"package",
",",
"pkg_path",
",",
"related_name",
",",
"ignore_exceptions",
"=",
"False",
")",
":",
"try",
":",
"imp",
".",
"find_module",
"(",
"related_name",
",",
"pkg_path",
")",
"except",
"ImportError",
":",
"return",
"t... | Import module from given path. | [
"Import",
"module",
"from",
"given",
"path",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/autodiscovery/__init__.py#L108-L127 |
39,972 | alexcepoi/cake | cake/color.py | ansi | def ansi(string, *args):
""" Convenience function to chain multiple ColorWrappers to a string """
ansi = ''
for arg in args:
arg = str(arg)
if not re.match(ANSI_PATTERN, arg):
raise ValueError('Additional arguments must be ansi strings')
ansi += arg
return ansi + string + colorama.Style.RESET_ALL | python | def ansi(string, *args):
""" Convenience function to chain multiple ColorWrappers to a string """
ansi = ''
for arg in args:
arg = str(arg)
if not re.match(ANSI_PATTERN, arg):
raise ValueError('Additional arguments must be ansi strings')
ansi += arg
return ansi + string + colorama.Style.RESET_ALL | [
"def",
"ansi",
"(",
"string",
",",
"*",
"args",
")",
":",
"ansi",
"=",
"''",
"for",
"arg",
"in",
"args",
":",
"arg",
"=",
"str",
"(",
"arg",
")",
"if",
"not",
"re",
".",
"match",
"(",
"ANSI_PATTERN",
",",
"arg",
")",
":",
"raise",
"ValueError",
... | Convenience function to chain multiple ColorWrappers to a string | [
"Convenience",
"function",
"to",
"chain",
"multiple",
"ColorWrappers",
"to",
"a",
"string"
] | 0fde58dfea1fdbfd632816d5850b47cb0f9ece64 | https://github.com/alexcepoi/cake/blob/0fde58dfea1fdbfd632816d5850b47cb0f9ece64/cake/color.py#L52-L64 |
39,973 | alexcepoi/cake | cake/color.py | puts | def puts(*args, **kwargs):
"""
Full feature printing function featuring
trimming and padding for both files and ttys
"""
# parse kwargs
trim = kwargs.pop('trim', False)
padding = kwargs.pop('padding', None)
stream = kwargs.pop('stream', sys.stdout)
# HACK: check if stream is IndentedFile
indent = getatt... | python | def puts(*args, **kwargs):
"""
Full feature printing function featuring
trimming and padding for both files and ttys
"""
# parse kwargs
trim = kwargs.pop('trim', False)
padding = kwargs.pop('padding', None)
stream = kwargs.pop('stream', sys.stdout)
# HACK: check if stream is IndentedFile
indent = getatt... | [
"def",
"puts",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# parse kwargs",
"trim",
"=",
"kwargs",
".",
"pop",
"(",
"'trim'",
",",
"False",
")",
"padding",
"=",
"kwargs",
".",
"pop",
"(",
"'padding'",
",",
"None",
")",
"stream",
"=",
"kwa... | Full feature printing function featuring
trimming and padding for both files and ttys | [
"Full",
"feature",
"printing",
"function",
"featuring",
"trimming",
"and",
"padding",
"for",
"both",
"files",
"and",
"ttys"
] | 0fde58dfea1fdbfd632816d5850b47cb0f9ece64 | https://github.com/alexcepoi/cake/blob/0fde58dfea1fdbfd632816d5850b47cb0f9ece64/cake/color.py#L67-L133 |
39,974 | chaosim/dao | dao/builtins/terminal.py | char_between | def char_between(lower, upper, func_name):
'''return current char and step if char is between lower and upper, where
@test: a python function with one argument, which tests on one char and return True or False
@test must be registered with register_function'''
function = register_function(func_na... | python | def char_between(lower, upper, func_name):
'''return current char and step if char is between lower and upper, where
@test: a python function with one argument, which tests on one char and return True or False
@test must be registered with register_function'''
function = register_function(func_na... | [
"def",
"char_between",
"(",
"lower",
",",
"upper",
",",
"func_name",
")",
":",
"function",
"=",
"register_function",
"(",
"func_name",
",",
"lambda",
"char",
":",
"lower",
"<=",
"char",
"<=",
"upper",
")",
"return",
"char_on_predicate",
"(",
"function",
")"
... | return current char and step if char is between lower and upper, where
@test: a python function with one argument, which tests on one char and return True or False
@test must be registered with register_function | [
"return",
"current",
"char",
"and",
"step",
"if",
"char",
"is",
"between",
"lower",
"and",
"upper",
"where"
] | d7ba65c98ee063aefd1ff4eabb192d1536fdbaaa | https://github.com/chaosim/dao/blob/d7ba65c98ee063aefd1ff4eabb192d1536fdbaaa/dao/builtins/terminal.py#L82-L88 |
39,975 | chaosim/dao | dao/builtins/terminal.py | char_in | def char_in(string, func_name):
'''return current char and step if char is in string, where
@test: a python function with one argument, which tests on one char and return True or False
@test must be registered with register_function'''
function = register_function(func_name,
... | python | def char_in(string, func_name):
'''return current char and step if char is in string, where
@test: a python function with one argument, which tests on one char and return True or False
@test must be registered with register_function'''
function = register_function(func_name,
... | [
"def",
"char_in",
"(",
"string",
",",
"func_name",
")",
":",
"function",
"=",
"register_function",
"(",
"func_name",
",",
"lambda",
"char",
":",
"char",
"in",
"string",
")",
"return",
"char_on_predicate",
"(",
"function",
")"
] | return current char and step if char is in string, where
@test: a python function with one argument, which tests on one char and return True or False
@test must be registered with register_function | [
"return",
"current",
"char",
"and",
"step",
"if",
"char",
"is",
"in",
"string",
"where"
] | d7ba65c98ee063aefd1ff4eabb192d1536fdbaaa | https://github.com/chaosim/dao/blob/d7ba65c98ee063aefd1ff4eabb192d1536fdbaaa/dao/builtins/terminal.py#L90-L96 |
39,976 | devopsconsulting/vdt.version | vdt/version/repo.py | GitRepository.update_version | def update_version(self, version, step=1):
"Compute an new version and write it as a tag"
# update the version based on the flags passed.
if self.config.patch:
version.patch += step
if self.config.minor:
version.minor += step
if self.config.major:
... | python | def update_version(self, version, step=1):
"Compute an new version and write it as a tag"
# update the version based on the flags passed.
if self.config.patch:
version.patch += step
if self.config.minor:
version.minor += step
if self.config.major:
... | [
"def",
"update_version",
"(",
"self",
",",
"version",
",",
"step",
"=",
"1",
")",
":",
"# update the version based on the flags passed.",
"if",
"self",
".",
"config",
".",
"patch",
":",
"version",
".",
"patch",
"+=",
"step",
"if",
"self",
".",
"config",
".",... | Compute an new version and write it as a tag | [
"Compute",
"an",
"new",
"version",
"and",
"write",
"it",
"as",
"a",
"tag"
] | 25854ac9e1a26f1c7d31c26fd012781f05570574 | https://github.com/devopsconsulting/vdt.version/blob/25854ac9e1a26f1c7d31c26fd012781f05570574/vdt/version/repo.py#L32-L53 |
39,977 | trevisanj/a99 | a99/gui/a_WDBRegistry.py | WDBRegistry._get_id | def _get_id(self):
"""Getter because using the id property from within was not working"""
ret = None
row = self.row
if row:
ret = row["id"]
return ret | python | def _get_id(self):
"""Getter because using the id property from within was not working"""
ret = None
row = self.row
if row:
ret = row["id"]
return ret | [
"def",
"_get_id",
"(",
"self",
")",
":",
"ret",
"=",
"None",
"row",
"=",
"self",
".",
"row",
"if",
"row",
":",
"ret",
"=",
"row",
"[",
"\"id\"",
"]",
"return",
"ret"
] | Getter because using the id property from within was not working | [
"Getter",
"because",
"using",
"the",
"id",
"property",
"from",
"within",
"was",
"not",
"working"
] | 193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539 | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/gui/a_WDBRegistry.py#L195-L201 |
39,978 | CodyKochmann/generators | generators/performance_tools.py | time_pipeline | def time_pipeline(iterable, *steps):
'''
This times the steps in a pipeline. Give it an iterable to test against
followed by the steps of the pipeline seperated in individual functions.
Example Usage:
```
from random import choice, randint
l = [randint(0,50) for i in range(100)]
step1 = lambda iterab... | python | def time_pipeline(iterable, *steps):
'''
This times the steps in a pipeline. Give it an iterable to test against
followed by the steps of the pipeline seperated in individual functions.
Example Usage:
```
from random import choice, randint
l = [randint(0,50) for i in range(100)]
step1 = lambda iterab... | [
"def",
"time_pipeline",
"(",
"iterable",
",",
"*",
"steps",
")",
":",
"if",
"callable",
"(",
"iterable",
")",
":",
"try",
":",
"iter",
"(",
"iterable",
"(",
")",
")",
"callable_base",
"=",
"True",
"except",
":",
"raise",
"TypeError",
"(",
"'time_pipeline... | This times the steps in a pipeline. Give it an iterable to test against
followed by the steps of the pipeline seperated in individual functions.
Example Usage:
```
from random import choice, randint
l = [randint(0,50) for i in range(100)]
step1 = lambda iterable:(i for i in iterable if i%5==0)
step2 ... | [
"This",
"times",
"the",
"steps",
"in",
"a",
"pipeline",
".",
"Give",
"it",
"an",
"iterable",
"to",
"test",
"against",
"followed",
"by",
"the",
"steps",
"of",
"the",
"pipeline",
"seperated",
"in",
"individual",
"functions",
"."
] | e4ca4dd25d5023a94b0349c69d6224070cc2526f | https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/performance_tools.py#L48-L141 |
39,979 | CodyKochmann/generators | generators/performance_tools.py | runs_per_second | def runs_per_second(generator, seconds=3):
'''
use this function as a profiler for both functions and generators
to see how many iterations or cycles they can run per second
Example usage for timing simple operations/functions:
```
print(runs_per_second(lambda:1+2))
# 2074558
print(runs_per_second(... | python | def runs_per_second(generator, seconds=3):
'''
use this function as a profiler for both functions and generators
to see how many iterations or cycles they can run per second
Example usage for timing simple operations/functions:
```
print(runs_per_second(lambda:1+2))
# 2074558
print(runs_per_second(... | [
"def",
"runs_per_second",
"(",
"generator",
",",
"seconds",
"=",
"3",
")",
":",
"assert",
"isinstance",
"(",
"seconds",
",",
"int",
")",
",",
"'runs_per_second needs seconds to be an int, not {}'",
".",
"format",
"(",
"repr",
"(",
"seconds",
")",
")",
"assert",
... | use this function as a profiler for both functions and generators
to see how many iterations or cycles they can run per second
Example usage for timing simple operations/functions:
```
print(runs_per_second(lambda:1+2))
# 2074558
print(runs_per_second(lambda:1-2))
# 2048523
print(runs_per_second... | [
"use",
"this",
"function",
"as",
"a",
"profiler",
"for",
"both",
"functions",
"and",
"generators",
"to",
"see",
"how",
"many",
"iterations",
"or",
"cycles",
"they",
"can",
"run",
"per",
"second"
] | e4ca4dd25d5023a94b0349c69d6224070cc2526f | https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/performance_tools.py#L145-L206 |
39,980 | Titan-C/slaveparticles | slaveparticles/spins.py | fermion_avg | def fermion_avg(efermi, norm_hopping, func):
"""calcules for every slave it's average over the desired observable"""
if func == 'ekin':
func = bethe_ekin_zeroT
elif func == 'ocupation':
func = bethe_filling_zeroT
return np.asarray([func(ef, tz) for ef, tz in zip(efermi, norm_hopping)]) | python | def fermion_avg(efermi, norm_hopping, func):
"""calcules for every slave it's average over the desired observable"""
if func == 'ekin':
func = bethe_ekin_zeroT
elif func == 'ocupation':
func = bethe_filling_zeroT
return np.asarray([func(ef, tz) for ef, tz in zip(efermi, norm_hopping)]) | [
"def",
"fermion_avg",
"(",
"efermi",
",",
"norm_hopping",
",",
"func",
")",
":",
"if",
"func",
"==",
"'ekin'",
":",
"func",
"=",
"bethe_ekin_zeroT",
"elif",
"func",
"==",
"'ocupation'",
":",
"func",
"=",
"bethe_filling_zeroT",
"return",
"np",
".",
"asarray",... | calcules for every slave it's average over the desired observable | [
"calcules",
"for",
"every",
"slave",
"it",
"s",
"average",
"over",
"the",
"desired",
"observable"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L25-L32 |
39,981 | Titan-C/slaveparticles | slaveparticles/spins.py | spinflipandhop | def spinflipandhop(slaves):
"""Calculates the interaction term of a spin flip and pair hopping"""
Sdw = [csr_matrix(spin_gen(slaves, i, 0)) for i in range(slaves)]
Sup = [mat.T for mat in Sdw]
sfh = np.zeros_like(Sup[0])
orbitals = slaves//2
for n in range(orbitals):
for m in range(n+1... | python | def spinflipandhop(slaves):
"""Calculates the interaction term of a spin flip and pair hopping"""
Sdw = [csr_matrix(spin_gen(slaves, i, 0)) for i in range(slaves)]
Sup = [mat.T for mat in Sdw]
sfh = np.zeros_like(Sup[0])
orbitals = slaves//2
for n in range(orbitals):
for m in range(n+1... | [
"def",
"spinflipandhop",
"(",
"slaves",
")",
":",
"Sdw",
"=",
"[",
"csr_matrix",
"(",
"spin_gen",
"(",
"slaves",
",",
"i",
",",
"0",
")",
")",
"for",
"i",
"in",
"range",
"(",
"slaves",
")",
"]",
"Sup",
"=",
"[",
"mat",
".",
"T",
"for",
"mat",
"... | Calculates the interaction term of a spin flip and pair hopping | [
"Calculates",
"the",
"interaction",
"term",
"of",
"a",
"spin",
"flip",
"and",
"pair",
"hopping"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L42-L58 |
39,982 | Titan-C/slaveparticles | slaveparticles/spins.py | spin_z_op | def spin_z_op(param, oper):
"""Generates the required Sz operators, given the system parameter setup
and the operator dictionary"""
slaves = param['slaves']
oper['Sz'] = np.array([spin_z(slaves, spin) for spin in range(slaves)])
oper['Sz+1/2'] = oper['Sz'] + 0.5*np.eye(2**slaves)
oper['sumSz2... | python | def spin_z_op(param, oper):
"""Generates the required Sz operators, given the system parameter setup
and the operator dictionary"""
slaves = param['slaves']
oper['Sz'] = np.array([spin_z(slaves, spin) for spin in range(slaves)])
oper['Sz+1/2'] = oper['Sz'] + 0.5*np.eye(2**slaves)
oper['sumSz2... | [
"def",
"spin_z_op",
"(",
"param",
",",
"oper",
")",
":",
"slaves",
"=",
"param",
"[",
"'slaves'",
"]",
"oper",
"[",
"'Sz'",
"]",
"=",
"np",
".",
"array",
"(",
"[",
"spin_z",
"(",
"slaves",
",",
"spin",
")",
"for",
"spin",
"in",
"range",
"(",
"sla... | Generates the required Sz operators, given the system parameter setup
and the operator dictionary | [
"Generates",
"the",
"required",
"Sz",
"operators",
"given",
"the",
"system",
"parameter",
"setup",
"and",
"the",
"operator",
"dictionary"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L61-L70 |
39,983 | Titan-C/slaveparticles | slaveparticles/spins.py | spin_gen_op | def spin_gen_op(oper, gauge):
"""Generates the generic spin matrices for the system"""
slaves = len(gauge)
oper['O'] = np.array([spin_gen(slaves, i, c) for i, c in enumerate(gauge)])
oper['O_d'] = np.transpose(oper['O'], (0, 2, 1))
oper['O_dO'] = np.einsum('...ij,...jk->...ik', oper['O_d'], oper['O'... | python | def spin_gen_op(oper, gauge):
"""Generates the generic spin matrices for the system"""
slaves = len(gauge)
oper['O'] = np.array([spin_gen(slaves, i, c) for i, c in enumerate(gauge)])
oper['O_d'] = np.transpose(oper['O'], (0, 2, 1))
oper['O_dO'] = np.einsum('...ij,...jk->...ik', oper['O_d'], oper['O'... | [
"def",
"spin_gen_op",
"(",
"oper",
",",
"gauge",
")",
":",
"slaves",
"=",
"len",
"(",
"gauge",
")",
"oper",
"[",
"'O'",
"]",
"=",
"np",
".",
"array",
"(",
"[",
"spin_gen",
"(",
"slaves",
",",
"i",
",",
"c",
")",
"for",
"i",
",",
"c",
"in",
"e... | Generates the generic spin matrices for the system | [
"Generates",
"the",
"generic",
"spin",
"matrices",
"for",
"the",
"system"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L73-L79 |
39,984 | Titan-C/slaveparticles | slaveparticles/spins.py | Spinon.set_filling | def set_filling(self, populations):
"""Sets the orbital enenergies for on the reference of the free case.
By setting the desired local populations on every orbital.
Then generate the necesary operators to respect such configuraion"""
populations = np.asarray(populations)
#
# s... | python | def set_filling(self, populations):
"""Sets the orbital enenergies for on the reference of the free case.
By setting the desired local populations on every orbital.
Then generate the necesary operators to respect such configuraion"""
populations = np.asarray(populations)
#
# s... | [
"def",
"set_filling",
"(",
"self",
",",
"populations",
")",
":",
"populations",
"=",
"np",
".",
"asarray",
"(",
"populations",
")",
"#",
"# self.param['orbital_e'] -= bethe_findfill_zeroT( \\",
"# self.param['avg_particles'],",
"# ... | Sets the orbital enenergies for on the reference of the free case.
By setting the desired local populations on every orbital.
Then generate the necesary operators to respect such configuraion | [
"Sets",
"the",
"orbital",
"enenergies",
"for",
"on",
"the",
"reference",
"of",
"the",
"free",
"case",
".",
"By",
"setting",
"the",
"desired",
"local",
"populations",
"on",
"every",
"orbital",
".",
"Then",
"generate",
"the",
"necesary",
"operators",
"to",
"re... | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L127-L143 |
39,985 | Titan-C/slaveparticles | slaveparticles/spins.py | Spinon.reset | def reset(self, populations, lag, mu, u_int, j_coup, mean_f):
"""Resets the system into the last known state as given by the input
values"""
self.set_filling(populations)
self.param['lambda'] = lag
self.param['orbital_e'] = mu
self.selfconsistency(u_int, j_coup, mean_... | python | def reset(self, populations, lag, mu, u_int, j_coup, mean_f):
"""Resets the system into the last known state as given by the input
values"""
self.set_filling(populations)
self.param['lambda'] = lag
self.param['orbital_e'] = mu
self.selfconsistency(u_int, j_coup, mean_... | [
"def",
"reset",
"(",
"self",
",",
"populations",
",",
"lag",
",",
"mu",
",",
"u_int",
",",
"j_coup",
",",
"mean_f",
")",
":",
"self",
".",
"set_filling",
"(",
"populations",
")",
"self",
".",
"param",
"[",
"'lambda'",
"]",
"=",
"lag",
"self",
".",
... | Resets the system into the last known state as given by the input
values | [
"Resets",
"the",
"system",
"into",
"the",
"last",
"known",
"state",
"as",
"given",
"by",
"the",
"input",
"values"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L145-L152 |
39,986 | Titan-C/slaveparticles | slaveparticles/spins.py | Spinon.update_H | def update_H(self, mean_field, l):
"""Updates the spin hamiltonian and recalculates its eigenbasis"""
self.H_s = self.spin_hamiltonian(mean_field, l)
try:
self.eig_energies, self.eig_states = diagonalize(self.H_s)
except np.linalg.linalg.LinAlgError:
np.savez('er... | python | def update_H(self, mean_field, l):
"""Updates the spin hamiltonian and recalculates its eigenbasis"""
self.H_s = self.spin_hamiltonian(mean_field, l)
try:
self.eig_energies, self.eig_states = diagonalize(self.H_s)
except np.linalg.linalg.LinAlgError:
np.savez('er... | [
"def",
"update_H",
"(",
"self",
",",
"mean_field",
",",
"l",
")",
":",
"self",
".",
"H_s",
"=",
"self",
".",
"spin_hamiltonian",
"(",
"mean_field",
",",
"l",
")",
"try",
":",
"self",
".",
"eig_energies",
",",
"self",
".",
"eig_states",
"=",
"diagonaliz... | Updates the spin hamiltonian and recalculates its eigenbasis | [
"Updates",
"the",
"spin",
"hamiltonian",
"and",
"recalculates",
"its",
"eigenbasis"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L154-L166 |
39,987 | Titan-C/slaveparticles | slaveparticles/spins.py | Spinon.spin_hamiltonian | def spin_hamiltonian(self, h, l):
"""Constructs the single site spin Hamiltonian"""
h_spin = np.einsum('i,ijk', h[1], self.oper['O'])
h_spin += np.einsum('i,ijk', h[0], self.oper['O_d'])
h_spin += np.einsum('i,ijk', l, self.oper['Sz+1/2'])
h_spin += self.oper['Hint']
re... | python | def spin_hamiltonian(self, h, l):
"""Constructs the single site spin Hamiltonian"""
h_spin = np.einsum('i,ijk', h[1], self.oper['O'])
h_spin += np.einsum('i,ijk', h[0], self.oper['O_d'])
h_spin += np.einsum('i,ijk', l, self.oper['Sz+1/2'])
h_spin += self.oper['Hint']
re... | [
"def",
"spin_hamiltonian",
"(",
"self",
",",
"h",
",",
"l",
")",
":",
"h_spin",
"=",
"np",
".",
"einsum",
"(",
"'i,ijk'",
",",
"h",
"[",
"1",
"]",
",",
"self",
".",
"oper",
"[",
"'O'",
"]",
")",
"h_spin",
"+=",
"np",
".",
"einsum",
"(",
"'i,ijk... | Constructs the single site spin Hamiltonian | [
"Constructs",
"the",
"single",
"site",
"spin",
"Hamiltonian"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L168-L175 |
39,988 | Titan-C/slaveparticles | slaveparticles/spins.py | Spinon.inter_spin_hamiltonian | def inter_spin_hamiltonian(self, u_int, J_coup):
"""Calculates the interaction Hamiltonian. The Hund coupling is a
fraction of the coulom interaction"""
J_coup *= u_int
h_int = (u_int - 2*J_coup)/2.*self.oper['sumSz2']
h_int += J_coup*self.oper['sumSz-sp2']
h_int -= J... | python | def inter_spin_hamiltonian(self, u_int, J_coup):
"""Calculates the interaction Hamiltonian. The Hund coupling is a
fraction of the coulom interaction"""
J_coup *= u_int
h_int = (u_int - 2*J_coup)/2.*self.oper['sumSz2']
h_int += J_coup*self.oper['sumSz-sp2']
h_int -= J... | [
"def",
"inter_spin_hamiltonian",
"(",
"self",
",",
"u_int",
",",
"J_coup",
")",
":",
"J_coup",
"*=",
"u_int",
"h_int",
"=",
"(",
"u_int",
"-",
"2",
"*",
"J_coup",
")",
"/",
"2.",
"*",
"self",
".",
"oper",
"[",
"'sumSz2'",
"]",
"h_int",
"+=",
"J_coup"... | Calculates the interaction Hamiltonian. The Hund coupling is a
fraction of the coulom interaction | [
"Calculates",
"the",
"interaction",
"Hamiltonian",
".",
"The",
"Hund",
"coupling",
"is",
"a",
"fraction",
"of",
"the",
"coulom",
"interaction"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L177-L186 |
39,989 | Titan-C/slaveparticles | slaveparticles/spins.py | Spinon.expected | def expected(self, observable, beta=1e5):
"""Wrapper to the expected_value function to fix the eigenbasis"""
return expected_value(observable,
self.eig_energies,
self.eig_states,
beta) | python | def expected(self, observable, beta=1e5):
"""Wrapper to the expected_value function to fix the eigenbasis"""
return expected_value(observable,
self.eig_energies,
self.eig_states,
beta) | [
"def",
"expected",
"(",
"self",
",",
"observable",
",",
"beta",
"=",
"1e5",
")",
":",
"return",
"expected_value",
"(",
"observable",
",",
"self",
".",
"eig_energies",
",",
"self",
".",
"eig_states",
",",
"beta",
")"
] | Wrapper to the expected_value function to fix the eigenbasis | [
"Wrapper",
"to",
"the",
"expected_value",
"function",
"to",
"fix",
"the",
"eigenbasis"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L188-L193 |
39,990 | Titan-C/slaveparticles | slaveparticles/spins.py | Spinon.quasiparticle_weight | def quasiparticle_weight(self):
"""Calculates quasiparticle weight"""
return np.array([self.expected(op)**2 for op in self.oper['O']]) | python | def quasiparticle_weight(self):
"""Calculates quasiparticle weight"""
return np.array([self.expected(op)**2 for op in self.oper['O']]) | [
"def",
"quasiparticle_weight",
"(",
"self",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"self",
".",
"expected",
"(",
"op",
")",
"**",
"2",
"for",
"op",
"in",
"self",
".",
"oper",
"[",
"'O'",
"]",
"]",
")"
] | Calculates quasiparticle weight | [
"Calculates",
"quasiparticle",
"weight"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L195-L197 |
39,991 | Titan-C/slaveparticles | slaveparticles/spins.py | Spinon.mean_field | def mean_field(self):
"""Calculates mean field"""
mean_field = []
for sp_oper in [self.oper['O'], self.oper['O_d']]:
avgO = np.array([self.expected(op) for op in sp_oper])
avgO[abs(avgO) < 1e-10] = 0.
mean_field.append(avgO*self.param['ekin'])
return ... | python | def mean_field(self):
"""Calculates mean field"""
mean_field = []
for sp_oper in [self.oper['O'], self.oper['O_d']]:
avgO = np.array([self.expected(op) for op in sp_oper])
avgO[abs(avgO) < 1e-10] = 0.
mean_field.append(avgO*self.param['ekin'])
return ... | [
"def",
"mean_field",
"(",
"self",
")",
":",
"mean_field",
"=",
"[",
"]",
"for",
"sp_oper",
"in",
"[",
"self",
".",
"oper",
"[",
"'O'",
"]",
",",
"self",
".",
"oper",
"[",
"'O_d'",
"]",
"]",
":",
"avgO",
"=",
"np",
".",
"array",
"(",
"[",
"self"... | Calculates mean field | [
"Calculates",
"mean",
"field"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L199-L207 |
39,992 | Titan-C/slaveparticles | slaveparticles/spins.py | Spinon.selfconsistency | def selfconsistency(self, u_int, J_coup, mean_field_prev=None):
"""Iterates over the hamiltonian to get the stable selfcosistent one"""
if mean_field_prev is None:
mean_field_prev = np.array([self.param['ekin']]*2)
hlog = [mean_field_prev]
self.oper['Hint'] = self.inter_spin... | python | def selfconsistency(self, u_int, J_coup, mean_field_prev=None):
"""Iterates over the hamiltonian to get the stable selfcosistent one"""
if mean_field_prev is None:
mean_field_prev = np.array([self.param['ekin']]*2)
hlog = [mean_field_prev]
self.oper['Hint'] = self.inter_spin... | [
"def",
"selfconsistency",
"(",
"self",
",",
"u_int",
",",
"J_coup",
",",
"mean_field_prev",
"=",
"None",
")",
":",
"if",
"mean_field_prev",
"is",
"None",
":",
"mean_field_prev",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"param",
"[",
"'ekin'",
"]",... | Iterates over the hamiltonian to get the stable selfcosistent one | [
"Iterates",
"over",
"the",
"hamiltonian",
"to",
"get",
"the",
"stable",
"selfcosistent",
"one"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L209-L235 |
39,993 | Titan-C/slaveparticles | slaveparticles/spins.py | Spinon.restriction | def restriction(self, lam, mean_field):
"""Lagrange multiplier in lattice slave spin"""
self.update_H(mean_field, lam)
restric = np.array([self.expected(op) - n for op, n in zip(self.oper['Sz+1/2'], self.param['populations'])])
return restric | python | def restriction(self, lam, mean_field):
"""Lagrange multiplier in lattice slave spin"""
self.update_H(mean_field, lam)
restric = np.array([self.expected(op) - n for op, n in zip(self.oper['Sz+1/2'], self.param['populations'])])
return restric | [
"def",
"restriction",
"(",
"self",
",",
"lam",
",",
"mean_field",
")",
":",
"self",
".",
"update_H",
"(",
"mean_field",
",",
"lam",
")",
"restric",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"expected",
"(",
"op",
")",
"-",
"n",
"for",
"op",
... | Lagrange multiplier in lattice slave spin | [
"Lagrange",
"multiplier",
"in",
"lattice",
"slave",
"spin"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L237-L241 |
39,994 | evocell/rabifier | rabifier/utils.py | run_cmd | def run_cmd(cmd, out=os.path.devnull, err=os.path.devnull):
"""Runs an external command
:param list cmd: Command to run.
:param str out: Output file
:param str err: Error file
:raises: RuntimeError
"""
logger.debug(' '.join(cmd))
with open(out, 'w') as hout:
proc = subprocess.P... | python | def run_cmd(cmd, out=os.path.devnull, err=os.path.devnull):
"""Runs an external command
:param list cmd: Command to run.
:param str out: Output file
:param str err: Error file
:raises: RuntimeError
"""
logger.debug(' '.join(cmd))
with open(out, 'w') as hout:
proc = subprocess.P... | [
"def",
"run_cmd",
"(",
"cmd",
",",
"out",
"=",
"os",
".",
"path",
".",
"devnull",
",",
"err",
"=",
"os",
".",
"path",
".",
"devnull",
")",
":",
"logger",
".",
"debug",
"(",
"' '",
".",
"join",
"(",
"cmd",
")",
")",
"with",
"open",
"(",
"out",
... | Runs an external command
:param list cmd: Command to run.
:param str out: Output file
:param str err: Error file
:raises: RuntimeError | [
"Runs",
"an",
"external",
"command"
] | a5be3d516517e555bde463b94f06aeed106d19b8 | https://github.com/evocell/rabifier/blob/a5be3d516517e555bde463b94f06aeed106d19b8/rabifier/utils.py#L85-L103 |
39,995 | evocell/rabifier | rabifier/utils.py | run_cmd_if_file_missing | def run_cmd_if_file_missing(cmd, fname, out=os.path.devnull, err=os.path.devnull):
"""Runs an external command if file is absent.
:param list cmd: Command to run.
:param str fname: Path to the file, which existence is being checked.
:param str out: Output file
:param str err: Error file
:return... | python | def run_cmd_if_file_missing(cmd, fname, out=os.path.devnull, err=os.path.devnull):
"""Runs an external command if file is absent.
:param list cmd: Command to run.
:param str fname: Path to the file, which existence is being checked.
:param str out: Output file
:param str err: Error file
:return... | [
"def",
"run_cmd_if_file_missing",
"(",
"cmd",
",",
"fname",
",",
"out",
"=",
"os",
".",
"path",
".",
"devnull",
",",
"err",
"=",
"os",
".",
"path",
".",
"devnull",
")",
":",
"if",
"fname",
"is",
"None",
"or",
"not",
"os",
".",
"path",
".",
"exists"... | Runs an external command if file is absent.
:param list cmd: Command to run.
:param str fname: Path to the file, which existence is being checked.
:param str out: Output file
:param str err: Error file
:return: True if cmd was executed, False otherwise
:rtype: boolean | [
"Runs",
"an",
"external",
"command",
"if",
"file",
"is",
"absent",
"."
] | a5be3d516517e555bde463b94f06aeed106d19b8 | https://github.com/evocell/rabifier/blob/a5be3d516517e555bde463b94f06aeed106d19b8/rabifier/utils.py#L106-L121 |
39,996 | evocell/rabifier | rabifier/utils.py | merge_files | def merge_files(sources, destination):
"""Copy content of multiple files into a single file.
:param list(str) sources: source file names (paths)
:param str destination: destination file name (path)
:return:
"""
with open(destination, 'w') as hout:
for f in sources:
if os.pa... | python | def merge_files(sources, destination):
"""Copy content of multiple files into a single file.
:param list(str) sources: source file names (paths)
:param str destination: destination file name (path)
:return:
"""
with open(destination, 'w') as hout:
for f in sources:
if os.pa... | [
"def",
"merge_files",
"(",
"sources",
",",
"destination",
")",
":",
"with",
"open",
"(",
"destination",
",",
"'w'",
")",
"as",
"hout",
":",
"for",
"f",
"in",
"sources",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"f",
")",
":",
"with",
"open"... | Copy content of multiple files into a single file.
:param list(str) sources: source file names (paths)
:param str destination: destination file name (path)
:return: | [
"Copy",
"content",
"of",
"multiple",
"files",
"into",
"a",
"single",
"file",
"."
] | a5be3d516517e555bde463b94f06aeed106d19b8 | https://github.com/evocell/rabifier/blob/a5be3d516517e555bde463b94f06aeed106d19b8/rabifier/utils.py#L124-L138 |
39,997 | evocell/rabifier | rabifier/utils.py | Pathfinder.add_path | def add_path(self, path):
""" Adds a new path to the list of searchable paths
:param path: new path
"""
if os.path.exists(path):
self.paths.add(path)
return path
else:
#logger.debug('Path {} doesn\'t exist'.format(path))
return No... | python | def add_path(self, path):
""" Adds a new path to the list of searchable paths
:param path: new path
"""
if os.path.exists(path):
self.paths.add(path)
return path
else:
#logger.debug('Path {} doesn\'t exist'.format(path))
return No... | [
"def",
"add_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"self",
".",
"paths",
".",
"add",
"(",
"path",
")",
"return",
"path",
"else",
":",
"#logger.debug('Path {} doesn\\'t exist'.format(path))"... | Adds a new path to the list of searchable paths
:param path: new path | [
"Adds",
"a",
"new",
"path",
"to",
"the",
"list",
"of",
"searchable",
"paths"
] | a5be3d516517e555bde463b94f06aeed106d19b8 | https://github.com/evocell/rabifier/blob/a5be3d516517e555bde463b94f06aeed106d19b8/rabifier/utils.py#L46-L57 |
39,998 | evocell/rabifier | rabifier/utils.py | Pathfinder.get | def get(self, name):
""" Looks for a name in the path.
:param name: file name
:return: path to the file
"""
for d in self.paths:
if os.path.exists(d) and name in os.listdir(d):
return os.path.join(d, name)
logger.debug('File not found {}'.for... | python | def get(self, name):
""" Looks for a name in the path.
:param name: file name
:return: path to the file
"""
for d in self.paths:
if os.path.exists(d) and name in os.listdir(d):
return os.path.join(d, name)
logger.debug('File not found {}'.for... | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"for",
"d",
"in",
"self",
".",
"paths",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"d",
")",
"and",
"name",
"in",
"os",
".",
"listdir",
"(",
"d",
")",
":",
"return",
"os",
".",
"path",
... | Looks for a name in the path.
:param name: file name
:return: path to the file | [
"Looks",
"for",
"a",
"name",
"in",
"the",
"path",
"."
] | a5be3d516517e555bde463b94f06aeed106d19b8 | https://github.com/evocell/rabifier/blob/a5be3d516517e555bde463b94f06aeed106d19b8/rabifier/utils.py#L62-L73 |
39,999 | wuher/devil | devil/resource.py | Resource.__handle_request | def __handle_request(self, request, *args, **kw):
""" Intercept the request and response.
This function lets `HttpStatusCodeError`s fall through. They
are caught and transformed into HTTP responses by the caller.
:return: ``HttpResponse``
"""
self._authenticate(request... | python | def __handle_request(self, request, *args, **kw):
""" Intercept the request and response.
This function lets `HttpStatusCodeError`s fall through. They
are caught and transformed into HTTP responses by the caller.
:return: ``HttpResponse``
"""
self._authenticate(request... | [
"def",
"__handle_request",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"_authenticate",
"(",
"request",
")",
"self",
".",
"_check_permission",
"(",
"request",
")",
"method",
"=",
"self",
".",
"_get_method",
... | Intercept the request and response.
This function lets `HttpStatusCodeError`s fall through. They
are caught and transformed into HTTP responses by the caller.
:return: ``HttpResponse`` | [
"Intercept",
"the",
"request",
"and",
"response",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/resource.py#L111-L126 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.