repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
bretth/woven | woven/deployment.py | mkdirs | def mkdirs(remote_dir, use_sudo=False):
"""
Wrapper around mkdir -pv
Returns a list of directories created
"""
func = use_sudo and sudo or run
result = func(' '.join(['mkdir -pv',remote_dir])).split('\n')
#extract dir list from ["mkdir: created directory `example.com/some/dir'"]
if ... | python | def mkdirs(remote_dir, use_sudo=False):
"""
Wrapper around mkdir -pv
Returns a list of directories created
"""
func = use_sudo and sudo or run
result = func(' '.join(['mkdir -pv',remote_dir])).split('\n')
#extract dir list from ["mkdir: created directory `example.com/some/dir'"]
if ... | [
"def",
"mkdirs",
"(",
"remote_dir",
",",
"use_sudo",
"=",
"False",
")",
":",
"func",
"=",
"use_sudo",
"and",
"sudo",
"or",
"run",
"result",
"=",
"func",
"(",
"' '",
".",
"join",
"(",
"[",
"'mkdir -pv'",
",",
"remote_dir",
"]",
")",
")",
".",
"split",... | Wrapper around mkdir -pv
Returns a list of directories created | [
"Wrapper",
"around",
"mkdir",
"-",
"pv",
"Returns",
"a",
"list",
"of",
"directories",
"created"
] | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/deployment.py#L149-L159 |
bretth/woven | woven/deployment.py | upload_template | def upload_template(filename, destination, context={}, use_sudo=False, backup=True, modified_only=False):
"""
Render and upload a template text file to a remote host using the Django
template api.
``filename`` should be the Django template name.
``context`` is the Django template dictionar... | python | def upload_template(filename, destination, context={}, use_sudo=False, backup=True, modified_only=False):
"""
Render and upload a template text file to a remote host using the Django
template api.
``filename`` should be the Django template name.
``context`` is the Django template dictionar... | [
"def",
"upload_template",
"(",
"filename",
",",
"destination",
",",
"context",
"=",
"{",
"}",
",",
"use_sudo",
"=",
"False",
",",
"backup",
"=",
"True",
",",
"modified_only",
"=",
"False",
")",
":",
"#Replaces the default fabric.contrib.files.upload_template",
"ba... | Render and upload a template text file to a remote host using the Django
template api.
``filename`` should be the Django template name.
``context`` is the Django template dictionary context to use.
The resulting rendered file will be uploaded to the remote file path
``destination`` (which sh... | [
"Render",
"and",
"upload",
"a",
"template",
"text",
"file",
"to",
"a",
"remote",
"host",
"using",
"the",
"Django",
"template",
"api",
"."
] | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/deployment.py#L161-L227 |
vortec/versionbump | versionbump/versionbump.py | VersionBump.pre_release | def pre_release(self):
""" Return true if version is a pre-release. """
label = self.version_info.get('label', None)
pre = self.version_info.get('pre', None)
return True if (label is not None and pre is not None) else False | python | def pre_release(self):
""" Return true if version is a pre-release. """
label = self.version_info.get('label', None)
pre = self.version_info.get('pre', None)
return True if (label is not None and pre is not None) else False | [
"def",
"pre_release",
"(",
"self",
")",
":",
"label",
"=",
"self",
".",
"version_info",
".",
"get",
"(",
"'label'",
",",
"None",
")",
"pre",
"=",
"self",
".",
"version_info",
".",
"get",
"(",
"'pre'",
",",
"None",
")",
"return",
"True",
"if",
"(",
... | Return true if version is a pre-release. | [
"Return",
"true",
"if",
"version",
"is",
"a",
"pre",
"-",
"release",
"."
] | train | https://github.com/vortec/versionbump/blob/6945d316af700c3c3ceaf3882283b3f1f4876d9e/versionbump/versionbump.py#L37-L42 |
vortec/versionbump | versionbump/versionbump.py | VersionBump.bump | def bump(self, level='patch', label=None):
""" Bump version following semantic versioning rules. """
bump = self._bump_pre if level == 'pre' else self._bump
bump(level, label) | python | def bump(self, level='patch', label=None):
""" Bump version following semantic versioning rules. """
bump = self._bump_pre if level == 'pre' else self._bump
bump(level, label) | [
"def",
"bump",
"(",
"self",
",",
"level",
"=",
"'patch'",
",",
"label",
"=",
"None",
")",
":",
"bump",
"=",
"self",
".",
"_bump_pre",
"if",
"level",
"==",
"'pre'",
"else",
"self",
".",
"_bump",
"bump",
"(",
"level",
",",
"label",
")"
] | Bump version following semantic versioning rules. | [
"Bump",
"version",
"following",
"semantic",
"versioning",
"rules",
"."
] | train | https://github.com/vortec/versionbump/blob/6945d316af700c3c3ceaf3882283b3f1f4876d9e/versionbump/versionbump.py#L66-L69 |
vortec/versionbump | versionbump/versionbump.py | VersionBump.zeroize_after_level | def zeroize_after_level(self, base_level):
""" Set all levels after ``base_level`` to zero. """
index = _LEVELS.index(base_level) + 1
for level in _LEVELS[index:]:
self.version_info[level] = 0 | python | def zeroize_after_level(self, base_level):
""" Set all levels after ``base_level`` to zero. """
index = _LEVELS.index(base_level) + 1
for level in _LEVELS[index:]:
self.version_info[level] = 0 | [
"def",
"zeroize_after_level",
"(",
"self",
",",
"base_level",
")",
":",
"index",
"=",
"_LEVELS",
".",
"index",
"(",
"base_level",
")",
"+",
"1",
"for",
"level",
"in",
"_LEVELS",
"[",
"index",
":",
"]",
":",
"self",
".",
"version_info",
"[",
"level",
"]... | Set all levels after ``base_level`` to zero. | [
"Set",
"all",
"levels",
"after",
"base_level",
"to",
"zero",
"."
] | train | https://github.com/vortec/versionbump/blob/6945d316af700c3c3ceaf3882283b3f1f4876d9e/versionbump/versionbump.py#L71-L75 |
vortec/versionbump | versionbump/versionbump.py | VersionBump.get_version | def get_version(self):
""" Return complete version string. """
version = '{major}.{minor}.{patch}'.format(**self.version_info)
if self.pre_release:
version = '{}-{label}.{pre}'.format(version, **self.version_info)
return version | python | def get_version(self):
""" Return complete version string. """
version = '{major}.{minor}.{patch}'.format(**self.version_info)
if self.pre_release:
version = '{}-{label}.{pre}'.format(version, **self.version_info)
return version | [
"def",
"get_version",
"(",
"self",
")",
":",
"version",
"=",
"'{major}.{minor}.{patch}'",
".",
"format",
"(",
"*",
"*",
"self",
".",
"version_info",
")",
"if",
"self",
".",
"pre_release",
":",
"version",
"=",
"'{}-{label}.{pre}'",
".",
"format",
"(",
"versio... | Return complete version string. | [
"Return",
"complete",
"version",
"string",
"."
] | train | https://github.com/vortec/versionbump/blob/6945d316af700c3c3ceaf3882283b3f1f4876d9e/versionbump/versionbump.py#L91-L97 |
quantmind/pulsar-odm | benchmark/app.py | Router.get | def get(self, request):
'''Simply list test urls
'''
data = {}
for router in self.routes:
data[router.name] = request.absolute_uri(router.path())
return Json(data).http_response(request) | python | def get(self, request):
'''Simply list test urls
'''
data = {}
for router in self.routes:
data[router.name] = request.absolute_uri(router.path())
return Json(data).http_response(request) | [
"def",
"get",
"(",
"self",
",",
"request",
")",
":",
"data",
"=",
"{",
"}",
"for",
"router",
"in",
"self",
".",
"routes",
":",
"data",
"[",
"router",
".",
"name",
"]",
"=",
"request",
".",
"absolute_uri",
"(",
"router",
".",
"path",
"(",
")",
")"... | Simply list test urls | [
"Simply",
"list",
"test",
"urls"
] | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/benchmark/app.py#L38-L44 |
quantmind/pulsar-odm | benchmark/app.py | Router.db | def db(self, request):
'''Single Database Query'''
with self.mapper.begin() as session:
world = session.query(World).get(randint(1, 10000))
return Json(self.get_json(world)).http_response(request) | python | def db(self, request):
'''Single Database Query'''
with self.mapper.begin() as session:
world = session.query(World).get(randint(1, 10000))
return Json(self.get_json(world)).http_response(request) | [
"def",
"db",
"(",
"self",
",",
"request",
")",
":",
"with",
"self",
".",
"mapper",
".",
"begin",
"(",
")",
"as",
"session",
":",
"world",
"=",
"session",
".",
"query",
"(",
"World",
")",
".",
"get",
"(",
"randint",
"(",
"1",
",",
"10000",
")",
... | Single Database Query | [
"Single",
"Database",
"Query"
] | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/benchmark/app.py#L55-L59 |
quantmind/pulsar-odm | benchmark/app.py | Router.queries | def queries(self, request):
'''Multiple Database Queries'''
queries = self.get_queries(request)
worlds = []
with self.mapper.begin() as session:
for _ in range(queries):
world = session.query(World).get(randint(1, MAXINT))
worlds.append(self.ge... | python | def queries(self, request):
'''Multiple Database Queries'''
queries = self.get_queries(request)
worlds = []
with self.mapper.begin() as session:
for _ in range(queries):
world = session.query(World).get(randint(1, MAXINT))
worlds.append(self.ge... | [
"def",
"queries",
"(",
"self",
",",
"request",
")",
":",
"queries",
"=",
"self",
".",
"get_queries",
"(",
"request",
")",
"worlds",
"=",
"[",
"]",
"with",
"self",
".",
"mapper",
".",
"begin",
"(",
")",
"as",
"session",
":",
"for",
"_",
"in",
"range... | Multiple Database Queries | [
"Multiple",
"Database",
"Queries"
] | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/benchmark/app.py#L62-L70 |
PMBio/limix-backup | limix/core/old/covar/covariance.py | Covariance.setRandomParams | def setRandomParams(self):
"""
set random hyperparameters
"""
params = SP.randn(self.getNumberParams())
self.setParams(params) | python | def setRandomParams(self):
"""
set random hyperparameters
"""
params = SP.randn(self.getNumberParams())
self.setParams(params) | [
"def",
"setRandomParams",
"(",
"self",
")",
":",
"params",
"=",
"SP",
".",
"randn",
"(",
"self",
".",
"getNumberParams",
"(",
")",
")",
"self",
".",
"setParams",
"(",
"params",
")"
] | set random hyperparameters | [
"set",
"random",
"hyperparameters"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/core/old/covar/covariance.py#L31-L36 |
PMBio/limix-backup | limix/core/old/covar/covariance.py | Covariance.setParams | def setParams(self,params):
"""
set hyperParams
"""
self.params = params
self.clear_all()
self._notify() | python | def setParams(self,params):
"""
set hyperParams
"""
self.params = params
self.clear_all()
self._notify() | [
"def",
"setParams",
"(",
"self",
",",
"params",
")",
":",
"self",
".",
"params",
"=",
"params",
"self",
".",
"clear_all",
"(",
")",
"self",
".",
"_notify",
"(",
")"
] | set hyperParams | [
"set",
"hyperParams"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/core/old/covar/covariance.py#L50-L56 |
PMBio/limix-backup | limix/core/old/covar/covariance.py | Covariance._initParams | def _initParams(self):
"""
initialize paramters to vector of zeros
"""
params = SP.zeros(self.getNumberParams())
self.setParams(params) | python | def _initParams(self):
"""
initialize paramters to vector of zeros
"""
params = SP.zeros(self.getNumberParams())
self.setParams(params) | [
"def",
"_initParams",
"(",
"self",
")",
":",
"params",
"=",
"SP",
".",
"zeros",
"(",
"self",
".",
"getNumberParams",
"(",
")",
")",
"self",
".",
"setParams",
"(",
"params",
")"
] | initialize paramters to vector of zeros | [
"initialize",
"paramters",
"to",
"vector",
"of",
"zeros"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/core/old/covar/covariance.py#L84-L89 |
dnarvaez/gwebsockets | gwebsockets/protocol.py | parse_frame | def parse_frame(buf):
"""Return the next frame from the socket."""
# read header
while buf.available < 2:
yield
data = buf.read(2)
first_byte, second_byte = struct.unpack('!BB', data)
fin = (first_byte >> 7) & 1
rsv1 = (first_byte >> 6) & 1
rsv2 = (first_byte >> 5) & 1
rsv3... | python | def parse_frame(buf):
"""Return the next frame from the socket."""
# read header
while buf.available < 2:
yield
data = buf.read(2)
first_byte, second_byte = struct.unpack('!BB', data)
fin = (first_byte >> 7) & 1
rsv1 = (first_byte >> 6) & 1
rsv2 = (first_byte >> 5) & 1
rsv3... | [
"def",
"parse_frame",
"(",
"buf",
")",
":",
"# read header",
"while",
"buf",
".",
"available",
"<",
"2",
":",
"yield",
"data",
"=",
"buf",
".",
"read",
"(",
"2",
")",
"first_byte",
",",
"second_byte",
"=",
"struct",
".",
"unpack",
"(",
"'!BB'",
",",
... | Return the next frame from the socket. | [
"Return",
"the",
"next",
"frame",
"from",
"the",
"socket",
"."
] | train | https://github.com/dnarvaez/gwebsockets/blob/777954a3a97de2e62817f3180d5b3bc530caff65/gwebsockets/protocol.py#L48-L116 |
dnarvaez/gwebsockets | gwebsockets/protocol.py | make_close_message | def make_close_message(code=1000, message=b''):
"""Close the websocket, sending the specified code and message."""
return _make_frame(struct.pack('!H%ds' % len(message), code, message),
opcode=OPCODE_CLOSE) | python | def make_close_message(code=1000, message=b''):
"""Close the websocket, sending the specified code and message."""
return _make_frame(struct.pack('!H%ds' % len(message), code, message),
opcode=OPCODE_CLOSE) | [
"def",
"make_close_message",
"(",
"code",
"=",
"1000",
",",
"message",
"=",
"b''",
")",
":",
"return",
"_make_frame",
"(",
"struct",
".",
"pack",
"(",
"'!H%ds'",
"%",
"len",
"(",
"message",
")",
",",
"code",
",",
"message",
")",
",",
"opcode",
"=",
"... | Close the websocket, sending the specified code and message. | [
"Close",
"the",
"websocket",
"sending",
"the",
"specified",
"code",
"and",
"message",
"."
] | train | https://github.com/dnarvaez/gwebsockets/blob/777954a3a97de2e62817f3180d5b3bc530caff65/gwebsockets/protocol.py#L200-L203 |
dnarvaez/gwebsockets | gwebsockets/protocol.py | make_message | def make_message(message, binary=False):
"""Make text message."""
if isinstance(message, str):
message = message.encode('utf-8')
if binary:
return _make_frame(message, OPCODE_BINARY)
else:
return _make_frame(message, OPCODE_TEXT) | python | def make_message(message, binary=False):
"""Make text message."""
if isinstance(message, str):
message = message.encode('utf-8')
if binary:
return _make_frame(message, OPCODE_BINARY)
else:
return _make_frame(message, OPCODE_TEXT) | [
"def",
"make_message",
"(",
"message",
",",
"binary",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"message",
",",
"str",
")",
":",
"message",
"=",
"message",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"binary",
":",
"return",
"_make_frame",
"(",
"m... | Make text message. | [
"Make",
"text",
"message",
"."
] | train | https://github.com/dnarvaez/gwebsockets/blob/777954a3a97de2e62817f3180d5b3bc530caff65/gwebsockets/protocol.py#L206-L214 |
jacquerie/flask-shell-ptpython | flask_shell_ptpython.py | shell_command | def shell_command():
"""Runs an interactive Python shell in the context of a given
Flask application. The application will populate the default
namespace of this shell according to its configuration.
This is useful for executing small snippets of management code
without having to manually configur... | python | def shell_command():
"""Runs an interactive Python shell in the context of a given
Flask application. The application will populate the default
namespace of this shell according to its configuration.
This is useful for executing small snippets of management code
without having to manually configur... | [
"def",
"shell_command",
"(",
")",
":",
"from",
"flask",
".",
"globals",
"import",
"_app_ctx_stack",
"from",
"ptpython",
".",
"repl",
"import",
"embed",
"app",
"=",
"_app_ctx_stack",
".",
"top",
".",
"app",
"ctx",
"=",
"{",
"}",
"# Support the regular Python in... | Runs an interactive Python shell in the context of a given
Flask application. The application will populate the default
namespace of this shell according to its configuration.
This is useful for executing small snippets of management code
without having to manually configure the application. | [
"Runs",
"an",
"interactive",
"Python",
"shell",
"in",
"the",
"context",
"of",
"a",
"given",
"Flask",
"application",
".",
"The",
"application",
"will",
"populate",
"the",
"default",
"namespace",
"of",
"this",
"shell",
"according",
"to",
"its",
"configuration",
... | train | https://github.com/jacquerie/flask-shell-ptpython/blob/515a502c81eb58474dcbdad7137e4c82a6167670/flask_shell_ptpython.py#L14-L37 |
rags/pynt-contrib | build.py | upload | def upload():
"""Uploads to PyPI"""
env=os.environ.copy()
print(env)
env['PYTHONPATH']= "./pynt"
print(env)
# subprocess.call(['ssh-add', '~/.ssh/id_rsa'])
pipe=subprocess.Popen(['python', 'setup.py', 'sdist','upload'], env=env)
pipe.wait() | python | def upload():
"""Uploads to PyPI"""
env=os.environ.copy()
print(env)
env['PYTHONPATH']= "./pynt"
print(env)
# subprocess.call(['ssh-add', '~/.ssh/id_rsa'])
pipe=subprocess.Popen(['python', 'setup.py', 'sdist','upload'], env=env)
pipe.wait() | [
"def",
"upload",
"(",
")",
":",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"print",
"(",
"env",
")",
"env",
"[",
"'PYTHONPATH'",
"]",
"=",
"\"./pynt\"",
"print",
"(",
"env",
")",
"# subprocess.call(['ssh-add', '~/.ssh/id_rsa'])",
"pipe",
"... | Uploads to PyPI | [
"Uploads",
"to",
"PyPI"
] | train | https://github.com/rags/pynt-contrib/blob/912315f2df9ea9b4b61abc923cad8807eed54cba/build.py#L32-L40 |
whtsky/parguments | parguments/__init__.py | Parguments.command | def command(self, func):
"""
Decorator to add a command function to the registry.
:param func: command function.
"""
command = Command(func)
self._commands[func.__name__] = command
return func | python | def command(self, func):
"""
Decorator to add a command function to the registry.
:param func: command function.
"""
command = Command(func)
self._commands[func.__name__] = command
return func | [
"def",
"command",
"(",
"self",
",",
"func",
")",
":",
"command",
"=",
"Command",
"(",
"func",
")",
"self",
".",
"_commands",
"[",
"func",
".",
"__name__",
"]",
"=",
"command",
"return",
"func"
] | Decorator to add a command function to the registry.
:param func: command function. | [
"Decorator",
"to",
"add",
"a",
"command",
"function",
"to",
"the",
"registry",
"."
] | train | https://github.com/whtsky/parguments/blob/96aa23af411a67c2f70d856e81fa186bb187daab/parguments/__init__.py#L109-L118 |
whtsky/parguments | parguments/__init__.py | Parguments.add_command | def add_command(self, func, name=None, doc=None):
"""
Add a command function to the registry.
:param func: command function.
:param name: default name of func.
:param doc: description of the func.default docstring of func.
"""
command = Command(func, doc)
... | python | def add_command(self, func, name=None, doc=None):
"""
Add a command function to the registry.
:param func: command function.
:param name: default name of func.
:param doc: description of the func.default docstring of func.
"""
command = Command(func, doc)
... | [
"def",
"add_command",
"(",
"self",
",",
"func",
",",
"name",
"=",
"None",
",",
"doc",
"=",
"None",
")",
":",
"command",
"=",
"Command",
"(",
"func",
",",
"doc",
")",
"name",
"=",
"name",
"or",
"func",
".",
"__name__",
"self",
".",
"_commands",
"[",... | Add a command function to the registry.
:param func: command function.
:param name: default name of func.
:param doc: description of the func.default docstring of func. | [
"Add",
"a",
"command",
"function",
"to",
"the",
"registry",
"."
] | train | https://github.com/whtsky/parguments/blob/96aa23af411a67c2f70d856e81fa186bb187daab/parguments/__init__.py#L120-L131 |
whtsky/parguments | parguments/__init__.py | Parguments.run | def run(self, command=None, argv=None, help=True, exit=True):
"""
Parse arguments and run the funcs.
:param command: name of command to run. default argv[0]
:param argv: argument vector to be parsed.
sys.argv[1:] is used if not provided.
:param help: Set to False to ... | python | def run(self, command=None, argv=None, help=True, exit=True):
"""
Parse arguments and run the funcs.
:param command: name of command to run. default argv[0]
:param argv: argument vector to be parsed.
sys.argv[1:] is used if not provided.
:param help: Set to False to ... | [
"def",
"run",
"(",
"self",
",",
"command",
"=",
"None",
",",
"argv",
"=",
"None",
",",
"help",
"=",
"True",
",",
"exit",
"=",
"True",
")",
":",
"result",
"=",
"0",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"[",
"1",
":... | Parse arguments and run the funcs.
:param command: name of command to run. default argv[0]
:param argv: argument vector to be parsed.
sys.argv[1:] is used if not provided.
:param help: Set to False to disable automatic
help on -h or --help options.
:param exit: S... | [
"Parse",
"arguments",
"and",
"run",
"the",
"funcs",
"."
] | train | https://github.com/whtsky/parguments/blob/96aa23af411a67c2f70d856e81fa186bb187daab/parguments/__init__.py#L149-L180 |
peterldowns/djoauth2 | example/client_demo.py | assert_200 | def assert_200(response, max_len=500):
""" Check that a HTTP response returned 200. """
if response.status_code == 200:
return
raise ValueError(
"Response was {}, not 200:\n{}\n{}".format(
response.status_code,
json.dumps(dict(response.headers), indent=2),
response.content... | python | def assert_200(response, max_len=500):
""" Check that a HTTP response returned 200. """
if response.status_code == 200:
return
raise ValueError(
"Response was {}, not 200:\n{}\n{}".format(
response.status_code,
json.dumps(dict(response.headers), indent=2),
response.content... | [
"def",
"assert_200",
"(",
"response",
",",
"max_len",
"=",
"500",
")",
":",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"return",
"raise",
"ValueError",
"(",
"\"Response was {}, not 200:\\n{}\\n{}\"",
".",
"format",
"(",
"response",
".",
"status_code... | Check that a HTTP response returned 200. | [
"Check",
"that",
"a",
"HTTP",
"response",
"returned",
"200",
"."
] | train | https://github.com/peterldowns/djoauth2/blob/151c7619d1d7a91d720397cfecf3a29fcc9747a9/example/client_demo.py#L7-L16 |
jhermann/rudiments | src/rudiments/www.py | url_as_file | def url_as_file(url, ext=None):
"""
Context manager that GETs a given `url` and provides it as a local file.
The file is in a closed state upon entering the context,
and removed when leaving it, if still there.
To give the file name a specific extension, use `ext`;
the exte... | python | def url_as_file(url, ext=None):
"""
Context manager that GETs a given `url` and provides it as a local file.
The file is in a closed state upon entering the context,
and removed when leaving it, if still there.
To give the file name a specific extension, use `ext`;
the exte... | [
"def",
"url_as_file",
"(",
"url",
",",
"ext",
"=",
"None",
")",
":",
"if",
"ext",
":",
"ext",
"=",
"'.'",
"+",
"ext",
".",
"strip",
"(",
"'.'",
")",
"# normalize extension",
"url_hint",
"=",
"'www-{}-'",
".",
"format",
"(",
"urlparse",
"(",
"url",
")... | Context manager that GETs a given `url` and provides it as a local file.
The file is in a closed state upon entering the context,
and removed when leaving it, if still there.
To give the file name a specific extension, use `ext`;
the extension can optionally include a separating dot,
... | [
"Context",
"manager",
"that",
"GETs",
"a",
"given",
"url",
"and",
"provides",
"it",
"as",
"a",
"local",
"file",
"."
] | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/www.py#L38-L78 |
grycap/cpyutils | evaluate.py | Analyzer.t_NUMBER | def t_NUMBER(self, t):
r'(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?(kb|gb|mb|tb|pb|Kb|Gb|Mb|Tb|Pb)?'
if re.match(r'^(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?(kb|gb|mb|tb|pb|Kb|Gb|Mb|Tb|Pb)?$',t.value):
multiplyer = 1
try:
suffix = (t.value[-2:]).lower()
if suffix... | python | def t_NUMBER(self, t):
r'(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?(kb|gb|mb|tb|pb|Kb|Gb|Mb|Tb|Pb)?'
if re.match(r'^(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?(kb|gb|mb|tb|pb|Kb|Gb|Mb|Tb|Pb)?$',t.value):
multiplyer = 1
try:
suffix = (t.value[-2:]).lower()
if suffix... | [
"def",
"t_NUMBER",
"(",
"self",
",",
"t",
")",
":",
"if",
"re",
".",
"match",
"(",
"r'^(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?(kb|gb|mb|tb|pb|Kb|Gb|Mb|Tb|Pb)?$'",
",",
"t",
".",
"value",
")",
":",
"multiplyer",
"=",
"1",
"try",
":",
"suffix",
"=",
"(",
"t",
... | r'(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?(kb|gb|mb|tb|pb|Kb|Gb|Mb|Tb|Pb)? | [
"r",
"(",
"\\",
"d",
"+",
"(",
"\\",
".",
"\\",
"d",
"*",
")",
"?|",
"\\",
".",
"\\",
"d",
"+",
")",
"(",
"[",
"eE",
"]",
"[",
"+",
"-",
"]",
"?",
"\\",
"d",
"+",
")",
"?",
"(",
"kb|gb|mb|tb|pb|Kb|Gb|Mb|Tb|Pb",
")",
"?"
] | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/evaluate.py#L263-L302 |
grycap/cpyutils | evaluate.py | Analyzer.t_VAR | def t_VAR(self, t):
r'[a-zA-Z_][a-zA-Z0-9_]*'
t.type = self.reserved.get(t.value.lower(), 'VAR')
return t | python | def t_VAR(self, t):
r'[a-zA-Z_][a-zA-Z0-9_]*'
t.type = self.reserved.get(t.value.lower(), 'VAR')
return t | [
"def",
"t_VAR",
"(",
"self",
",",
"t",
")",
":",
"t",
".",
"type",
"=",
"self",
".",
"reserved",
".",
"get",
"(",
"t",
".",
"value",
".",
"lower",
"(",
")",
",",
"'VAR'",
")",
"return",
"t"
] | r'[a-zA-Z_][a-zA-Z0-9_]* | [
"r",
"[",
"a",
"-",
"zA",
"-",
"Z_",
"]",
"[",
"a",
"-",
"zA",
"-",
"Z0",
"-",
"9_",
"]",
"*"
] | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/evaluate.py#L304-L307 |
grycap/cpyutils | evaluate.py | Analyzer.p_kwl_kwl | def p_kwl_kwl(self, p):
''' kwl : kwl SEPARATOR kwl
'''
_LOGGER.debug("kwl -> kwl ; kwl")
if p[3] is not None:
p[0] = p[3]
elif p[1] is not None:
p[0] = p[1]
else:
p[0] = TypedClass(None, TypedClass.UNKNOWN) | python | def p_kwl_kwl(self, p):
''' kwl : kwl SEPARATOR kwl
'''
_LOGGER.debug("kwl -> kwl ; kwl")
if p[3] is not None:
p[0] = p[3]
elif p[1] is not None:
p[0] = p[1]
else:
p[0] = TypedClass(None, TypedClass.UNKNOWN) | [
"def",
"p_kwl_kwl",
"(",
"self",
",",
"p",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"kwl -> kwl ; kwl\"",
")",
"if",
"p",
"[",
"3",
"]",
"is",
"not",
"None",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"3",
"]",
"elif",
"p",
"[",
"1",
"]",
"is",... | kwl : kwl SEPARATOR kwl | [
"kwl",
":",
"kwl",
"SEPARATOR",
"kwl"
] | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/evaluate.py#L368-L377 |
grycap/cpyutils | evaluate.py | Analyzer.p_statement_notexpr | def p_statement_notexpr(self, p):
''' expression : NOT expression
| '!' expression
'''
_LOGGER.debug("expresion -> ! expression")
if p[2].type == TypedClass.BOOLEAN:
p[0] = TypedClass(not p[2].value, TypedClass.BOOLEAN)
else:
rais... | python | def p_statement_notexpr(self, p):
''' expression : NOT expression
| '!' expression
'''
_LOGGER.debug("expresion -> ! expression")
if p[2].type == TypedClass.BOOLEAN:
p[0] = TypedClass(not p[2].value, TypedClass.BOOLEAN)
else:
rais... | [
"def",
"p_statement_notexpr",
"(",
"self",
",",
"p",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"expresion -> ! expression\"",
")",
"if",
"p",
"[",
"2",
"]",
".",
"type",
"==",
"TypedClass",
".",
"BOOLEAN",
":",
"p",
"[",
"0",
"]",
"=",
"TypedClass",
"(... | expression : NOT expression
| '!' expression | [
"expression",
":",
"NOT",
"expression",
"|",
"!",
"expression"
] | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/evaluate.py#L391-L399 |
grycap/cpyutils | evaluate.py | Analyzer.p_expression_boolop | def p_expression_boolop(self, p):
"""
expression : expression GT expression
| expression LT expression
| expression GE expression
| expression LE expression
| expression EQ expression
| expression NE expression
... | python | def p_expression_boolop(self, p):
"""
expression : expression GT expression
| expression LT expression
| expression GE expression
| expression LE expression
| expression EQ expression
| expression NE expression
... | [
"def",
"p_expression_boolop",
"(",
"self",
",",
"p",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"expresion -> expresion %s expression\"",
"%",
"p",
"[",
"2",
"]",
")",
"if",
"self",
".",
"_autodefine_vars",
":",
"self",
".",
"_init_vars",
"(",
"p",
"[",
"1"... | expression : expression GT expression
| expression LT expression
| expression GE expression
| expression LE expression
| expression EQ expression
| expression NE expression
| expression AND expression
... | [
"expression",
":",
"expression",
"GT",
"expression",
"|",
"expression",
"LT",
"expression",
"|",
"expression",
"GE",
"expression",
"|",
"expression",
"LE",
"expression",
"|",
"expression",
"EQ",
"expression",
"|",
"expression",
"NE",
"expression",
"|",
"expression... | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/evaluate.py#L401-L443 |
grycap/cpyutils | evaluate.py | Analyzer.p_expression_binop | def p_expression_binop(self, p):
"""
expression : expression PLUS expression
| expression MINUS expression
| expression TIMES expression
| expression DIVIDE expression
"""
_LOGGER.debug("expresion -> expresion %s expression" % p[2])
... | python | def p_expression_binop(self, p):
"""
expression : expression PLUS expression
| expression MINUS expression
| expression TIMES expression
| expression DIVIDE expression
"""
_LOGGER.debug("expresion -> expresion %s expression" % p[2])
... | [
"def",
"p_expression_binop",
"(",
"self",
",",
"p",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"expresion -> expresion %s expression\"",
"%",
"p",
"[",
"2",
"]",
")",
"if",
"self",
".",
"_autodefine_vars",
":",
"self",
".",
"_init_vars",
"(",
"p",
"[",
"1",... | expression : expression PLUS expression
| expression MINUS expression
| expression TIMES expression
| expression DIVIDE expression | [
"expression",
":",
"expression",
"PLUS",
"expression",
"|",
"expression",
"MINUS",
"expression",
"|",
"expression",
"TIMES",
"expression",
"|",
"expression",
"DIVIDE",
"expression"
] | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/evaluate.py#L446-L480 |
grycap/cpyutils | evaluate.py | Analyzer.p_expression_inlist | def p_expression_inlist(self, p):
''' expression : expression IN lexp
'''
_LOGGER.debug("expresion -> expresion IN lexp")
if self._autodefine_vars:
self._init_vars(TypedList([]), p[3])
if p[3].type != TypedClass.LIST: raise TypeError("expected list for IN oper... | python | def p_expression_inlist(self, p):
''' expression : expression IN lexp
'''
_LOGGER.debug("expresion -> expresion IN lexp")
if self._autodefine_vars:
self._init_vars(TypedList([]), p[3])
if p[3].type != TypedClass.LIST: raise TypeError("expected list for IN oper... | [
"def",
"p_expression_inlist",
"(",
"self",
",",
"p",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"expresion -> expresion IN lexp\"",
")",
"if",
"self",
".",
"_autodefine_vars",
":",
"self",
".",
"_init_vars",
"(",
"TypedList",
"(",
"[",
"]",
")",
",",
"p",
"... | expression : expression IN lexp | [
"expression",
":",
"expression",
"IN",
"lexp"
] | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/evaluate.py#L482-L498 |
grycap/cpyutils | evaluate.py | Analyzer.p_expression_invar | def p_expression_invar(self, p):
''' expression : expression IN VAR
'''
_LOGGER.debug("expresion -> expresion IN VAR")
if p[3] not in self._VAR_VALUES:
if self._autodefine_vars:
self._VAR_VALUES[p[3]] = TypedList([])
else:
... | python | def p_expression_invar(self, p):
''' expression : expression IN VAR
'''
_LOGGER.debug("expresion -> expresion IN VAR")
if p[3] not in self._VAR_VALUES:
if self._autodefine_vars:
self._VAR_VALUES[p[3]] = TypedList([])
else:
... | [
"def",
"p_expression_invar",
"(",
"self",
",",
"p",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"expresion -> expresion IN VAR\"",
")",
"if",
"p",
"[",
"3",
"]",
"not",
"in",
"self",
".",
"_VAR_VALUES",
":",
"if",
"self",
".",
"_autodefine_vars",
":",
"self"... | expression : expression IN VAR | [
"expression",
":",
"expression",
"IN",
"VAR"
] | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/evaluate.py#L500-L515 |
grycap/cpyutils | evaluate.py | Analyzer.p_expression_subsetlist | def p_expression_subsetlist(self, p):
''' expression : expression SUBSET lexp
'''
_LOGGER.debug("expresion -> expresion SUBSET lexp")
if p[1].type != TypedClass.LIST: raise TypeError("lists expected for SUBSET operator")
if p[3].type != TypedClass.LIST: raise TypeError... | python | def p_expression_subsetlist(self, p):
''' expression : expression SUBSET lexp
'''
_LOGGER.debug("expresion -> expresion SUBSET lexp")
if p[1].type != TypedClass.LIST: raise TypeError("lists expected for SUBSET operator")
if p[3].type != TypedClass.LIST: raise TypeError... | [
"def",
"p_expression_subsetlist",
"(",
"self",
",",
"p",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"expresion -> expresion SUBSET lexp\"",
")",
"if",
"p",
"[",
"1",
"]",
".",
"type",
"!=",
"TypedClass",
".",
"LIST",
":",
"raise",
"TypeError",
"(",
"\"lists e... | expression : expression SUBSET lexp | [
"expression",
":",
"expression",
"SUBSET",
"lexp"
] | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/evaluate.py#L518-L537 |
grycap/cpyutils | evaluate.py | Analyzer.p_expression_subsetvar | def p_expression_subsetvar(self, p):
''' expression : expression SUBSET VAR
'''
_LOGGER.debug("expresion -> expresion SUBSET VAR")
if p[3] not in self._VAR_VALUES:
if self._autodefine_vars:
self._VAR_VALUES[p[3]] = TypedList([])
else:
... | python | def p_expression_subsetvar(self, p):
''' expression : expression SUBSET VAR
'''
_LOGGER.debug("expresion -> expresion SUBSET VAR")
if p[3] not in self._VAR_VALUES:
if self._autodefine_vars:
self._VAR_VALUES[p[3]] = TypedList([])
else:
... | [
"def",
"p_expression_subsetvar",
"(",
"self",
",",
"p",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"expresion -> expresion SUBSET VAR\"",
")",
"if",
"p",
"[",
"3",
"]",
"not",
"in",
"self",
".",
"_VAR_VALUES",
":",
"if",
"self",
".",
"_autodefine_vars",
":",
... | expression : expression SUBSET VAR | [
"expression",
":",
"expression",
"SUBSET",
"VAR"
] | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/evaluate.py#L539-L554 |
grycap/cpyutils | evaluate.py | Analyzer.p_expression_uminus | def p_expression_uminus(self, p):
''' expression : MINUS expression %prec UMINUS
'''
_LOGGER.debug("expresion -> - expresion")
if p[2].type == TypedClass.NUMBER:
p[0] = TypedClass(-p[2].value, TypedClass.NUMBER)
else:
raise TypeError("operator invalid... | python | def p_expression_uminus(self, p):
''' expression : MINUS expression %prec UMINUS
'''
_LOGGER.debug("expresion -> - expresion")
if p[2].type == TypedClass.NUMBER:
p[0] = TypedClass(-p[2].value, TypedClass.NUMBER)
else:
raise TypeError("operator invalid... | [
"def",
"p_expression_uminus",
"(",
"self",
",",
"p",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"expresion -> - expresion\"",
")",
"if",
"p",
"[",
"2",
"]",
".",
"type",
"==",
"TypedClass",
".",
"NUMBER",
":",
"p",
"[",
"0",
"]",
"=",
"TypedClass",
"(",... | expression : MINUS expression %prec UMINUS | [
"expression",
":",
"MINUS",
"expression",
"%prec",
"UMINUS"
] | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/evaluate.py#L556-L564 |
grycap/cpyutils | evaluate.py | Analyzer.p_l_expression | def p_l_expression(self, p):
''' l : expression
'''
_LOGGER.debug("l -> expresion")
l = TypedList( [ p[1] ] )
p[0] = l | python | def p_l_expression(self, p):
''' l : expression
'''
_LOGGER.debug("l -> expresion")
l = TypedList( [ p[1] ] )
p[0] = l | [
"def",
"p_l_expression",
"(",
"self",
",",
"p",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"l -> expresion\"",
")",
"l",
"=",
"TypedList",
"(",
"[",
"p",
"[",
"1",
"]",
"]",
")",
"p",
"[",
"0",
"]",
"=",
"l"
] | l : expression | [
"l",
":",
"expression"
] | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/evaluate.py#L599-L605 |
grycap/cpyutils | evaluate.py | Analyzer.p_l_comma_l | def p_l_comma_l(self, p):
''' l : expression COMMA l
'''
_LOGGER.debug("l -> expresion , l")
if p[3].type != TypedClass.LIST: raise TypeError("list expected")
l = TypedList( [ p[1] ] + p[3].value)
p[0] = l | python | def p_l_comma_l(self, p):
''' l : expression COMMA l
'''
_LOGGER.debug("l -> expresion , l")
if p[3].type != TypedClass.LIST: raise TypeError("list expected")
l = TypedList( [ p[1] ] + p[3].value)
p[0] = l | [
"def",
"p_l_comma_l",
"(",
"self",
",",
"p",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"l -> expresion , l\"",
")",
"if",
"p",
"[",
"3",
"]",
".",
"type",
"!=",
"TypedClass",
".",
"LIST",
":",
"raise",
"TypeError",
"(",
"\"list expected\"",
")",
"l",
"... | l : expression COMMA l | [
"l",
":",
"expression",
"COMMA",
"l"
] | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/evaluate.py#L607-L614 |
grycap/cpyutils | evaluate.py | Analyzer.p_term_var | def p_term_var(self, p):
''' term : VAR
'''
_LOGGER.debug("term -> VAR")
# TODO: determine the type of the var
if p[1] not in self._VAR_VALUES:
if self._autodefine_vars:
self._VAR_VALUES[p[1]] = TypedClass(None, TypedClass.UNKNOWN)
... | python | def p_term_var(self, p):
''' term : VAR
'''
_LOGGER.debug("term -> VAR")
# TODO: determine the type of the var
if p[1] not in self._VAR_VALUES:
if self._autodefine_vars:
self._VAR_VALUES[p[1]] = TypedClass(None, TypedClass.UNKNOWN)
... | [
"def",
"p_term_var",
"(",
"self",
",",
"p",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"term -> VAR\"",
")",
"# TODO: determine the type of the var",
"if",
"p",
"[",
"1",
"]",
"not",
"in",
"self",
".",
"_VAR_VALUES",
":",
"if",
"self",
".",
"_autodefine_vars"... | term : VAR | [
"term",
":",
"VAR"
] | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/evaluate.py#L616-L630 |
grycap/cpyutils | evaluate.py | Analyzer.p_term_bool | def p_term_bool(self, p):
''' term : TRUE
| FALSE
'''
_LOGGER.debug("term -> TRUE/FALSE")
if p[1].lower() == 'true':
p[0] = TypedClass(True, TypedClass.BOOLEAN)
else:
p[0] = TypedClass(False, TypedClass.BOOLEAN) | python | def p_term_bool(self, p):
''' term : TRUE
| FALSE
'''
_LOGGER.debug("term -> TRUE/FALSE")
if p[1].lower() == 'true':
p[0] = TypedClass(True, TypedClass.BOOLEAN)
else:
p[0] = TypedClass(False, TypedClass.BOOLEAN) | [
"def",
"p_term_bool",
"(",
"self",
",",
"p",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"term -> TRUE/FALSE\"",
")",
"if",
"p",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"==",
"'true'",
":",
"p",
"[",
"0",
"]",
"=",
"TypedClass",
"(",
"True",
",",
"T... | term : TRUE
| FALSE | [
"term",
":",
"TRUE",
"|",
"FALSE"
] | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/evaluate.py#L632-L641 |
grycap/cpyutils | evaluate.py | Analyzer.p_term_string | def p_term_string(self, p):
''' term : STRING
'''
_LOGGER.debug("term -> STRING")
p[0] = TypedClass(p[1], TypedClass.STRING) | python | def p_term_string(self, p):
''' term : STRING
'''
_LOGGER.debug("term -> STRING")
p[0] = TypedClass(p[1], TypedClass.STRING) | [
"def",
"p_term_string",
"(",
"self",
",",
"p",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"term -> STRING\"",
")",
"p",
"[",
"0",
"]",
"=",
"TypedClass",
"(",
"p",
"[",
"1",
"]",
",",
"TypedClass",
".",
"STRING",
")"
] | term : STRING | [
"term",
":",
"STRING"
] | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/evaluate.py#L657-L662 |
bcaller/pinyin_markdown | pinyin_markdown/pinyinextension.py | NumberedPinyinPattern.handleMatch | def handleMatch(self, m):
"""
Makes an ElementTree for the discovered Pinyin syllables.
The root element holding all syllables is <junkpinyinmd>, which is removed by RemoveJunkParentTreeprocessor
Converts Xi3ban4 to <junkpinyinmd><span class="tone3">Xǐ</span><span class="tone4">bàn</span... | python | def handleMatch(self, m):
"""
Makes an ElementTree for the discovered Pinyin syllables.
The root element holding all syllables is <junkpinyinmd>, which is removed by RemoveJunkParentTreeprocessor
Converts Xi3ban4 to <junkpinyinmd><span class="tone3">Xǐ</span><span class="tone4">bàn</span... | [
"def",
"handleMatch",
"(",
"self",
",",
"m",
")",
":",
"polysyllabic_chinese_word",
"=",
"m",
".",
"group",
"(",
"2",
")",
"parent",
"=",
"etree",
".",
"Element",
"(",
"JUNK_TAG",
")",
"for",
"i",
",",
"sound",
"in",
"enumerate",
"(",
"pinyin_regex",
"... | Makes an ElementTree for the discovered Pinyin syllables.
The root element holding all syllables is <junkpinyinmd>, which is removed by RemoveJunkParentTreeprocessor
Converts Xi3ban4 to <junkpinyinmd><span class="tone3">Xǐ</span><span class="tone4">bàn</span></junkpinyinmd>
:param m: polysyllabi... | [
"Makes",
"an",
"ElementTree",
"for",
"the",
"discovered",
"Pinyin",
"syllables",
".",
"The",
"root",
"element",
"holding",
"all",
"syllables",
"is",
"<junkpinyinmd",
">",
"which",
"is",
"removed",
"by",
"RemoveJunkParentTreeprocessor",
"Converts",
"Xi3ban4",
"to",
... | train | https://github.com/bcaller/pinyin_markdown/blob/d2f07233b37a885478198fb2fdf9978a250d82d3/pinyin_markdown/pinyinextension.py#L55-L78 |
crowsonkb/aiohttp_index | aiohttp_index/index.py | IndexMiddleware | def IndexMiddleware(index='index.html'):
"""Middleware to serve index files (e.g. index.html) when static directories are requested.
Usage:
::
from aiohttp import web
from aiohttp_index import IndexMiddleware
app = web.Application(middlewares=[IndexMiddleware()])
app.router... | python | def IndexMiddleware(index='index.html'):
"""Middleware to serve index files (e.g. index.html) when static directories are requested.
Usage:
::
from aiohttp import web
from aiohttp_index import IndexMiddleware
app = web.Application(middlewares=[IndexMiddleware()])
app.router... | [
"def",
"IndexMiddleware",
"(",
"index",
"=",
"'index.html'",
")",
":",
"async",
"def",
"middleware_factory",
"(",
"app",
",",
"handler",
")",
":",
"\"\"\"Middleware factory method.\n\n :type app: aiohttp.web.Application\n :type handler: function\n :returns: The... | Middleware to serve index files (e.g. index.html) when static directories are requested.
Usage:
::
from aiohttp import web
from aiohttp_index import IndexMiddleware
app = web.Application(middlewares=[IndexMiddleware()])
app.router.add_static('/', 'static')
``app`` will now... | [
"Middleware",
"to",
"serve",
"index",
"files",
"(",
"e",
".",
"g",
".",
"index",
".",
"html",
")",
"when",
"static",
"directories",
"are",
"requested",
"."
] | train | https://github.com/crowsonkb/aiohttp_index/blob/2fb8ff23143947a451b15f1392011764c481d813/aiohttp_index/index.py#L6-L49 |
KelSolaar/Foundations | foundations/cache.py | Cache.add_content | def add_content(self, **content):
"""
Adds given content to the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache
{'Luke': 'Skywalker', 'John': 'Doe'}
:param \*\*content: Co... | python | def add_content(self, **content):
"""
Adds given content to the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache
{'Luke': 'Skywalker', 'John': 'Doe'}
:param \*\*content: Co... | [
"def",
"add_content",
"(",
"self",
",",
"*",
"*",
"content",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Adding '{0}' content to the cache.\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"content",
")",
")",
"self",
".",
"update",
... | Adds given content to the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache
{'Luke': 'Skywalker', 'John': 'Doe'}
:param \*\*content: Content to add.
:type \*\*content: \*\*
... | [
"Adds",
"given",
"content",
"to",
"the",
"cache",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/cache.py#L51-L72 |
KelSolaar/Foundations | foundations/cache.py | Cache.remove_content | def remove_content(self, *keys):
"""
Removes given content from the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.remove_content("Luke", "John")
True
>>> cache
... | python | def remove_content(self, *keys):
"""
Removes given content from the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.remove_content("Luke", "John")
True
>>> cache
... | [
"def",
"remove_content",
"(",
"self",
",",
"*",
"keys",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Removing '{0}' content from the cache.\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"keys",
")",
")",
"for",
"key",
"in",
"keys",
... | Removes given content from the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.remove_content("Luke", "John")
True
>>> cache
{}
:param \*keys: Content to remove.
... | [
"Removes",
"given",
"content",
"from",
"the",
"cache",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/cache.py#L74-L101 |
KelSolaar/Foundations | foundations/cache.py | Cache.get_content | def get_content(self, key):
"""
Gets given content from the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.get_content("Luke")
'Skywalker'
:param key: Content to retrieve... | python | def get_content(self, key):
"""
Gets given content from the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.get_content("Luke")
'Skywalker'
:param key: Content to retrieve... | [
"def",
"get_content",
"(",
"self",
",",
"key",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Retrieving '{0}' content from the cache.\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"key",
")",
")",
"return",
"self",
".",
"get",
"(",
... | Gets given content from the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.get_content("Luke")
'Skywalker'
:param key: Content to retrieve.
:type key: object
:return: Con... | [
"Gets",
"given",
"content",
"from",
"the",
"cache",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/cache.py#L103-L123 |
KelSolaar/Foundations | foundations/cache.py | Cache.flush_content | def flush_content(self):
"""
Flushes the cache content.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.flush_content()
True
>>> cache
{}
:return: Method ... | python | def flush_content(self):
"""
Flushes the cache content.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.flush_content()
True
>>> cache
{}
:return: Method ... | [
"def",
"flush_content",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Flushing cache content.\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"self",
".",
"clear",
"(",
")",
"return",
"True"
] | Flushes the cache content.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.flush_content()
True
>>> cache
{}
:return: Method success.
:rtype: bool | [
"Flushes",
"the",
"cache",
"content",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/cache.py#L125-L146 |
fitnr/twitter_bot_utils | twitter_bot_utils/cli.py | post | def post(arguments):
'''Post text to a given twitter account.'''
twitter = api.API(arguments)
params = {}
if arguments.update == '-':
params['status'] = sys.stdin.read()
else:
params['status'] = arguments.update
if arguments.media_file:
medias = [twitter.media_upload(m)... | python | def post(arguments):
'''Post text to a given twitter account.'''
twitter = api.API(arguments)
params = {}
if arguments.update == '-':
params['status'] = sys.stdin.read()
else:
params['status'] = arguments.update
if arguments.media_file:
medias = [twitter.media_upload(m)... | [
"def",
"post",
"(",
"arguments",
")",
":",
"twitter",
"=",
"api",
".",
"API",
"(",
"arguments",
")",
"params",
"=",
"{",
"}",
"if",
"arguments",
".",
"update",
"==",
"'-'",
":",
"params",
"[",
"'status'",
"]",
"=",
"sys",
".",
"stdin",
".",
"read",... | Post text to a given twitter account. | [
"Post",
"text",
"to",
"a",
"given",
"twitter",
"account",
"."
] | train | https://github.com/fitnr/twitter_bot_utils/blob/21f35afa5048cd3efa54db8cb87d405f69a78a62/twitter_bot_utils/cli.py#L145-L165 |
feifangit/dj-sso-server | djssoserver/models.py | SSO.sso_api_list | def sso_api_list():
"""
return sso related API
"""
ssourls = []
def collect(u, prefixre, prefixname):
_prefixname = prefixname + [u._regex, ]
urldisplayname = " ".join(_prefixname)
if hasattr(u.urlconf_module, "_MODULE_MAGIC_ID_") \
... | python | def sso_api_list():
"""
return sso related API
"""
ssourls = []
def collect(u, prefixre, prefixname):
_prefixname = prefixname + [u._regex, ]
urldisplayname = " ".join(_prefixname)
if hasattr(u.urlconf_module, "_MODULE_MAGIC_ID_") \
... | [
"def",
"sso_api_list",
"(",
")",
":",
"ssourls",
"=",
"[",
"]",
"def",
"collect",
"(",
"u",
",",
"prefixre",
",",
"prefixname",
")",
":",
"_prefixname",
"=",
"prefixname",
"+",
"[",
"u",
".",
"_regex",
",",
"]",
"urldisplayname",
"=",
"\" \"",
".",
"... | return sso related API | [
"return",
"sso",
"related",
"API"
] | train | https://github.com/feifangit/dj-sso-server/blob/72b8298413fb10da35bd3be885f7f74b34207a24/djssoserver/models.py#L22-L44 |
goshuirc/irc | girc/features.py | Features._simplify_feature_value | def _simplify_feature_value(self, name, value):
"""Return simplified and more pythonic feature values."""
if name == 'prefix':
channel_modes, channel_chars = value.split(')')
channel_modes = channel_modes[1:]
# [::-1] to reverse order and go from lowest to highest pr... | python | def _simplify_feature_value(self, name, value):
"""Return simplified and more pythonic feature values."""
if name == 'prefix':
channel_modes, channel_chars = value.split(')')
channel_modes = channel_modes[1:]
# [::-1] to reverse order and go from lowest to highest pr... | [
"def",
"_simplify_feature_value",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"name",
"==",
"'prefix'",
":",
"channel_modes",
",",
"channel_chars",
"=",
"value",
".",
"split",
"(",
"')'",
")",
"channel_modes",
"=",
"channel_modes",
"[",
"1",
":... | Return simplified and more pythonic feature values. | [
"Return",
"simplified",
"and",
"more",
"pythonic",
"feature",
"values",
"."
] | train | https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/features.py#L48-L86 |
PMBio/limix-backup | limix/mtSet/core/splitter.py | Splitter.splitGeno | def splitGeno(self,method='slidingWindow',size=5e4,step=None,annotation_file=None,cis=1e4,funct=None,minSnps=1.,maxSnps=SP.inf,cache=False,out_dir='./cache',fname=None,rewrite=False):
"""
split into windows
Args:
method: method used to slit the windows:
's... | python | def splitGeno(self,method='slidingWindow',size=5e4,step=None,annotation_file=None,cis=1e4,funct=None,minSnps=1.,maxSnps=SP.inf,cache=False,out_dir='./cache',fname=None,rewrite=False):
"""
split into windows
Args:
method: method used to slit the windows:
's... | [
"def",
"splitGeno",
"(",
"self",
",",
"method",
"=",
"'slidingWindow'",
",",
"size",
"=",
"5e4",
",",
"step",
"=",
"None",
",",
"annotation_file",
"=",
"None",
",",
"cis",
"=",
"1e4",
",",
"funct",
"=",
"None",
",",
"minSnps",
"=",
"1.",
",",
"maxSnp... | split into windows
Args:
method: method used to slit the windows:
'slidingWindow': uses a sliding window
'geneWindow': uses windows centered on genes
size: window size used in slidingWindow method
step: ... | [
"split",
"into",
"windows",
"Args",
":",
"method",
":",
"method",
"used",
"to",
"slit",
"the",
"windows",
":",
"slidingWindow",
":",
"uses",
"a",
"sliding",
"window",
"geneWindow",
":",
"uses",
"windows",
"centered",
"on",
"genes",
"size",
":",
"window",
"... | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/mtSet/core/splitter.py#L37-L85 |
PMBio/limix-backup | limix/mtSet/core/splitter.py | Splitter._splitGenoSlidingWindow | def _splitGenoSlidingWindow(self,size=5e4,step=None,minSnps=1.,maxSnps=SP.inf):
"""
split into windows using a slide criterion
Args:
size: window size
step: moving step (default: 0.5*size)
minSnps: only windows with nSnps>=minSnps are considered... | python | def _splitGenoSlidingWindow(self,size=5e4,step=None,minSnps=1.,maxSnps=SP.inf):
"""
split into windows using a slide criterion
Args:
size: window size
step: moving step (default: 0.5*size)
minSnps: only windows with nSnps>=minSnps are considered... | [
"def",
"_splitGenoSlidingWindow",
"(",
"self",
",",
"size",
"=",
"5e4",
",",
"step",
"=",
"None",
",",
"minSnps",
"=",
"1.",
",",
"maxSnps",
"=",
"SP",
".",
"inf",
")",
":",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"0.5",
"*",
"size",
"chroms"... | split into windows using a slide criterion
Args:
size: window size
step: moving step (default: 0.5*size)
minSnps: only windows with nSnps>=minSnps are considered
maxSnps: only windows with nSnps>=maxSnps are considered | [
"split",
"into",
"windows",
"using",
"a",
"slide",
"criterion",
"Args",
":",
"size",
":",
"window",
"size",
"step",
":",
"moving",
"step",
"(",
"default",
":",
"0",
".",
"5",
"*",
"size",
")",
"minSnps",
":",
"only",
"windows",
"with",
"nSnps",
">",
... | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/mtSet/core/splitter.py#L87-L123 |
PMBio/limix-backup | limix/mtSet/core/splitter.py | Splitter._splitGenoGeneWindow | def _splitGenoGeneWindow(self,annotation_file=None,cis=1e4,funct='protein_coding',minSnps=1.,maxSnps=SP.inf):
"""
split into windows based on genes
"""
#1. load annotation
assert annotation_file is not None, 'Splitter:: specify annotation file'
try:
f = h5py.... | python | def _splitGenoGeneWindow(self,annotation_file=None,cis=1e4,funct='protein_coding',minSnps=1.,maxSnps=SP.inf):
"""
split into windows based on genes
"""
#1. load annotation
assert annotation_file is not None, 'Splitter:: specify annotation file'
try:
f = h5py.... | [
"def",
"_splitGenoGeneWindow",
"(",
"self",
",",
"annotation_file",
"=",
"None",
",",
"cis",
"=",
"1e4",
",",
"funct",
"=",
"'protein_coding'",
",",
"minSnps",
"=",
"1.",
",",
"maxSnps",
"=",
"SP",
".",
"inf",
")",
":",
"#1. load annotation",
"assert",
"an... | split into windows based on genes | [
"split",
"into",
"windows",
"based",
"on",
"genes"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/mtSet/core/splitter.py#L125-L171 |
tchx84/grestful | grestful/decorators.py | check_is_created | def check_is_created(method):
""" Make sure the Object DOES have an id, already. """
def check(self, *args, **kwargs):
if self.id is None:
raise NotCreatedError('%s does not exists.' %
self.__class__.__name__)
return method(self, *args, **kwargs)
... | python | def check_is_created(method):
""" Make sure the Object DOES have an id, already. """
def check(self, *args, **kwargs):
if self.id is None:
raise NotCreatedError('%s does not exists.' %
self.__class__.__name__)
return method(self, *args, **kwargs)
... | [
"def",
"check_is_created",
"(",
"method",
")",
":",
"def",
"check",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"id",
"is",
"None",
":",
"raise",
"NotCreatedError",
"(",
"'%s does not exists.'",
"%",
"self",
"."... | Make sure the Object DOES have an id, already. | [
"Make",
"sure",
"the",
"Object",
"DOES",
"have",
"an",
"id",
"already",
"."
] | train | https://github.com/tchx84/grestful/blob/5f7ee7eb358cf260c97d41f8680e8f168ef5d843/grestful/decorators.py#L24-L31 |
tchx84/grestful | grestful/decorators.py | check_is_not_created | def check_is_not_created(method):
""" Make sure the Object does NOT have an id, yet. """
def check(self, *args, **kwargs):
if self.id is not None:
raise AlreadyCreatedError('%s.id %s already exists.' %
(self.__class__.__name__, self.id))
return me... | python | def check_is_not_created(method):
""" Make sure the Object does NOT have an id, yet. """
def check(self, *args, **kwargs):
if self.id is not None:
raise AlreadyCreatedError('%s.id %s already exists.' %
(self.__class__.__name__, self.id))
return me... | [
"def",
"check_is_not_created",
"(",
"method",
")",
":",
"def",
"check",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"id",
"is",
"not",
"None",
":",
"raise",
"AlreadyCreatedError",
"(",
"'%s.id %s already exists.'",
... | Make sure the Object does NOT have an id, yet. | [
"Make",
"sure",
"the",
"Object",
"does",
"NOT",
"have",
"an",
"id",
"yet",
"."
] | train | https://github.com/tchx84/grestful/blob/5f7ee7eb358cf260c97d41f8680e8f168ef5d843/grestful/decorators.py#L34-L41 |
tchx84/grestful | grestful/decorators.py | asynchronous | def asynchronous(method):
""" Convenience wrapper for GObject.idle_add. """
def _async(*args, **kwargs):
GObject.idle_add(method, *args, **kwargs)
return _async | python | def asynchronous(method):
""" Convenience wrapper for GObject.idle_add. """
def _async(*args, **kwargs):
GObject.idle_add(method, *args, **kwargs)
return _async | [
"def",
"asynchronous",
"(",
"method",
")",
":",
"def",
"_async",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"GObject",
".",
"idle_add",
"(",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"_async"
] | Convenience wrapper for GObject.idle_add. | [
"Convenience",
"wrapper",
"for",
"GObject",
".",
"idle_add",
"."
] | train | https://github.com/tchx84/grestful/blob/5f7ee7eb358cf260c97d41f8680e8f168ef5d843/grestful/decorators.py#L44-L48 |
goshuirc/irc | girc/asyncio_compat.py | ensure_future | def ensure_future(fut, *, loop=None):
"""
Wraps asyncio.async()/asyncio.ensure_future() depending on the python version
:param fut: The awaitable, future, or coroutine to wrap
:param loop: The loop to run in
:return: The wrapped future
"""
if sys.version_info < (3, 4, 4):
# This is t... | python | def ensure_future(fut, *, loop=None):
"""
Wraps asyncio.async()/asyncio.ensure_future() depending on the python version
:param fut: The awaitable, future, or coroutine to wrap
:param loop: The loop to run in
:return: The wrapped future
"""
if sys.version_info < (3, 4, 4):
# This is t... | [
"def",
"ensure_future",
"(",
"fut",
",",
"*",
",",
"loop",
"=",
"None",
")",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"4",
",",
"4",
")",
":",
"# This is to avoid a SyntaxError on 3.7.0a2+",
"func",
"=",
"getattr",
"(",
"asyncio",
",",
... | Wraps asyncio.async()/asyncio.ensure_future() depending on the python version
:param fut: The awaitable, future, or coroutine to wrap
:param loop: The loop to run in
:return: The wrapped future | [
"Wraps",
"asyncio",
".",
"async",
"()",
"/",
"asyncio",
".",
"ensure_future",
"()",
"depending",
"on",
"the",
"python",
"version",
":",
"param",
"fut",
":",
"The",
"awaitable",
"future",
"or",
"coroutine",
"to",
"wrap",
":",
"param",
"loop",
":",
"The",
... | train | https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/asyncio_compat.py#L10-L23 |
fitnr/twitter_bot_utils | twitter_bot_utils/args.py | add_default_args | def add_default_args(parser, version=None, include=None):
'''
Add default arguments to a parser. These are:
- config: argument for specifying a configuration file.
- user: argument for specifying a user.
- dry-run: option for running without side effects.
- verbose: option for ru... | python | def add_default_args(parser, version=None, include=None):
'''
Add default arguments to a parser. These are:
- config: argument for specifying a configuration file.
- user: argument for specifying a user.
- dry-run: option for running without side effects.
- verbose: option for ru... | [
"def",
"add_default_args",
"(",
"parser",
",",
"version",
"=",
"None",
",",
"include",
"=",
"None",
")",
":",
"include",
"=",
"include",
"or",
"(",
"'config'",
",",
"'user'",
",",
"'dry-run'",
",",
"'verbose'",
",",
"'quiet'",
")",
"if",
"'config'",
"in"... | Add default arguments to a parser. These are:
- config: argument for specifying a configuration file.
- user: argument for specifying a user.
- dry-run: option for running without side effects.
- verbose: option for running verbosely.
- quiet: option for running quietly.
... | [
"Add",
"default",
"arguments",
"to",
"a",
"parser",
".",
"These",
"are",
":",
"-",
"config",
":",
"argument",
"for",
"specifying",
"a",
"configuration",
"file",
".",
"-",
"user",
":",
"argument",
"for",
"specifying",
"a",
"user",
".",
"-",
"dry",
"-",
... | train | https://github.com/fitnr/twitter_bot_utils/blob/21f35afa5048cd3efa54db8cb87d405f69a78a62/twitter_bot_utils/args.py#L21-L53 |
fitnr/twitter_bot_utils | twitter_bot_utils/args.py | parent | def parent(version=None, include=None):
'''
Return the default args as a parent parser, optionally adding a version
Args:
version (str): version to return on <cli> --version
include (Sequence): default arguments to add to cli. Default: (config, user, dry-run, verbose, quiet)
'''
par... | python | def parent(version=None, include=None):
'''
Return the default args as a parent parser, optionally adding a version
Args:
version (str): version to return on <cli> --version
include (Sequence): default arguments to add to cli. Default: (config, user, dry-run, verbose, quiet)
'''
par... | [
"def",
"parent",
"(",
"version",
"=",
"None",
",",
"include",
"=",
"None",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"add_help",
"=",
"False",
")",
"add_default_args",
"(",
"parser",
",",
"version",
"=",
"version",
",",
"include",
... | Return the default args as a parent parser, optionally adding a version
Args:
version (str): version to return on <cli> --version
include (Sequence): default arguments to add to cli. Default: (config, user, dry-run, verbose, quiet) | [
"Return",
"the",
"default",
"args",
"as",
"a",
"parent",
"parser",
"optionally",
"adding",
"a",
"version"
] | train | https://github.com/fitnr/twitter_bot_utils/blob/21f35afa5048cd3efa54db8cb87d405f69a78a62/twitter_bot_utils/args.py#L56-L66 |
fitnr/twitter_bot_utils | twitter_bot_utils/args.py | add_logger | def add_logger(name, level=None, format=None):
'''
Set up a stdout logger.
Args:
name (str): name of the logger
level: defaults to logging.INFO
format (str): format string for logging output.
defaults to ``%(filename)-11s %(lineno)-3d: %(message)s``.
Retur... | python | def add_logger(name, level=None, format=None):
'''
Set up a stdout logger.
Args:
name (str): name of the logger
level: defaults to logging.INFO
format (str): format string for logging output.
defaults to ``%(filename)-11s %(lineno)-3d: %(message)s``.
Retur... | [
"def",
"add_logger",
"(",
"name",
",",
"level",
"=",
"None",
",",
"format",
"=",
"None",
")",
":",
"format",
"=",
"format",
"or",
"'%(filename)-11s %(lineno)-3d: %(message)s'",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"# Set logging level.",
... | Set up a stdout logger.
Args:
name (str): name of the logger
level: defaults to logging.INFO
format (str): format string for logging output.
defaults to ``%(filename)-11s %(lineno)-3d: %(message)s``.
Returns:
The logger object. | [
"Set",
"up",
"a",
"stdout",
"logger",
"."
] | train | https://github.com/fitnr/twitter_bot_utils/blob/21f35afa5048cd3efa54db8cb87d405f69a78a62/twitter_bot_utils/args.py#L69-L92 |
basilfx/flask-daapserver | daapserver/provider.py | Provider.create_session | def create_session(self, user_agent, remote_address, client_version):
"""
Create a new session.
:param str user_agent: Client user agent
:param str remote_addr: Remote address of client
:param str client_version: Remote client version
:return: The new session id
... | python | def create_session(self, user_agent, remote_address, client_version):
"""
Create a new session.
:param str user_agent: Client user agent
:param str remote_addr: Remote address of client
:param str client_version: Remote client version
:return: The new session id
... | [
"def",
"create_session",
"(",
"self",
",",
"user_agent",
",",
"remote_address",
",",
"client_version",
")",
":",
"self",
".",
"session_counter",
"+=",
"1",
"self",
".",
"sessions",
"[",
"self",
".",
"session_counter",
"]",
"=",
"session",
"=",
"self",
".",
... | Create a new session.
:param str user_agent: Client user agent
:param str remote_addr: Remote address of client
:param str client_version: Remote client version
:return: The new session id
:rtype: int | [
"Create",
"a",
"new",
"session",
"."
] | train | https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/provider.py#L96-L118 |
basilfx/flask-daapserver | daapserver/provider.py | Provider.destroy_session | def destroy_session(self, session_id):
"""
Destroy an (existing) session.
"""
try:
del self.sessions[session_id]
except KeyError:
pass
# Invoke hooks
invoke_hooks(self.hooks, "session_destroyed", session_id) | python | def destroy_session(self, session_id):
"""
Destroy an (existing) session.
"""
try:
del self.sessions[session_id]
except KeyError:
pass
# Invoke hooks
invoke_hooks(self.hooks, "session_destroyed", session_id) | [
"def",
"destroy_session",
"(",
"self",
",",
"session_id",
")",
":",
"try",
":",
"del",
"self",
".",
"sessions",
"[",
"session_id",
"]",
"except",
"KeyError",
":",
"pass",
"# Invoke hooks",
"invoke_hooks",
"(",
"self",
".",
"hooks",
",",
"\"session_destroyed\""... | Destroy an (existing) session. | [
"Destroy",
"an",
"(",
"existing",
")",
"session",
"."
] | train | https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/provider.py#L120-L131 |
basilfx/flask-daapserver | daapserver/provider.py | Provider.get_next_revision | def get_next_revision(self, session_id, revision, delta):
"""
Determine the next revision number for a given session id, revision
and delta.
In case the client is up-to-date, this method will block until the next
revision is available.
:param int session_id: Session ide... | python | def get_next_revision(self, session_id, revision, delta):
"""
Determine the next revision number for a given session id, revision
and delta.
In case the client is up-to-date, this method will block until the next
revision is available.
:param int session_id: Session ide... | [
"def",
"get_next_revision",
"(",
"self",
",",
"session_id",
",",
"revision",
",",
"delta",
")",
":",
"session",
"=",
"self",
".",
"sessions",
"[",
"session_id",
"]",
"session",
".",
"state",
"=",
"State",
".",
"connected",
"if",
"delta",
"==",
"revision",
... | Determine the next revision number for a given session id, revision
and delta.
In case the client is up-to-date, this method will block until the next
revision is available.
:param int session_id: Session identifier
:param int revision: Client revision number
:param int... | [
"Determine",
"the",
"next",
"revision",
"number",
"for",
"a",
"given",
"session",
"id",
"revision",
"and",
"delta",
"."
] | train | https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/provider.py#L133-L158 |
basilfx/flask-daapserver | daapserver/provider.py | Provider.update | def update(self):
"""
Update this provider. Should be invoked when the server gets updated.
This method will notify all clients that wait for
`self.next_revision_available`.
"""
with self.lock:
# Increment revision and commit it.
self.revision +=... | python | def update(self):
"""
Update this provider. Should be invoked when the server gets updated.
This method will notify all clients that wait for
`self.next_revision_available`.
"""
with self.lock:
# Increment revision and commit it.
self.revision +=... | [
"def",
"update",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"# Increment revision and commit it.",
"self",
".",
"revision",
"+=",
"1",
"self",
".",
"server",
".",
"commit",
"(",
"self",
".",
"revision",
"+",
"1",
")",
"# Unblock all waiting cli... | Update this provider. Should be invoked when the server gets updated.
This method will notify all clients that wait for
`self.next_revision_available`. | [
"Update",
"this",
"provider",
".",
"Should",
"be",
"invoked",
"when",
"the",
"server",
"gets",
"updated",
"."
] | train | https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/provider.py#L160-L187 |
basilfx/flask-daapserver | daapserver/provider.py | LocalFileProvider.get_item_data | def get_item_data(self, session, item, byte_range=None):
"""
Return a file pointer to the item file. Assumes `item.file_name` points
to the file on disk.
"""
# Parse byte range
if byte_range is not None:
begin, end = parse_byte_range(byte_range, max_byte=item... | python | def get_item_data(self, session, item, byte_range=None):
"""
Return a file pointer to the item file. Assumes `item.file_name` points
to the file on disk.
"""
# Parse byte range
if byte_range is not None:
begin, end = parse_byte_range(byte_range, max_byte=item... | [
"def",
"get_item_data",
"(",
"self",
",",
"session",
",",
"item",
",",
"byte_range",
"=",
"None",
")",
":",
"# Parse byte range",
"if",
"byte_range",
"is",
"not",
"None",
":",
"begin",
",",
"end",
"=",
"parse_byte_range",
"(",
"byte_range",
",",
"max_byte",
... | Return a file pointer to the item file. Assumes `item.file_name` points
to the file on disk. | [
"Return",
"a",
"file",
"pointer",
"to",
"the",
"item",
"file",
".",
"Assumes",
"item",
".",
"file_name",
"points",
"to",
"the",
"file",
"on",
"disk",
"."
] | train | https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/provider.py#L356-L382 |
PMBio/limix-backup | limix/mtSet/core/plink_reader.py | readBIM | def readBIM(basefilename,usecols=None):
"""
helper method for speeding up read BED
"""
bim = basefilename+ '.bim'
bim = SP.loadtxt(bim,dtype=bytes,usecols=usecols)
return bim | python | def readBIM(basefilename,usecols=None):
"""
helper method for speeding up read BED
"""
bim = basefilename+ '.bim'
bim = SP.loadtxt(bim,dtype=bytes,usecols=usecols)
return bim | [
"def",
"readBIM",
"(",
"basefilename",
",",
"usecols",
"=",
"None",
")",
":",
"bim",
"=",
"basefilename",
"+",
"'.bim'",
"bim",
"=",
"SP",
".",
"loadtxt",
"(",
"bim",
",",
"dtype",
"=",
"bytes",
",",
"usecols",
"=",
"usecols",
")",
"return",
"bim"
] | helper method for speeding up read BED | [
"helper",
"method",
"for",
"speeding",
"up",
"read",
"BED"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/mtSet/core/plink_reader.py#L27-L33 |
PMBio/limix-backup | limix/mtSet/core/plink_reader.py | readFAM | def readFAM(basefilename,usecols=None):
"""
helper method for speeding up read FAM
"""
fam = basefilename+'.fam'
fam = SP.loadtxt(fam,dtype=bytes,usecols=usecols)
return fam | python | def readFAM(basefilename,usecols=None):
"""
helper method for speeding up read FAM
"""
fam = basefilename+'.fam'
fam = SP.loadtxt(fam,dtype=bytes,usecols=usecols)
return fam | [
"def",
"readFAM",
"(",
"basefilename",
",",
"usecols",
"=",
"None",
")",
":",
"fam",
"=",
"basefilename",
"+",
"'.fam'",
"fam",
"=",
"SP",
".",
"loadtxt",
"(",
"fam",
",",
"dtype",
"=",
"bytes",
",",
"usecols",
"=",
"usecols",
")",
"return",
"fam"
] | helper method for speeding up read FAM | [
"helper",
"method",
"for",
"speeding",
"up",
"read",
"FAM"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/mtSet/core/plink_reader.py#L36-L42 |
PMBio/limix-backup | limix/mtSet/core/plink_reader.py | readBED | def readBED(basefilename, useMAFencoding=False,blocksize = 1, start = 0, nSNPs = SP.inf, startpos = None, endpos = None, order = 'F',standardizeSNPs=False,ipos = 2,bim=None,fam=None):
'''
read [basefilename].bed,[basefilename].bim,[basefilename].fam
---------------------------------------------------------... | python | def readBED(basefilename, useMAFencoding=False,blocksize = 1, start = 0, nSNPs = SP.inf, startpos = None, endpos = None, order = 'F',standardizeSNPs=False,ipos = 2,bim=None,fam=None):
'''
read [basefilename].bed,[basefilename].bim,[basefilename].fam
---------------------------------------------------------... | [
"def",
"readBED",
"(",
"basefilename",
",",
"useMAFencoding",
"=",
"False",
",",
"blocksize",
"=",
"1",
",",
"start",
"=",
"0",
",",
"nSNPs",
"=",
"SP",
".",
"inf",
",",
"startpos",
"=",
"None",
",",
"endpos",
"=",
"None",
",",
"order",
"=",
"'F'",
... | read [basefilename].bed,[basefilename].bim,[basefilename].fam
--------------------------------------------------------------------------
Input:
basefilename : string of the basename of [basename].bed, [basename].bim,
and [basename].fam
blocksize : load blocksize SNPs at a ... | [
"read",
"[",
"basefilename",
"]",
".",
"bed",
"[",
"basefilename",
"]",
".",
"bim",
"[",
"basefilename",
"]",
".",
"fam",
"--------------------------------------------------------------------------",
"Input",
":",
"basefilename",
":",
"string",
"of",
"the",
"basename"... | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/mtSet/core/plink_reader.py#L45-L194 |
grycap/cpyutils | iputils.py | ip2hex | def ip2hex(ip):
'''
Converts an ip to a hex value that can be used with a hex bit mask
'''
parts = ip.split(".")
if len(parts) != 4: return None
ipv = 0
for part in parts:
try:
p = int(part)
if p < 0 or p > 255: return None
ipv = (ipv << 8) + p
... | python | def ip2hex(ip):
'''
Converts an ip to a hex value that can be used with a hex bit mask
'''
parts = ip.split(".")
if len(parts) != 4: return None
ipv = 0
for part in parts:
try:
p = int(part)
if p < 0 or p > 255: return None
ipv = (ipv << 8) + p
... | [
"def",
"ip2hex",
"(",
"ip",
")",
":",
"parts",
"=",
"ip",
".",
"split",
"(",
"\".\"",
")",
"if",
"len",
"(",
"parts",
")",
"!=",
"4",
":",
"return",
"None",
"ipv",
"=",
"0",
"for",
"part",
"in",
"parts",
":",
"try",
":",
"p",
"=",
"int",
"(",... | Converts an ip to a hex value that can be used with a hex bit mask | [
"Converts",
"an",
"ip",
"to",
"a",
"hex",
"value",
"that",
"can",
"be",
"used",
"with",
"a",
"hex",
"bit",
"mask"
] | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/iputils.py#L19-L33 |
grycap/cpyutils | iputils.py | str_to_ipmask | def str_to_ipmask(ipmask):
'''
Converts a string with the notation ip/mask (e.g. 192.168.1.1/24 or 192.168.1.1/255.255.255.0) to an hex mask
'''
v = ipmask.split("/")
if len(v) > 2: raise Exception("bad mask format")
mask_ip = ip2hex(v[0])
if mask_ip is None: raise Exception("bad mask format... | python | def str_to_ipmask(ipmask):
'''
Converts a string with the notation ip/mask (e.g. 192.168.1.1/24 or 192.168.1.1/255.255.255.0) to an hex mask
'''
v = ipmask.split("/")
if len(v) > 2: raise Exception("bad mask format")
mask_ip = ip2hex(v[0])
if mask_ip is None: raise Exception("bad mask format... | [
"def",
"str_to_ipmask",
"(",
"ipmask",
")",
":",
"v",
"=",
"ipmask",
".",
"split",
"(",
"\"/\"",
")",
"if",
"len",
"(",
"v",
")",
">",
"2",
":",
"raise",
"Exception",
"(",
"\"bad mask format\"",
")",
"mask_ip",
"=",
"ip2hex",
"(",
"v",
"[",
"0",
"]... | Converts a string with the notation ip/mask (e.g. 192.168.1.1/24 or 192.168.1.1/255.255.255.0) to an hex mask | [
"Converts",
"a",
"string",
"with",
"the",
"notation",
"ip",
"/",
"mask",
"(",
"e",
".",
"g",
".",
"192",
".",
"168",
".",
"1",
".",
"1",
"/",
"24",
"or",
"192",
".",
"168",
".",
"1",
".",
"1",
"/",
"255",
".",
"255",
".",
"255",
".",
"0",
... | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/iputils.py#L35-L50 |
grycap/cpyutils | iputils.py | ip_in_ip_mask | def ip_in_ip_mask(ip, mask_ip, mask):
'''
Checks whether an ip is contained in an ip subnet where the subnet is stated as an ip in the dotted format, and a hex mask
'''
ip = ip2hex(ip)
if ip is None: raise Exception("bad ip format")
if (mask_ip & mask) == (ip & mask):
return True
ret... | python | def ip_in_ip_mask(ip, mask_ip, mask):
'''
Checks whether an ip is contained in an ip subnet where the subnet is stated as an ip in the dotted format, and a hex mask
'''
ip = ip2hex(ip)
if ip is None: raise Exception("bad ip format")
if (mask_ip & mask) == (ip & mask):
return True
ret... | [
"def",
"ip_in_ip_mask",
"(",
"ip",
",",
"mask_ip",
",",
"mask",
")",
":",
"ip",
"=",
"ip2hex",
"(",
"ip",
")",
"if",
"ip",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"bad ip format\"",
")",
"if",
"(",
"mask_ip",
"&",
"mask",
")",
"==",
"(",
"i... | Checks whether an ip is contained in an ip subnet where the subnet is stated as an ip in the dotted format, and a hex mask | [
"Checks",
"whether",
"an",
"ip",
"is",
"contained",
"in",
"an",
"ip",
"subnet",
"where",
"the",
"subnet",
"is",
"stated",
"as",
"an",
"ip",
"in",
"the",
"dotted",
"format",
"and",
"a",
"hex",
"mask"
] | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/iputils.py#L53-L61 |
grycap/cpyutils | iputils.py | ip_in_ipmask | def ip_in_ipmask(ip, ipmask):
'''
Checks whether an ip is contained in an ip subnet where the subnet is a string with the notation ip/mask (e.g. 192.168.1.1/24 or 192.168.1.1/255.255.255.0)
'''
mask_ip, mask = str_to_ipmask(ipmask)
return ip_in_ip_mask(ip, mask_ip, mask) | python | def ip_in_ipmask(ip, ipmask):
'''
Checks whether an ip is contained in an ip subnet where the subnet is a string with the notation ip/mask (e.g. 192.168.1.1/24 or 192.168.1.1/255.255.255.0)
'''
mask_ip, mask = str_to_ipmask(ipmask)
return ip_in_ip_mask(ip, mask_ip, mask) | [
"def",
"ip_in_ipmask",
"(",
"ip",
",",
"ipmask",
")",
":",
"mask_ip",
",",
"mask",
"=",
"str_to_ipmask",
"(",
"ipmask",
")",
"return",
"ip_in_ip_mask",
"(",
"ip",
",",
"mask_ip",
",",
"mask",
")"
] | Checks whether an ip is contained in an ip subnet where the subnet is a string with the notation ip/mask (e.g. 192.168.1.1/24 or 192.168.1.1/255.255.255.0) | [
"Checks",
"whether",
"an",
"ip",
"is",
"contained",
"in",
"an",
"ip",
"subnet",
"where",
"the",
"subnet",
"is",
"a",
"string",
"with",
"the",
"notation",
"ip",
"/",
"mask",
"(",
"e",
".",
"g",
".",
"192",
".",
"168",
".",
"1",
".",
"1",
"/",
"24"... | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/iputils.py#L63-L68 |
grycap/cpyutils | iputils.py | check_mac | def check_mac(original_mac):
'''
Checks the format of a MAC address and returns it without double-colons and in capital letters, if it is correct. Otherwise it returns None.
* it accepts the format of the double colons and a single hex string
'''
mac = (original_mac.upper()).strip()
parts = mac.... | python | def check_mac(original_mac):
'''
Checks the format of a MAC address and returns it without double-colons and in capital letters, if it is correct. Otherwise it returns None.
* it accepts the format of the double colons and a single hex string
'''
mac = (original_mac.upper()).strip()
parts = mac.... | [
"def",
"check_mac",
"(",
"original_mac",
")",
":",
"mac",
"=",
"(",
"original_mac",
".",
"upper",
"(",
")",
")",
".",
"strip",
"(",
")",
"parts",
"=",
"mac",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"6",
":",
"# let's ... | Checks the format of a MAC address and returns it without double-colons and in capital letters, if it is correct. Otherwise it returns None.
* it accepts the format of the double colons and a single hex string | [
"Checks",
"the",
"format",
"of",
"a",
"MAC",
"address",
"and",
"returns",
"it",
"without",
"double",
"-",
"colons",
"and",
"in",
"capital",
"letters",
"if",
"it",
"is",
"correct",
".",
"Otherwise",
"it",
"returns",
"None",
".",
"*",
"it",
"accepts",
"the... | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/iputils.py#L70-L88 |
grycap/cpyutils | iputils.py | check_ip | def check_ip(original_ip):
'''
Checks the format of an IP address and returns it if it is correct. Otherwise it returns None.
'''
ip = original_ip.strip()
parts = ip.split('.')
if len(parts) != 4:
return None
for p in parts:
try:
p = int(p)
if (p < 0)... | python | def check_ip(original_ip):
'''
Checks the format of an IP address and returns it if it is correct. Otherwise it returns None.
'''
ip = original_ip.strip()
parts = ip.split('.')
if len(parts) != 4:
return None
for p in parts:
try:
p = int(p)
if (p < 0)... | [
"def",
"check_ip",
"(",
"original_ip",
")",
":",
"ip",
"=",
"original_ip",
".",
"strip",
"(",
")",
"parts",
"=",
"ip",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"parts",
")",
"!=",
"4",
":",
"return",
"None",
"for",
"p",
"in",
"parts",
":"... | Checks the format of an IP address and returns it if it is correct. Otherwise it returns None. | [
"Checks",
"the",
"format",
"of",
"an",
"IP",
"address",
"and",
"returns",
"it",
"if",
"it",
"is",
"correct",
".",
"Otherwise",
"it",
"returns",
"None",
"."
] | train | https://github.com/grycap/cpyutils/blob/fa966fc6d2ae1e1e799e19941561aa79b617f1b1/iputils.py#L90-L105 |
jhshi/wltrace | wltrace/peektagged.py | PeektaggedPacketHeader.to_phy | def to_phy(self):
"""Convert this to the standard :class:`pyparser.capture.common.PhyInfo`
class.
"""
kwargs = {}
for attr in ['signal', 'noise', 'freq_mhz', 'fcs_error', 'rate', 'mcs',
'len', 'caplen', 'epoch_ts', 'end_epoch_ts']:
kwargs[attr] = ... | python | def to_phy(self):
"""Convert this to the standard :class:`pyparser.capture.common.PhyInfo`
class.
"""
kwargs = {}
for attr in ['signal', 'noise', 'freq_mhz', 'fcs_error', 'rate', 'mcs',
'len', 'caplen', 'epoch_ts', 'end_epoch_ts']:
kwargs[attr] = ... | [
"def",
"to_phy",
"(",
"self",
")",
":",
"kwargs",
"=",
"{",
"}",
"for",
"attr",
"in",
"[",
"'signal'",
",",
"'noise'",
",",
"'freq_mhz'",
",",
"'fcs_error'",
",",
"'rate'",
",",
"'mcs'",
",",
"'len'",
",",
"'caplen'",
",",
"'epoch_ts'",
",",
"'end_epoc... | Convert this to the standard :class:`pyparser.capture.common.PhyInfo`
class. | [
"Convert",
"this",
"to",
"the",
"standard",
":",
"class",
":",
"pyparser",
".",
"capture",
".",
"common",
".",
"PhyInfo",
"class",
"."
] | train | https://github.com/jhshi/wltrace/blob/4c8441162f7cddd47375da2effc52c95b97dc81d/wltrace/peektagged.py#L126-L135 |
rjw57/starman | starman/slh.py | slh_associate | def slh_associate(a_features, b_features, max_sigma=5):
"""
An implementation of the Scott and Longuet-Higgins algorithm for feature
association.
This function takes two lists of features. Each feature is a
:py:class:`MultivariateNormal` instance representing a feature
location and its associat... | python | def slh_associate(a_features, b_features, max_sigma=5):
"""
An implementation of the Scott and Longuet-Higgins algorithm for feature
association.
This function takes two lists of features. Each feature is a
:py:class:`MultivariateNormal` instance representing a feature
location and its associat... | [
"def",
"slh_associate",
"(",
"a_features",
",",
"b_features",
",",
"max_sigma",
"=",
"5",
")",
":",
"# Compute proximity matrix",
"proximity",
"=",
"_weighted_proximity",
"(",
"a_features",
",",
"b_features",
")",
"# Compute association matrix",
"association_matrix",
"=... | An implementation of the Scott and Longuet-Higgins algorithm for feature
association.
This function takes two lists of features. Each feature is a
:py:class:`MultivariateNormal` instance representing a feature
location and its associated uncertainty.
Args:
a_features (list of MultivariateN... | [
"An",
"implementation",
"of",
"the",
"Scott",
"and",
"Longuet",
"-",
"Higgins",
"algorithm",
"for",
"feature",
"association",
"."
] | train | https://github.com/rjw57/starman/blob/1f9475e2354c9630a61f4898ad871de1d2fdbc71/starman/slh.py#L7-L61 |
rjw57/starman | starman/slh.py | _proximity_to_association | def _proximity_to_association(proximity):
"""SLH algorithm for increasing orthogonality of a matrix."""
# pylint:disable=invalid-name
# I'm afraid that the short names here are just a function of the
# mathematical nature of the code.
# Special case: zero-size matrix
if proximity.shape[0] == 0 ... | python | def _proximity_to_association(proximity):
"""SLH algorithm for increasing orthogonality of a matrix."""
# pylint:disable=invalid-name
# I'm afraid that the short names here are just a function of the
# mathematical nature of the code.
# Special case: zero-size matrix
if proximity.shape[0] == 0 ... | [
"def",
"_proximity_to_association",
"(",
"proximity",
")",
":",
"# pylint:disable=invalid-name",
"# I'm afraid that the short names here are just a function of the",
"# mathematical nature of the code.",
"# Special case: zero-size matrix",
"if",
"proximity",
".",
"shape",
"[",
"0",
"... | SLH algorithm for increasing orthogonality of a matrix. | [
"SLH",
"algorithm",
"for",
"increasing",
"orthogonality",
"of",
"a",
"matrix",
"."
] | train | https://github.com/rjw57/starman/blob/1f9475e2354c9630a61f4898ad871de1d2fdbc71/starman/slh.py#L75-L95 |
bretth/woven | woven/virtualenv.py | active_version | def active_version():
"""
Determine the current active version on the server
Just examine the which environment is symlinked
"""
link = '/'.join([deployment_root(),'env',env.project_name])
if not exists(link): return None
active = os.path.split(run('ls -al '+link).split(' -> ')[1])... | python | def active_version():
"""
Determine the current active version on the server
Just examine the which environment is symlinked
"""
link = '/'.join([deployment_root(),'env',env.project_name])
if not exists(link): return None
active = os.path.split(run('ls -al '+link).split(' -> ')[1])... | [
"def",
"active_version",
"(",
")",
":",
"link",
"=",
"'/'",
".",
"join",
"(",
"[",
"deployment_root",
"(",
")",
",",
"'env'",
",",
"env",
".",
"project_name",
"]",
")",
"if",
"not",
"exists",
"(",
"link",
")",
":",
"return",
"None",
"active",
"=",
... | Determine the current active version on the server
Just examine the which environment is symlinked | [
"Determine",
"the",
"current",
"active",
"version",
"on",
"the",
"server",
"Just",
"examine",
"the",
"which",
"environment",
"is",
"symlinked"
] | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/virtualenv.py#L24-L34 |
bretth/woven | woven/virtualenv.py | activate | def activate():
"""
Activates the version specified in ``env.project_version`` if it is different
from the current active version.
An active version is just the version that is symlinked.
"""
env_path = '/'.join([deployment_root(),'env',env.project_fullname])
if not exists(env_path):
... | python | def activate():
"""
Activates the version specified in ``env.project_version`` if it is different
from the current active version.
An active version is just the version that is symlinked.
"""
env_path = '/'.join([deployment_root(),'env',env.project_fullname])
if not exists(env_path):
... | [
"def",
"activate",
"(",
")",
":",
"env_path",
"=",
"'/'",
".",
"join",
"(",
"[",
"deployment_root",
"(",
")",
",",
"'env'",
",",
"env",
".",
"project_fullname",
"]",
")",
"if",
"not",
"exists",
"(",
"env_path",
")",
":",
"print",
"env",
".",
"host",
... | Activates the version specified in ``env.project_version`` if it is different
from the current active version.
An active version is just the version that is symlinked. | [
"Activates",
"the",
"version",
"specified",
"in",
"env",
".",
"project_version",
"if",
"it",
"is",
"different",
"from",
"the",
"current",
"active",
"version",
".",
"An",
"active",
"version",
"is",
"just",
"the",
"version",
"that",
"is",
"symlinked",
"."
] | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/virtualenv.py#L36-L113 |
bretth/woven | woven/virtualenv.py | sync_db | def sync_db():
"""
Runs the django syncdb command
"""
with cd('/'.join([deployment_root(),'env',env.project_fullname,'project',env.project_package_name,'sitesettings'])):
venv = '/'.join([deployment_root(),'env',env.project_fullname,'bin','activate'])
sites = _get_django_sites()
... | python | def sync_db():
"""
Runs the django syncdb command
"""
with cd('/'.join([deployment_root(),'env',env.project_fullname,'project',env.project_package_name,'sitesettings'])):
venv = '/'.join([deployment_root(),'env',env.project_fullname,'bin','activate'])
sites = _get_django_sites()
... | [
"def",
"sync_db",
"(",
")",
":",
"with",
"cd",
"(",
"'/'",
".",
"join",
"(",
"[",
"deployment_root",
"(",
")",
",",
"'env'",
",",
"env",
".",
"project_fullname",
",",
"'project'",
",",
"env",
".",
"project_package_name",
",",
"'sitesettings'",
"]",
")",
... | Runs the django syncdb command | [
"Runs",
"the",
"django",
"syncdb",
"command"
] | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/virtualenv.py#L116-L133 |
bretth/woven | woven/virtualenv.py | manual_migration | def manual_migration():
"""
Simple interactive function to pause the deployment.
A manual migration can be done two different ways:
Option 1: Enter y to exit the current deployment. When migration is completed run deploy again.
Option 2: run the migration in a separate shell
"""
if env.IN... | python | def manual_migration():
"""
Simple interactive function to pause the deployment.
A manual migration can be done two different ways:
Option 1: Enter y to exit the current deployment. When migration is completed run deploy again.
Option 2: run the migration in a separate shell
"""
if env.IN... | [
"def",
"manual_migration",
"(",
")",
":",
"if",
"env",
".",
"INTERACTIVITY",
":",
"print",
"\"A manual migration can be done two different ways:\"",
"print",
"\"Option 1: Enter y to exit the current deployment. When migration is completed run deploy again.\"",
"print",
"\"Option 2: run... | Simple interactive function to pause the deployment.
A manual migration can be done two different ways:
Option 1: Enter y to exit the current deployment. When migration is completed run deploy again.
Option 2: run the migration in a separate shell | [
"Simple",
"interactive",
"function",
"to",
"pause",
"the",
"deployment",
".",
"A",
"manual",
"migration",
"can",
"be",
"done",
"two",
"different",
"ways",
":",
"Option",
"1",
":",
"Enter",
"y",
"to",
"exit",
"the",
"current",
"deployment",
".",
"When",
"mi... | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/virtualenv.py#L136-L152 |
bretth/woven | woven/virtualenv.py | migration | def migration():
"""
Integrate with south schema migration
"""
#activate env
with cd('/'.join([deployment_root(),'env',env.project_fullname,'project',env.project_package_name,'sitesettings'])):
#migrates all or specific env.migration
venv = '/'.join([deployment_root(),'env',... | python | def migration():
"""
Integrate with south schema migration
"""
#activate env
with cd('/'.join([deployment_root(),'env',env.project_fullname,'project',env.project_package_name,'sitesettings'])):
#migrates all or specific env.migration
venv = '/'.join([deployment_root(),'env',... | [
"def",
"migration",
"(",
")",
":",
"#activate env ",
"with",
"cd",
"(",
"'/'",
".",
"join",
"(",
"[",
"deployment_root",
"(",
")",
",",
"'env'",
",",
"env",
".",
"project_fullname",
",",
"'project'",
",",
"env",
".",
"project_package_name",
",",
"'s... | Integrate with south schema migration | [
"Integrate",
"with",
"south",
"schema",
"migration"
] | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/virtualenv.py#L155-L181 |
bretth/woven | woven/virtualenv.py | mkvirtualenv | def mkvirtualenv():
"""
Create the virtualenv project environment
"""
root = '/'.join([deployment_root(),'env'])
path = '/'.join([root,env.project_fullname])
dirs_created = []
if env.verbosity:
print env.host,'CREATING VIRTUALENV', path
if not exists(root): dirs_created += mkdirs... | python | def mkvirtualenv():
"""
Create the virtualenv project environment
"""
root = '/'.join([deployment_root(),'env'])
path = '/'.join([root,env.project_fullname])
dirs_created = []
if env.verbosity:
print env.host,'CREATING VIRTUALENV', path
if not exists(root): dirs_created += mkdirs... | [
"def",
"mkvirtualenv",
"(",
")",
":",
"root",
"=",
"'/'",
".",
"join",
"(",
"[",
"deployment_root",
"(",
")",
",",
"'env'",
"]",
")",
"path",
"=",
"'/'",
".",
"join",
"(",
"[",
"root",
",",
"env",
".",
"project_fullname",
"]",
")",
"dirs_created",
... | Create the virtualenv project environment | [
"Create",
"the",
"virtualenv",
"project",
"environment"
] | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/virtualenv.py#L184-L207 |
bretth/woven | woven/virtualenv.py | rmvirtualenv | def rmvirtualenv():
"""
Remove the current or ``env.project_version`` environment and all content in it
"""
path = '/'.join([deployment_root(),'env',env.project_fullname])
link = '/'.join([deployment_root(),'env',env.project_name])
if version_state('mkvirtualenv'):
sudo(' '.join(['rm -rf... | python | def rmvirtualenv():
"""
Remove the current or ``env.project_version`` environment and all content in it
"""
path = '/'.join([deployment_root(),'env',env.project_fullname])
link = '/'.join([deployment_root(),'env',env.project_name])
if version_state('mkvirtualenv'):
sudo(' '.join(['rm -rf... | [
"def",
"rmvirtualenv",
"(",
")",
":",
"path",
"=",
"'/'",
".",
"join",
"(",
"[",
"deployment_root",
"(",
")",
",",
"'env'",
",",
"env",
".",
"project_fullname",
"]",
")",
"link",
"=",
"'/'",
".",
"join",
"(",
"[",
"deployment_root",
"(",
")",
",",
... | Remove the current or ``env.project_version`` environment and all content in it | [
"Remove",
"the",
"current",
"or",
"env",
".",
"project_version",
"environment",
"and",
"all",
"content",
"in",
"it"
] | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/virtualenv.py#L209-L219 |
bretth/woven | woven/virtualenv.py | pip_install_requirements | def pip_install_requirements():
"""
Install on current installed virtualenv version from a pip bundle [dist/project name-version].zip or pip ``req.txt``|``requirements.txt``
or a env.pip_requirements list.
By default it will look for a zip bundle in the dist directory first then a requirements file... | python | def pip_install_requirements():
"""
Install on current installed virtualenv version from a pip bundle [dist/project name-version].zip or pip ``req.txt``|``requirements.txt``
or a env.pip_requirements list.
By default it will look for a zip bundle in the dist directory first then a requirements file... | [
"def",
"pip_install_requirements",
"(",
")",
":",
"if",
"not",
"version_state",
"(",
"'mkvirtualenv'",
")",
":",
"print",
"env",
".",
"host",
",",
"'Error: Cannot run pip_install_requirements. A virtualenv is not created for this version. Run mkvirtualenv first'",
"return",
"if... | Install on current installed virtualenv version from a pip bundle [dist/project name-version].zip or pip ``req.txt``|``requirements.txt``
or a env.pip_requirements list.
By default it will look for a zip bundle in the dist directory first then a requirements file.
The limitations of installing re... | [
"Install",
"on",
"current",
"installed",
"virtualenv",
"version",
"from",
"a",
"pip",
"bundle",
"[",
"dist",
"/",
"project",
"name",
"-",
"version",
"]",
".",
"zip",
"or",
"pip",
"req",
".",
"txt",
"|",
"requirements",
".",
"txt",
"or",
"a",
"env",
"."... | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/virtualenv.py#L223-L329 |
StyXman/ayrton | ayrton/functions.py | shift | def shift (*args):
"""`shift()` returns the leftmost element of `argv`.
`shitf(integer)` return the `integer` leftmost elements of `argv` as a list.
`shift(iterable)` and `shift(iterable, integer)` operate over `iterable`."""
if len(args) > 2:
raise ValueError("shift() takes 0, 1 or 2 arguments.... | python | def shift (*args):
"""`shift()` returns the leftmost element of `argv`.
`shitf(integer)` return the `integer` leftmost elements of `argv` as a list.
`shift(iterable)` and `shift(iterable, integer)` operate over `iterable`."""
if len(args) > 2:
raise ValueError("shift() takes 0, 1 or 2 arguments.... | [
"def",
"shift",
"(",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"2",
":",
"raise",
"ValueError",
"(",
"\"shift() takes 0, 1 or 2 arguments.\"",
")",
"n",
"=",
"1",
"l",
"=",
"ayrton",
".",
"runner",
".",
"globals",
"[",
"'argv'",
"]",
... | `shift()` returns the leftmost element of `argv`.
`shitf(integer)` return the `integer` leftmost elements of `argv` as a list.
`shift(iterable)` and `shift(iterable, integer)` operate over `iterable`. | [
"shift",
"()",
"returns",
"the",
"leftmost",
"element",
"of",
"argv",
".",
"shitf",
"(",
"integer",
")",
"return",
"the",
"integer",
"leftmost",
"elements",
"of",
"argv",
"as",
"a",
"list",
".",
"shift",
"(",
"iterable",
")",
"and",
"shift",
"(",
"iterab... | train | https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/functions.py#L105-L138 |
ssato/python-anytemplate | anytemplate/engines/pystache.py | Engine._make_renderer | def _make_renderer(self, at_paths, at_encoding, **kwargs):
"""
:param at_paths: Template search paths
:param at_encoding: Template encoding
:param kwargs: Keyword arguments passed to the template engine to
render templates with specific features enabled.
"""
f... | python | def _make_renderer(self, at_paths, at_encoding, **kwargs):
"""
:param at_paths: Template search paths
:param at_encoding: Template encoding
:param kwargs: Keyword arguments passed to the template engine to
render templates with specific features enabled.
"""
f... | [
"def",
"_make_renderer",
"(",
"self",
",",
"at_paths",
",",
"at_encoding",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"eopt",
"in",
"(",
"\"file_encoding\"",
",",
"\"string_encoding\"",
")",
":",
"default",
"=",
"self",
".",
"_roptions",
".",
"get",
"(",
... | :param at_paths: Template search paths
:param at_encoding: Template encoding
:param kwargs: Keyword arguments passed to the template engine to
render templates with specific features enabled. | [
":",
"param",
"at_paths",
":",
"Template",
"search",
"paths",
":",
"param",
"at_encoding",
":",
"Template",
"encoding",
":",
"param",
"kwargs",
":",
"Keyword",
"arguments",
"passed",
"to",
"the",
"template",
"engine",
"to",
"render",
"templates",
"with",
"spec... | train | https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/engines/pystache.py#L61-L78 |
ssato/python-anytemplate | anytemplate/engines/pystache.py | Engine.renders_impl | def renders_impl(self, template_content, context, at_paths=None,
at_encoding=anytemplate.compat.ENCODING,
**kwargs):
"""
Render given template string and return the result.
:param template_content: Template content
:param context: A dict or dict... | python | def renders_impl(self, template_content, context, at_paths=None,
at_encoding=anytemplate.compat.ENCODING,
**kwargs):
"""
Render given template string and return the result.
:param template_content: Template content
:param context: A dict or dict... | [
"def",
"renders_impl",
"(",
"self",
",",
"template_content",
",",
"context",
",",
"at_paths",
"=",
"None",
",",
"at_encoding",
"=",
"anytemplate",
".",
"compat",
".",
"ENCODING",
",",
"*",
"*",
"kwargs",
")",
":",
"renderer",
"=",
"self",
".",
"_make_rende... | Render given template string and return the result.
:param template_content: Template content
:param context: A dict or dict-like object to instantiate given
template file
:param at_paths: Template search paths
:param at_encoding: Template encoding
:param kwargs: Key... | [
"Render",
"given",
"template",
"string",
"and",
"return",
"the",
"result",
"."
] | train | https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/engines/pystache.py#L80-L99 |
ssato/python-anytemplate | anytemplate/engines/pystache.py | Engine.render_impl | def render_impl(self, template, context, at_paths=None,
at_encoding=anytemplate.compat.ENCODING, **kwargs):
"""
Render given template file and return the result.
:param template: Template file path
:param context: A dict or dict-like object to instantiate given
... | python | def render_impl(self, template, context, at_paths=None,
at_encoding=anytemplate.compat.ENCODING, **kwargs):
"""
Render given template file and return the result.
:param template: Template file path
:param context: A dict or dict-like object to instantiate given
... | [
"def",
"render_impl",
"(",
"self",
",",
"template",
",",
"context",
",",
"at_paths",
"=",
"None",
",",
"at_encoding",
"=",
"anytemplate",
".",
"compat",
".",
"ENCODING",
",",
"*",
"*",
"kwargs",
")",
":",
"renderer",
"=",
"self",
".",
"_make_renderer",
"... | Render given template file and return the result.
:param template: Template file path
:param context: A dict or dict-like object to instantiate given
template file
:param at_paths: Template search paths
:param at_encoding: Template encoding
:param kwargs: Keyword arg... | [
"Render",
"given",
"template",
"file",
"and",
"return",
"the",
"result",
"."
] | train | https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/engines/pystache.py#L101-L125 |
basilfx/flask-daapserver | utils/benchmark_store.py | parse_arguments | def parse_arguments():
"""
Parse commandline arguments.
"""
parser = argparse.ArgumentParser()
# Add options
parser.add_argument(
"-n", "--number", action="store", default=1000000, type=int,
help="number of items")
parser.add_argument(
"-p", "--pause", action="store... | python | def parse_arguments():
"""
Parse commandline arguments.
"""
parser = argparse.ArgumentParser()
# Add options
parser.add_argument(
"-n", "--number", action="store", default=1000000, type=int,
help="number of items")
parser.add_argument(
"-p", "--pause", action="store... | [
"def",
"parse_arguments",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"# Add options",
"parser",
".",
"add_argument",
"(",
"\"-n\"",
",",
"\"--number\"",
",",
"action",
"=",
"\"store\"",
",",
"default",
"=",
"1000000",
",",
"ty... | Parse commandline arguments. | [
"Parse",
"commandline",
"arguments",
"."
] | train | https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/utils/benchmark_store.py#L9-L24 |
basilfx/flask-daapserver | utils/benchmark_store.py | main | def main():
"""
Run a benchmark for N items. If N is not specified, take 1,000,000 for N.
"""
# Parse arguments and configure application instance.
arguments, parser = parse_arguments()
# Start iterating
store = RevisionStore()
sys.stdout.write("Iterating over %d items.\n" % arguments.... | python | def main():
"""
Run a benchmark for N items. If N is not specified, take 1,000,000 for N.
"""
# Parse arguments and configure application instance.
arguments, parser = parse_arguments()
# Start iterating
store = RevisionStore()
sys.stdout.write("Iterating over %d items.\n" % arguments.... | [
"def",
"main",
"(",
")",
":",
"# Parse arguments and configure application instance.",
"arguments",
",",
"parser",
"=",
"parse_arguments",
"(",
")",
"# Start iterating",
"store",
"=",
"RevisionStore",
"(",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"Iterating o... | Run a benchmark for N items. If N is not specified, take 1,000,000 for N. | [
"Run",
"a",
"benchmark",
"for",
"N",
"items",
".",
"If",
"N",
"is",
"not",
"specified",
"take",
"1",
"000",
"000",
"for",
"N",
"."
] | train | https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/utils/benchmark_store.py#L27-L48 |
wilzbach/smarkov | smarkov/markov.py | Markov._compute_transitions | def _compute_transitions(self, corpus, order=1):
""" Computes the transition probabilities of a corpus
Args:
corpus: the given corpus (a corpus_entry needs to be iterable)
order: the maximal Markov chain order
"""
self.transitions = defaultdict(lambda: defaultdict... | python | def _compute_transitions(self, corpus, order=1):
""" Computes the transition probabilities of a corpus
Args:
corpus: the given corpus (a corpus_entry needs to be iterable)
order: the maximal Markov chain order
"""
self.transitions = defaultdict(lambda: defaultdict... | [
"def",
"_compute_transitions",
"(",
"self",
",",
"corpus",
",",
"order",
"=",
"1",
")",
":",
"self",
".",
"transitions",
"=",
"defaultdict",
"(",
"lambda",
":",
"defaultdict",
"(",
"int",
")",
")",
"for",
"corpus_entry",
"in",
"corpus",
":",
"tokens",
"=... | Computes the transition probabilities of a corpus
Args:
corpus: the given corpus (a corpus_entry needs to be iterable)
order: the maximal Markov chain order | [
"Computes",
"the",
"transition",
"probabilities",
"of",
"a",
"corpus",
"Args",
":",
"corpus",
":",
"the",
"given",
"corpus",
"(",
"a",
"corpus_entry",
"needs",
"to",
"be",
"iterable",
")",
"order",
":",
"the",
"maximal",
"Markov",
"chain",
"order"
] | train | https://github.com/wilzbach/smarkov/blob/c98c08cc432e18c5c87fb9a6e013b1b8eaa54d37/smarkov/markov.py#L56-L76 |
wilzbach/smarkov | smarkov/markov.py | Markov._compute_relative_probs | def _compute_relative_probs(self, prob_dict):
""" computes the relative probabilities for every state """
for transition_counts in prob_dict.values():
summed_occurences = sum(transition_counts.values())
if summed_occurences > 0:
for token in transition_counts.keys... | python | def _compute_relative_probs(self, prob_dict):
""" computes the relative probabilities for every state """
for transition_counts in prob_dict.values():
summed_occurences = sum(transition_counts.values())
if summed_occurences > 0:
for token in transition_counts.keys... | [
"def",
"_compute_relative_probs",
"(",
"self",
",",
"prob_dict",
")",
":",
"for",
"transition_counts",
"in",
"prob_dict",
".",
"values",
"(",
")",
":",
"summed_occurences",
"=",
"sum",
"(",
"transition_counts",
".",
"values",
"(",
")",
")",
"if",
"summed_occur... | computes the relative probabilities for every state | [
"computes",
"the",
"relative",
"probabilities",
"for",
"every",
"state"
] | train | https://github.com/wilzbach/smarkov/blob/c98c08cc432e18c5c87fb9a6e013b1b8eaa54d37/smarkov/markov.py#L78-L85 |
wilzbach/smarkov | smarkov/markov.py | Markov._text_generator | def _text_generator(self, next_token=None, emit=lambda x, _, __: x, max_length=None):
""" loops from the start state to the end state and records the emissions
Tokens are joint to sentences by looking ahead for the next token type
emit: by default the markovian emit (see HMM for different emiss... | python | def _text_generator(self, next_token=None, emit=lambda x, _, __: x, max_length=None):
""" loops from the start state to the end state and records the emissions
Tokens are joint to sentences by looking ahead for the next token type
emit: by default the markovian emit (see HMM for different emiss... | [
"def",
"_text_generator",
"(",
"self",
",",
"next_token",
"=",
"None",
",",
"emit",
"=",
"lambda",
"x",
",",
"_",
",",
"__",
":",
"x",
",",
"max_length",
"=",
"None",
")",
":",
"assert",
"next_token",
"is",
"not",
"None",
"last_tokens",
"=",
"utils",
... | loops from the start state to the end state and records the emissions
Tokens are joint to sentences by looking ahead for the next token type
emit: by default the markovian emit (see HMM for different emission forms)
max_length: maximum number of emissions | [
"loops",
"from",
"the",
"start",
"state",
"to",
"the",
"end",
"state",
"and",
"records",
"the",
"emissions",
"Tokens",
"are",
"joint",
"to",
"sentences",
"by",
"looking",
"ahead",
"for",
"the",
"next",
"token",
"type"
] | train | https://github.com/wilzbach/smarkov/blob/c98c08cc432e18c5c87fb9a6e013b1b8eaa54d37/smarkov/markov.py#L87-L115 |
wilzbach/smarkov | smarkov/markov.py | Markov.generate_text | def generate_text(self, max_length=None):
""" Generates sentences from a given corpus
max_length: maximum number of emissions
Returns:
Properly formatted string of generated sentences
"""
return self._text_generator(next_token=self._generate_next_token, max_length=max... | python | def generate_text(self, max_length=None):
""" Generates sentences from a given corpus
max_length: maximum number of emissions
Returns:
Properly formatted string of generated sentences
"""
return self._text_generator(next_token=self._generate_next_token, max_length=max... | [
"def",
"generate_text",
"(",
"self",
",",
"max_length",
"=",
"None",
")",
":",
"return",
"self",
".",
"_text_generator",
"(",
"next_token",
"=",
"self",
".",
"_generate_next_token",
",",
"max_length",
"=",
"max_length",
")"
] | Generates sentences from a given corpus
max_length: maximum number of emissions
Returns:
Properly formatted string of generated sentences | [
"Generates",
"sentences",
"from",
"a",
"given",
"corpus",
"max_length",
":",
"maximum",
"number",
"of",
"emissions",
"Returns",
":",
"Properly",
"formatted",
"string",
"of",
"generated",
"sentences"
] | train | https://github.com/wilzbach/smarkov/blob/c98c08cc432e18c5c87fb9a6e013b1b8eaa54d37/smarkov/markov.py#L117-L123 |
wilzbach/smarkov | smarkov/markov.py | Markov._generate_next_token_helper | def _generate_next_token_helper(self, past_states, transitions):
""" generates next token based previous states """
key = tuple(past_states)
assert key in transitions, "%s" % str(key)
return utils.weighted_choice(transitions[key].items()) | python | def _generate_next_token_helper(self, past_states, transitions):
""" generates next token based previous states """
key = tuple(past_states)
assert key in transitions, "%s" % str(key)
return utils.weighted_choice(transitions[key].items()) | [
"def",
"_generate_next_token_helper",
"(",
"self",
",",
"past_states",
",",
"transitions",
")",
":",
"key",
"=",
"tuple",
"(",
"past_states",
")",
"assert",
"key",
"in",
"transitions",
",",
"\"%s\"",
"%",
"str",
"(",
"key",
")",
"return",
"utils",
".",
"we... | generates next token based previous states | [
"generates",
"next",
"token",
"based",
"previous",
"states"
] | train | https://github.com/wilzbach/smarkov/blob/c98c08cc432e18c5c87fb9a6e013b1b8eaa54d37/smarkov/markov.py#L125-L129 |
goshuirc/irc | girc/ircreactor/events.py | EventManager.dispatch | def dispatch(self, event, ev_msg):
"""Dispatch an event.
event: name of the event (str)
ev_msg: non-optional arguments dictionary.
Side effects:
If an EventObject is not already registered with the EventManager,
a new EventObject will be cre... | python | def dispatch(self, event, ev_msg):
"""Dispatch an event.
event: name of the event (str)
ev_msg: non-optional arguments dictionary.
Side effects:
If an EventObject is not already registered with the EventManager,
a new EventObject will be cre... | [
"def",
"dispatch",
"(",
"self",
",",
"event",
",",
"ev_msg",
")",
":",
"logger",
".",
"debug",
"(",
"'dispatching: '",
"+",
"event",
"+",
"': '",
"+",
"repr",
"(",
"ev_msg",
")",
")",
"eo",
"=",
"self",
".",
"events",
".",
"get",
"(",
"event",
",",... | Dispatch an event.
event: name of the event (str)
ev_msg: non-optional arguments dictionary.
Side effects:
If an EventObject is not already registered with the EventManager,
a new EventObject will be created and registered. | [
"Dispatch",
"an",
"event",
".",
"event",
":",
"name",
"of",
"the",
"event",
"(",
"str",
")",
"ev_msg",
":",
"non",
"-",
"optional",
"arguments",
"dictionary",
".",
"Side",
"effects",
":",
"If",
"an",
"EventObject",
"is",
"not",
"already",
"registered",
"... | train | https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/ircreactor/events.py#L68-L78 |
goshuirc/irc | girc/ircreactor/events.py | EventManager.register | def register(self, event, callable, priority=10):
"""Register interest in an event.
event: name of the event (str)
callable: the callable to be used as a callback function
Returns an EventReceiver object. To unregister interest, simply
delete the object."""
... | python | def register(self, event, callable, priority=10):
"""Register interest in an event.
event: name of the event (str)
callable: the callable to be used as a callback function
Returns an EventReceiver object. To unregister interest, simply
delete the object."""
... | [
"def",
"register",
"(",
"self",
",",
"event",
",",
"callable",
",",
"priority",
"=",
"10",
")",
":",
"logger",
".",
"debug",
"(",
"'registered: '",
"+",
"event",
"+",
"': '",
"+",
"repr",
"(",
"callable",
")",
"+",
"' ['",
"+",
"repr",
"(",
"self",
... | Register interest in an event.
event: name of the event (str)
callable: the callable to be used as a callback function
Returns an EventReceiver object. To unregister interest, simply
delete the object. | [
"Register",
"interest",
"in",
"an",
"event",
".",
"event",
":",
"name",
"of",
"the",
"event",
"(",
"str",
")",
"callable",
":",
"the",
"callable",
"to",
"be",
"used",
"as",
"a",
"callback",
"function",
"Returns",
"an",
"EventReceiver",
"object",
".",
"To... | train | https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/ircreactor/events.py#L80-L87 |
fitnr/twitter_bot_utils | twitter_bot_utils/helpers.py | has_entities | def has_entities(status):
"""
Returns true if a Status object has entities.
Args:
status: either a tweepy.Status object or a dict returned from Twitter API
"""
try:
if sum(len(v) for v in status.entities.values()) > 0:
return True
except AttributeError:
if s... | python | def has_entities(status):
"""
Returns true if a Status object has entities.
Args:
status: either a tweepy.Status object or a dict returned from Twitter API
"""
try:
if sum(len(v) for v in status.entities.values()) > 0:
return True
except AttributeError:
if s... | [
"def",
"has_entities",
"(",
"status",
")",
":",
"try",
":",
"if",
"sum",
"(",
"len",
"(",
"v",
")",
"for",
"v",
"in",
"status",
".",
"entities",
".",
"values",
"(",
")",
")",
">",
"0",
":",
"return",
"True",
"except",
"AttributeError",
":",
"if",
... | Returns true if a Status object has entities.
Args:
status: either a tweepy.Status object or a dict returned from Twitter API | [
"Returns",
"true",
"if",
"a",
"Status",
"object",
"has",
"entities",
"."
] | train | https://github.com/fitnr/twitter_bot_utils/blob/21f35afa5048cd3efa54db8cb87d405f69a78a62/twitter_bot_utils/helpers.py#L54-L69 |
fitnr/twitter_bot_utils | twitter_bot_utils/helpers.py | remove_entities | def remove_entities(status, entitylist):
'''Remove entities for a list of items.'''
try:
entities = status.entities
text = status.text
except AttributeError:
entities = status.get('entities', dict())
text = status['text']
indices = [ent['indices'] for etype, entval in li... | python | def remove_entities(status, entitylist):
'''Remove entities for a list of items.'''
try:
entities = status.entities
text = status.text
except AttributeError:
entities = status.get('entities', dict())
text = status['text']
indices = [ent['indices'] for etype, entval in li... | [
"def",
"remove_entities",
"(",
"status",
",",
"entitylist",
")",
":",
"try",
":",
"entities",
"=",
"status",
".",
"entities",
"text",
"=",
"status",
".",
"text",
"except",
"AttributeError",
":",
"entities",
"=",
"status",
".",
"get",
"(",
"'entities'",
","... | Remove entities for a list of items. | [
"Remove",
"entities",
"for",
"a",
"list",
"of",
"items",
"."
] | train | https://github.com/fitnr/twitter_bot_utils/blob/21f35afa5048cd3efa54db8cb87d405f69a78a62/twitter_bot_utils/helpers.py#L98-L113 |
fitnr/twitter_bot_utils | twitter_bot_utils/helpers.py | replace_urls | def replace_urls(status):
'''
Replace shorturls in a status with expanded urls.
Args:
status (tweepy.status): A tweepy status object
Returns:
str
'''
text = status.text
if not has_url(status):
return text
urls = [(e['indices'], e['expanded_url']) for e in stat... | python | def replace_urls(status):
'''
Replace shorturls in a status with expanded urls.
Args:
status (tweepy.status): A tweepy status object
Returns:
str
'''
text = status.text
if not has_url(status):
return text
urls = [(e['indices'], e['expanded_url']) for e in stat... | [
"def",
"replace_urls",
"(",
"status",
")",
":",
"text",
"=",
"status",
".",
"text",
"if",
"not",
"has_url",
"(",
"status",
")",
":",
"return",
"text",
"urls",
"=",
"[",
"(",
"e",
"[",
"'indices'",
"]",
",",
"e",
"[",
"'expanded_url'",
"]",
")",
"fo... | Replace shorturls in a status with expanded urls.
Args:
status (tweepy.status): A tweepy status object
Returns:
str | [
"Replace",
"shorturls",
"in",
"a",
"status",
"with",
"expanded",
"urls",
"."
] | train | https://github.com/fitnr/twitter_bot_utils/blob/21f35afa5048cd3efa54db8cb87d405f69a78a62/twitter_bot_utils/helpers.py#L116-L137 |
fitnr/twitter_bot_utils | twitter_bot_utils/helpers.py | shorten | def shorten(string, length=140, ellipsis=None):
'''
Shorten a string to 140 characters without breaking words.
Optionally add an ellipsis character: '…' if ellipsis=True, or a given string
e.g. ellipsis=' (cut)'
'''
string = string.strip()
if len(string) > length:
if ellipsis is Tru... | python | def shorten(string, length=140, ellipsis=None):
'''
Shorten a string to 140 characters without breaking words.
Optionally add an ellipsis character: '…' if ellipsis=True, or a given string
e.g. ellipsis=' (cut)'
'''
string = string.strip()
if len(string) > length:
if ellipsis is Tru... | [
"def",
"shorten",
"(",
"string",
",",
"length",
"=",
"140",
",",
"ellipsis",
"=",
"None",
")",
":",
"string",
"=",
"string",
".",
"strip",
"(",
")",
"if",
"len",
"(",
"string",
")",
">",
"length",
":",
"if",
"ellipsis",
"is",
"True",
":",
"ellipsis... | Shorten a string to 140 characters without breaking words.
Optionally add an ellipsis character: '…' if ellipsis=True, or a given string
e.g. ellipsis=' (cut)' | [
"Shorten",
"a",
"string",
"to",
"140",
"characters",
"without",
"breaking",
"words",
".",
"Optionally",
"add",
"an",
"ellipsis",
"character",
":",
"…",
"if",
"ellipsis",
"=",
"True",
"or",
"a",
"given",
"string",
"e",
".",
"g",
".",
"ellipsis",
"=",
"(",... | train | https://github.com/fitnr/twitter_bot_utils/blob/21f35afa5048cd3efa54db8cb87d405f69a78a62/twitter_bot_utils/helpers.py#L140-L159 |
fitnr/twitter_bot_utils | twitter_bot_utils/helpers.py | queryize | def queryize(terms, exclude_screen_name=None):
'''
Create query from list of terms, using OR
but intelligently excluding terms beginning with '-' (Twitter's NOT operator).
Optionally add -from:exclude_screen_name.
>>> helpers.queryize(['apple', 'orange', '-peach'])
u'apple OR orange -peach'
... | python | def queryize(terms, exclude_screen_name=None):
'''
Create query from list of terms, using OR
but intelligently excluding terms beginning with '-' (Twitter's NOT operator).
Optionally add -from:exclude_screen_name.
>>> helpers.queryize(['apple', 'orange', '-peach'])
u'apple OR orange -peach'
... | [
"def",
"queryize",
"(",
"terms",
",",
"exclude_screen_name",
"=",
"None",
")",
":",
"ors",
"=",
"' OR '",
".",
"join",
"(",
"'\"{}\"'",
".",
"format",
"(",
"x",
")",
"for",
"x",
"in",
"terms",
"if",
"not",
"x",
".",
"startswith",
"(",
"'-'",
")",
"... | Create query from list of terms, using OR
but intelligently excluding terms beginning with '-' (Twitter's NOT operator).
Optionally add -from:exclude_screen_name.
>>> helpers.queryize(['apple', 'orange', '-peach'])
u'apple OR orange -peach'
Args:
terms (list): Search terms.
exclude... | [
"Create",
"query",
"from",
"list",
"of",
"terms",
"using",
"OR",
"but",
"intelligently",
"excluding",
"terms",
"beginning",
"with",
"-",
"(",
"Twitter",
"s",
"NOT",
"operator",
")",
".",
"Optionally",
"add",
"-",
"from",
":",
"exclude_screen_name",
"."
] | train | https://github.com/fitnr/twitter_bot_utils/blob/21f35afa5048cd3efa54db8cb87d405f69a78a62/twitter_bot_utils/helpers.py#L162-L181 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.