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 |
|---|---|---|---|---|---|---|---|---|---|---|
SmartTeleMax/iktomi | iktomi/utils/system.py | doublefork | def doublefork(pidfile, logfile, cwd, umask): # pragma: nocover
'''Daemonize current process.
After first fork we return to the shell and removing our self from
controling terminal via `setsid`.
After second fork we are not session leader any more and cant get
controlling terminal when opening files.'''
try:
if os.fork():
os._exit(os.EX_OK)
except OSError as e:
sys.exit('fork #1 failed: ({}) {}'.format(e.errno, e.strerror))
os.setsid()
os.chdir(cwd)
os.umask(umask)
try:
if os.fork():
os._exit(os.EX_OK)
except OSError as e:
sys.exit('fork #2 failed: ({}) {}'.format(e.errno, e.strerror))
if logfile is not None:
si = open('/dev/null')
if six.PY2:
so = open(logfile, 'a+', 0)
else:
so = io.open(logfile, 'ab+', 0)
so = io.TextIOWrapper(so, write_through=True, encoding="utf-8")
os.dup2(si.fileno(), 0)
os.dup2(so.fileno(), 1)
os.dup2(so.fileno(), 2)
sys.stdin = si
sys.stdout = sys.stderr = so
with open(pidfile, 'w') as f:
f.write(str(os.getpid())) | python | def doublefork(pidfile, logfile, cwd, umask): # pragma: nocover
'''Daemonize current process.
After first fork we return to the shell and removing our self from
controling terminal via `setsid`.
After second fork we are not session leader any more and cant get
controlling terminal when opening files.'''
try:
if os.fork():
os._exit(os.EX_OK)
except OSError as e:
sys.exit('fork #1 failed: ({}) {}'.format(e.errno, e.strerror))
os.setsid()
os.chdir(cwd)
os.umask(umask)
try:
if os.fork():
os._exit(os.EX_OK)
except OSError as e:
sys.exit('fork #2 failed: ({}) {}'.format(e.errno, e.strerror))
if logfile is not None:
si = open('/dev/null')
if six.PY2:
so = open(logfile, 'a+', 0)
else:
so = io.open(logfile, 'ab+', 0)
so = io.TextIOWrapper(so, write_through=True, encoding="utf-8")
os.dup2(si.fileno(), 0)
os.dup2(so.fileno(), 1)
os.dup2(so.fileno(), 2)
sys.stdin = si
sys.stdout = sys.stderr = so
with open(pidfile, 'w') as f:
f.write(str(os.getpid())) | [
"def",
"doublefork",
"(",
"pidfile",
",",
"logfile",
",",
"cwd",
",",
"umask",
")",
":",
"# pragma: nocover",
"try",
":",
"if",
"os",
".",
"fork",
"(",
")",
":",
"os",
".",
"_exit",
"(",
"os",
".",
"EX_OK",
")",
"except",
"OSError",
"as",
"e",
":",... | Daemonize current process.
After first fork we return to the shell and removing our self from
controling terminal via `setsid`.
After second fork we are not session leader any more and cant get
controlling terminal when opening files. | [
"Daemonize",
"current",
"process",
".",
"After",
"first",
"fork",
"we",
"return",
"to",
"the",
"shell",
"and",
"removing",
"our",
"self",
"from",
"controling",
"terminal",
"via",
"setsid",
".",
"After",
"second",
"fork",
"we",
"are",
"not",
"session",
"leade... | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/utils/system.py#L49-L82 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/repositoryconfigurations_api.py | RepositoryconfigurationsApi.match | def match(self, search, **kwargs):
"""
Searches for Repository Configurations based on internal or external url, ignoring the protocol and \".git\" suffix. Only exact matches are returned.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.match(search, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str search: Url to search for (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:return: RepositoryConfigurationPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.match_with_http_info(search, **kwargs)
else:
(data) = self.match_with_http_info(search, **kwargs)
return data | python | def match(self, search, **kwargs):
"""
Searches for Repository Configurations based on internal or external url, ignoring the protocol and \".git\" suffix. Only exact matches are returned.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.match(search, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str search: Url to search for (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:return: RepositoryConfigurationPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.match_with_http_info(search, **kwargs)
else:
(data) = self.match_with_http_info(search, **kwargs)
return data | [
"def",
"match",
"(",
"self",
",",
"search",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"match_with_http_info",
"(",
"sear... | Searches for Repository Configurations based on internal or external url, ignoring the protocol and \".git\" suffix. Only exact matches are returned.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.match(search, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str search: Url to search for (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:return: RepositoryConfigurationPage
If the method is called asynchronously,
returns the request thread. | [
"Searches",
"for",
"Repository",
"Configurations",
"based",
"on",
"internal",
"or",
"external",
"url",
"ignoring",
"the",
"protocol",
"and",
"\\",
".",
"git",
"\\",
"suffix",
".",
"Only",
"exact",
"matches",
"are",
"returned",
".",
"This",
"method",
"makes",
... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/repositoryconfigurations_api.py#L366-L393 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/repositoryconfigurations_api.py | RepositoryconfigurationsApi.search | def search(self, search, **kwargs):
"""
Search for Repository Configurations based on internal or external url, ignoring the protocol and \".git\" suffix. The matching is done using LIKE.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.search(search, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str search: Url part to search for (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:return: RepositoryConfigurationPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.search_with_http_info(search, **kwargs)
else:
(data) = self.search_with_http_info(search, **kwargs)
return data | python | def search(self, search, **kwargs):
"""
Search for Repository Configurations based on internal or external url, ignoring the protocol and \".git\" suffix. The matching is done using LIKE.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.search(search, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str search: Url part to search for (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:return: RepositoryConfigurationPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.search_with_http_info(search, **kwargs)
else:
(data) = self.search_with_http_info(search, **kwargs)
return data | [
"def",
"search",
"(",
"self",
",",
"search",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"search_with_http_info",
"(",
"se... | Search for Repository Configurations based on internal or external url, ignoring the protocol and \".git\" suffix. The matching is done using LIKE.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.search(search, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str search: Url part to search for (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:return: RepositoryConfigurationPage
If the method is called asynchronously,
returns the request thread. | [
"Search",
"for",
"Repository",
"Configurations",
"based",
"on",
"internal",
"or",
"external",
"url",
"ignoring",
"the",
"protocol",
"and",
"\\",
".",
"git",
"\\",
"suffix",
".",
"The",
"matching",
"is",
"done",
"using",
"LIKE",
".",
"This",
"method",
"makes"... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/repositoryconfigurations_api.py#L484-L511 |
project-ncl/pnc-cli | pnc_cli/makemead.py | make_mead | def make_mead(config=None, run_build=False, environment=1, suffix="", product_name=None, product_version=None,
look_up_only="",clean_group=False):
"""
Create Build group based on Make-Mead configuration file
:param config: Make Mead config name
:return:
"""
ret=make_mead_impl(config, run_build, environment, suffix, product_name, product_version, look_up_only, clean_group)
if type(ret) == int and ret != 0:
sys.exit(ret)
return ret | python | def make_mead(config=None, run_build=False, environment=1, suffix="", product_name=None, product_version=None,
look_up_only="",clean_group=False):
"""
Create Build group based on Make-Mead configuration file
:param config: Make Mead config name
:return:
"""
ret=make_mead_impl(config, run_build, environment, suffix, product_name, product_version, look_up_only, clean_group)
if type(ret) == int and ret != 0:
sys.exit(ret)
return ret | [
"def",
"make_mead",
"(",
"config",
"=",
"None",
",",
"run_build",
"=",
"False",
",",
"environment",
"=",
"1",
",",
"suffix",
"=",
"\"\"",
",",
"product_name",
"=",
"None",
",",
"product_version",
"=",
"None",
",",
"look_up_only",
"=",
"\"\"",
",",
"clean... | Create Build group based on Make-Mead configuration file
:param config: Make Mead config name
:return: | [
"Create",
"Build",
"group",
"based",
"on",
"Make",
"-",
"Mead",
"configuration",
"file",
":",
"param",
"config",
":",
"Make",
"Mead",
"config",
"name",
":",
"return",
":"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/makemead.py#L35-L45 |
CivicSpleen/ambry | ambry/bundle/partitions.py | Partitions.partition | def partition(self, id_):
"""Get a partition by the id number.
Arguments:
id_ -- a partition id value
Returns:
A partitions.Partition object
Throws:
a Sqlalchemy exception if the partition either does not exist or
is not unique
Because this method works on the bundle, the id_ ( without version information )
is equivalent to the vid ( with version information )
"""
from ..orm import Partition as OrmPartition
from sqlalchemy import or_
from ..identity import PartialPartitionName
if isinstance(id_, PartitionIdentity):
id_ = id_.id_
elif isinstance(id_, PartialPartitionName):
id_ = id_.promote(self.bundle.identity.name)
session = self.bundle.dataset._database.session
q = session\
.query(OrmPartition)\
.filter(OrmPartition.d_vid == self.bundle.dataset.vid)\
.filter(or_(OrmPartition.id == str(id_).encode('ascii'),
OrmPartition.vid == str(id_).encode('ascii')))
try:
orm_partition = q.one()
return self.bundle.wrap_partition(orm_partition)
except NoResultFound:
orm_partition = None
if not orm_partition:
q = session\
.query(OrmPartition)\
.filter(OrmPartition.d_vid == self.bundle.dataset.vid)\
.filter(OrmPartition.name == str(id_).encode('ascii'))
try:
orm_partition = q.one()
return self.bundle.wrap_partition(orm_partition)
except NoResultFound:
orm_partition = None
return orm_partition | python | def partition(self, id_):
"""Get a partition by the id number.
Arguments:
id_ -- a partition id value
Returns:
A partitions.Partition object
Throws:
a Sqlalchemy exception if the partition either does not exist or
is not unique
Because this method works on the bundle, the id_ ( without version information )
is equivalent to the vid ( with version information )
"""
from ..orm import Partition as OrmPartition
from sqlalchemy import or_
from ..identity import PartialPartitionName
if isinstance(id_, PartitionIdentity):
id_ = id_.id_
elif isinstance(id_, PartialPartitionName):
id_ = id_.promote(self.bundle.identity.name)
session = self.bundle.dataset._database.session
q = session\
.query(OrmPartition)\
.filter(OrmPartition.d_vid == self.bundle.dataset.vid)\
.filter(or_(OrmPartition.id == str(id_).encode('ascii'),
OrmPartition.vid == str(id_).encode('ascii')))
try:
orm_partition = q.one()
return self.bundle.wrap_partition(orm_partition)
except NoResultFound:
orm_partition = None
if not orm_partition:
q = session\
.query(OrmPartition)\
.filter(OrmPartition.d_vid == self.bundle.dataset.vid)\
.filter(OrmPartition.name == str(id_).encode('ascii'))
try:
orm_partition = q.one()
return self.bundle.wrap_partition(orm_partition)
except NoResultFound:
orm_partition = None
return orm_partition | [
"def",
"partition",
"(",
"self",
",",
"id_",
")",
":",
"from",
".",
".",
"orm",
"import",
"Partition",
"as",
"OrmPartition",
"from",
"sqlalchemy",
"import",
"or_",
"from",
".",
".",
"identity",
"import",
"PartialPartitionName",
"if",
"isinstance",
"(",
"id_"... | Get a partition by the id number.
Arguments:
id_ -- a partition id value
Returns:
A partitions.Partition object
Throws:
a Sqlalchemy exception if the partition either does not exist or
is not unique
Because this method works on the bundle, the id_ ( without version information )
is equivalent to the vid ( with version information ) | [
"Get",
"a",
"partition",
"by",
"the",
"id",
"number",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/partitions.py#L45-L96 |
CivicSpleen/ambry | ambry/bundle/partitions.py | Partitions._find_orm | def _find_orm(self, pnq):
"""Return a Partition object from the database based on a PartitionId.
An ORM object is returned, so changes can be persisted.
"""
# import sqlalchemy.orm.exc
from ambry.orm import Partition as OrmPartition # , Table
from sqlalchemy.orm import joinedload # , joinedload_all
assert isinstance(pnq, PartitionNameQuery), "Expected PartitionNameQuery, got {}".format(type(pnq))
pnq = pnq.with_none()
q = self.bundle.dataset._database.session.query(OrmPartition)
if pnq.fqname is not NameQuery.ANY:
q = q.filter(OrmPartition.fqname == pnq.fqname)
elif pnq.vname is not NameQuery.ANY:
q = q.filter(OrmPartition.vname == pnq.vname)
elif pnq.name is not NameQuery.ANY:
q = q.filter(OrmPartition.name == str(pnq.name))
else:
if pnq.time is not NameQuery.ANY:
q = q.filter(OrmPartition.time == pnq.time)
if pnq.space is not NameQuery.ANY:
q = q.filter(OrmPartition.space == pnq.space)
if pnq.grain is not NameQuery.ANY:
q = q.filter(OrmPartition.grain == pnq.grain)
if pnq.format is not NameQuery.ANY:
q = q.filter(OrmPartition.format == pnq.format)
if pnq.segment is not NameQuery.ANY:
q = q.filter(OrmPartition.segment == pnq.segment)
if pnq.table is not NameQuery.ANY:
if pnq.table is None:
q = q.filter(OrmPartition.t_id is None)
else:
tr = self.bundle.table(pnq.table)
if not tr:
raise ValueError("Didn't find table named {} in {} bundle path = {}".format(
pnq.table, pnq.vname, self.bundle.database.path))
q = q.filter(OrmPartition.t_vid == tr.vid)
ds = self.bundle.dataset
q = q.filter(OrmPartition.d_vid == ds.vid)
q = q.order_by(
OrmPartition.vid.asc()).order_by(
OrmPartition.segment.asc())
q = q.options(joinedload(OrmPartition.table))
return q | python | def _find_orm(self, pnq):
"""Return a Partition object from the database based on a PartitionId.
An ORM object is returned, so changes can be persisted.
"""
# import sqlalchemy.orm.exc
from ambry.orm import Partition as OrmPartition # , Table
from sqlalchemy.orm import joinedload # , joinedload_all
assert isinstance(pnq, PartitionNameQuery), "Expected PartitionNameQuery, got {}".format(type(pnq))
pnq = pnq.with_none()
q = self.bundle.dataset._database.session.query(OrmPartition)
if pnq.fqname is not NameQuery.ANY:
q = q.filter(OrmPartition.fqname == pnq.fqname)
elif pnq.vname is not NameQuery.ANY:
q = q.filter(OrmPartition.vname == pnq.vname)
elif pnq.name is not NameQuery.ANY:
q = q.filter(OrmPartition.name == str(pnq.name))
else:
if pnq.time is not NameQuery.ANY:
q = q.filter(OrmPartition.time == pnq.time)
if pnq.space is not NameQuery.ANY:
q = q.filter(OrmPartition.space == pnq.space)
if pnq.grain is not NameQuery.ANY:
q = q.filter(OrmPartition.grain == pnq.grain)
if pnq.format is not NameQuery.ANY:
q = q.filter(OrmPartition.format == pnq.format)
if pnq.segment is not NameQuery.ANY:
q = q.filter(OrmPartition.segment == pnq.segment)
if pnq.table is not NameQuery.ANY:
if pnq.table is None:
q = q.filter(OrmPartition.t_id is None)
else:
tr = self.bundle.table(pnq.table)
if not tr:
raise ValueError("Didn't find table named {} in {} bundle path = {}".format(
pnq.table, pnq.vname, self.bundle.database.path))
q = q.filter(OrmPartition.t_vid == tr.vid)
ds = self.bundle.dataset
q = q.filter(OrmPartition.d_vid == ds.vid)
q = q.order_by(
OrmPartition.vid.asc()).order_by(
OrmPartition.segment.asc())
q = q.options(joinedload(OrmPartition.table))
return q | [
"def",
"_find_orm",
"(",
"self",
",",
"pnq",
")",
":",
"# import sqlalchemy.orm.exc",
"from",
"ambry",
".",
"orm",
"import",
"Partition",
"as",
"OrmPartition",
"# , Table",
"from",
"sqlalchemy",
".",
"orm",
"import",
"joinedload",
"# , joinedload_all",
"assert",
"... | Return a Partition object from the database based on a PartitionId.
An ORM object is returned, so changes can be persisted. | [
"Return",
"a",
"Partition",
"object",
"from",
"the",
"database",
"based",
"on",
"a",
"PartitionId",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/partitions.py#L98-L159 |
CivicSpleen/ambry | ambry/bundle/partitions.py | Partitions.new_db_from_pandas | def new_db_from_pandas(self, frame, table=None, data=None, load=True, **kwargs):
"""Create a new db partition from a pandas data frame.
If the table does not exist, it will be created
"""
from ..orm import Column
# from dbexceptions import ConfigurationError
# Create the table from the information in the data frame.
with self.bundle.session:
sch = self.bundle.schema
t = sch.new_table(table)
if frame.index.name:
id_name = frame.index.name
else:
id_name = 'id'
sch.add_column(t, id_name,
datatype=Column.convert_numpy_type(frame.index.dtype),
is_primary_key=True)
for name, type_ in zip([row for row in frame.columns],
[row for row in frame.convert_objects(convert_numeric=True,
convert_dates=True).dtypes]):
sch.add_column(t, name, datatype=Column.convert_numpy_type(type_))
sch.write_schema()
p = self.new_partition(table=table, data=data, **kwargs)
if load:
pk_name = frame.index.name
with p.inserter(table) as ins:
for i, row in frame.iterrows():
d = dict(row)
d[pk_name] = i
ins.insert(d)
return p | python | def new_db_from_pandas(self, frame, table=None, data=None, load=True, **kwargs):
"""Create a new db partition from a pandas data frame.
If the table does not exist, it will be created
"""
from ..orm import Column
# from dbexceptions import ConfigurationError
# Create the table from the information in the data frame.
with self.bundle.session:
sch = self.bundle.schema
t = sch.new_table(table)
if frame.index.name:
id_name = frame.index.name
else:
id_name = 'id'
sch.add_column(t, id_name,
datatype=Column.convert_numpy_type(frame.index.dtype),
is_primary_key=True)
for name, type_ in zip([row for row in frame.columns],
[row for row in frame.convert_objects(convert_numeric=True,
convert_dates=True).dtypes]):
sch.add_column(t, name, datatype=Column.convert_numpy_type(type_))
sch.write_schema()
p = self.new_partition(table=table, data=data, **kwargs)
if load:
pk_name = frame.index.name
with p.inserter(table) as ins:
for i, row in frame.iterrows():
d = dict(row)
d[pk_name] = i
ins.insert(d)
return p | [
"def",
"new_db_from_pandas",
"(",
"self",
",",
"frame",
",",
"table",
"=",
"None",
",",
"data",
"=",
"None",
",",
"load",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
".",
"orm",
"import",
"Column",
"# from dbexceptions import Configuration... | Create a new db partition from a pandas data frame.
If the table does not exist, it will be created | [
"Create",
"a",
"new",
"db",
"partition",
"from",
"a",
"pandas",
"data",
"frame",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/partitions.py#L212-L252 |
project-ncl/pnc-cli | pnc_cli/projects.py | update_project | def update_project(id, **kwargs):
"""
Update an existing Project with new information
"""
content = update_project_raw(id, **kwargs)
if content:
return utils.format_json(content) | python | def update_project(id, **kwargs):
"""
Update an existing Project with new information
"""
content = update_project_raw(id, **kwargs)
if content:
return utils.format_json(content) | [
"def",
"update_project",
"(",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"content",
"=",
"update_project_raw",
"(",
"id",
",",
"*",
"*",
"kwargs",
")",
"if",
"content",
":",
"return",
"utils",
".",
"format_json",
"(",
"content",
")"
] | Update an existing Project with new information | [
"Update",
"an",
"existing",
"Project",
"with",
"new",
"information"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/projects.py#L44-L50 |
project-ncl/pnc-cli | pnc_cli/projects.py | get_project | def get_project(id=None, name=None):
"""
Get a specific Project by ID or name
"""
content = get_project_raw(id, name)
if content:
return utils.format_json(content) | python | def get_project(id=None, name=None):
"""
Get a specific Project by ID or name
"""
content = get_project_raw(id, name)
if content:
return utils.format_json(content) | [
"def",
"get_project",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"content",
"=",
"get_project_raw",
"(",
"id",
",",
"name",
")",
"if",
"content",
":",
"return",
"utils",
".",
"format_json",
"(",
"content",
")"
] | Get a specific Project by ID or name | [
"Get",
"a",
"specific",
"Project",
"by",
"ID",
"or",
"name"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/projects.py#L69-L75 |
project-ncl/pnc-cli | pnc_cli/projects.py | delete_project | def delete_project(id=None, name=None):
"""
Delete a Project by ID or name.
"""
content = delete_project_raw(id, name)
if content:
return utils.format_json(content) | python | def delete_project(id=None, name=None):
"""
Delete a Project by ID or name.
"""
content = delete_project_raw(id, name)
if content:
return utils.format_json(content) | [
"def",
"delete_project",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"content",
"=",
"delete_project_raw",
"(",
"id",
",",
"name",
")",
"if",
"content",
":",
"return",
"utils",
".",
"format_json",
"(",
"content",
")"
] | Delete a Project by ID or name. | [
"Delete",
"a",
"Project",
"by",
"ID",
"or",
"name",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/projects.py#L85-L91 |
project-ncl/pnc-cli | pnc_cli/projects.py | list_projects | def list_projects(page_size=200, page_index=0, sort="", q=""):
"""
List all Projects
"""
content = list_projects_raw(page_size=page_size, page_index=page_index, sort=sort, q=q)
if content:
return utils.format_json_list(content) | python | def list_projects(page_size=200, page_index=0, sort="", q=""):
"""
List all Projects
"""
content = list_projects_raw(page_size=page_size, page_index=page_index, sort=sort, q=q)
if content:
return utils.format_json_list(content) | [
"def",
"list_projects",
"(",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
",",
"q",
"=",
"\"\"",
")",
":",
"content",
"=",
"list_projects_raw",
"(",
"page_size",
"=",
"page_size",
",",
"page_index",
"=",
"page_index",
"... | List all Projects | [
"List",
"all",
"Projects"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/projects.py#L104-L110 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildrecordpush_api.py | BuildrecordpushApi.cancel | def cancel(self, build_record_id, **kwargs):
"""
Build record push results.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.cancel(build_record_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int build_record_id: Build Record id (required)
:param BuildRecordPushResultRest body:
:return: int
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.cancel_with_http_info(build_record_id, **kwargs)
else:
(data) = self.cancel_with_http_info(build_record_id, **kwargs)
return data | python | def cancel(self, build_record_id, **kwargs):
"""
Build record push results.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.cancel(build_record_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int build_record_id: Build Record id (required)
:param BuildRecordPushResultRest body:
:return: int
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.cancel_with_http_info(build_record_id, **kwargs)
else:
(data) = self.cancel_with_http_info(build_record_id, **kwargs)
return data | [
"def",
"cancel",
"(",
"self",
",",
"build_record_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"cancel_with_http_info",
"... | Build record push results.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.cancel(build_record_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int build_record_id: Build Record id (required)
:param BuildRecordPushResultRest body:
:return: int
If the method is called asynchronously,
returns the request thread. | [
"Build",
"record",
"push",
"results",
".",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function",
"to",
"be",
"invoked",
... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildrecordpush_api.py#L42-L67 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildrecordpush_api.py | BuildrecordpushApi.get | def get(self, build_record_id, **kwargs):
"""
Get Build Record Push Result by Id..
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get(build_record_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int build_record_id: Build Record id (required)
:return: BuildRecordPushResultRest
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_with_http_info(build_record_id, **kwargs)
else:
(data) = self.get_with_http_info(build_record_id, **kwargs)
return data | python | def get(self, build_record_id, **kwargs):
"""
Get Build Record Push Result by Id..
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get(build_record_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int build_record_id: Build Record id (required)
:return: BuildRecordPushResultRest
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_with_http_info(build_record_id, **kwargs)
else:
(data) = self.get_with_http_info(build_record_id, **kwargs)
return data | [
"def",
"get",
"(",
"self",
",",
"build_record_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_with_http_info",
"(",
... | Get Build Record Push Result by Id..
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get(build_record_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int build_record_id: Build Record id (required)
:return: BuildRecordPushResultRest
If the method is called asynchronously,
returns the request thread. | [
"Get",
"Build",
"Record",
"Push",
"Result",
"by",
"Id",
"..",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function",
"to"... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildrecordpush_api.py#L152-L176 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildrecordpush_api.py | BuildrecordpushApi.push | def push(self, **kwargs):
"""
Push build record results to Brew.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.push(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param BuildRecordPushRequestRest body:
:return: list[ResultRest]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.push_with_http_info(**kwargs)
else:
(data) = self.push_with_http_info(**kwargs)
return data | python | def push(self, **kwargs):
"""
Push build record results to Brew.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.push(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param BuildRecordPushRequestRest body:
:return: list[ResultRest]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.push_with_http_info(**kwargs)
else:
(data) = self.push_with_http_info(**kwargs)
return data | [
"def",
"push",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"push_with_http_info",
"(",
"*",
"*",
"kwargs",
... | Push build record results to Brew.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.push(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param BuildRecordPushRequestRest body:
:return: list[ResultRest]
If the method is called asynchronously,
returns the request thread. | [
"Push",
"build",
"record",
"results",
"to",
"Brew",
".",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function",
"to",
"be... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildrecordpush_api.py#L258-L282 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildrecordpush_api.py | BuildrecordpushApi.push_0 | def push_0(self, build_record_id, **kwargs):
"""
Build record push results.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.push_0(build_record_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int build_record_id: Build Record id (required)
:param BuildRecordPushResultRest body:
:return: int
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.push_0_with_http_info(build_record_id, **kwargs)
else:
(data) = self.push_0_with_http_info(build_record_id, **kwargs)
return data | python | def push_0(self, build_record_id, **kwargs):
"""
Build record push results.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.push_0(build_record_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int build_record_id: Build Record id (required)
:param BuildRecordPushResultRest body:
:return: int
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.push_0_with_http_info(build_record_id, **kwargs)
else:
(data) = self.push_0_with_http_info(build_record_id, **kwargs)
return data | [
"def",
"push_0",
"(",
"self",
",",
"build_record_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"push_0_with_http_info",
"... | Build record push results.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.push_0(build_record_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int build_record_id: Build Record id (required)
:param BuildRecordPushResultRest body:
:return: int
If the method is called asynchronously,
returns the request thread. | [
"Build",
"record",
"push",
"results",
".",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function",
"to",
"be",
"invoked",
... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildrecordpush_api.py#L361-L386 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildrecordpush_api.py | BuildrecordpushApi.push_record_set | def push_record_set(self, **kwargs):
"""
Push build config set record to Brew.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.push_record_set(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param BuildConfigSetRecordPushRequestRest body:
:return: list[ResultRest]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.push_record_set_with_http_info(**kwargs)
else:
(data) = self.push_record_set_with_http_info(**kwargs)
return data | python | def push_record_set(self, **kwargs):
"""
Push build config set record to Brew.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.push_record_set(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param BuildConfigSetRecordPushRequestRest body:
:return: list[ResultRest]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.push_record_set_with_http_info(**kwargs)
else:
(data) = self.push_record_set_with_http_info(**kwargs)
return data | [
"def",
"push_record_set",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"push_record_set_with_http_info",
"(",
"*",... | Push build config set record to Brew.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.push_record_set(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param BuildConfigSetRecordPushRequestRest body:
:return: list[ResultRest]
If the method is called asynchronously,
returns the request thread. | [
"Push",
"build",
"config",
"set",
"record",
"to",
"Brew",
".",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function",
"to... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildrecordpush_api.py#L471-L495 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildrecordpush_api.py | BuildrecordpushApi.status | def status(self, build_record_id, **kwargs):
"""
Latest push result of BuildRecord.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.status(build_record_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int build_record_id: Build Record id (required)
:return: BuildRecordPushResultRest
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.status_with_http_info(build_record_id, **kwargs)
else:
(data) = self.status_with_http_info(build_record_id, **kwargs)
return data | python | def status(self, build_record_id, **kwargs):
"""
Latest push result of BuildRecord.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.status(build_record_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int build_record_id: Build Record id (required)
:return: BuildRecordPushResultRest
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.status_with_http_info(build_record_id, **kwargs)
else:
(data) = self.status_with_http_info(build_record_id, **kwargs)
return data | [
"def",
"status",
"(",
"self",
",",
"build_record_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"status_with_http_info",
"... | Latest push result of BuildRecord.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.status(build_record_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int build_record_id: Build Record id (required)
:return: BuildRecordPushResultRest
If the method is called asynchronously,
returns the request thread. | [
"Latest",
"push",
"result",
"of",
"BuildRecord",
".",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function",
"to",
"be",
... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildrecordpush_api.py#L574-L598 |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/session.py | BaseSession.set_handler | def set_handler(self, handler):
""" Set transport handler
@param handler: Handler, should derive from the
C{sockjs.cyclone.transports.base.BaseTransportMixin}
"""
if self.handler is not None:
raise Exception('Attempted to overwrite BaseSession handler')
self.handler = handler
self.transport_name = self.handler.name
if self.conn_info is None:
self.conn_info = handler.get_conn_info()
self.stats.sessionOpened(self.transport_name)
return True | python | def set_handler(self, handler):
""" Set transport handler
@param handler: Handler, should derive from the
C{sockjs.cyclone.transports.base.BaseTransportMixin}
"""
if self.handler is not None:
raise Exception('Attempted to overwrite BaseSession handler')
self.handler = handler
self.transport_name = self.handler.name
if self.conn_info is None:
self.conn_info = handler.get_conn_info()
self.stats.sessionOpened(self.transport_name)
return True | [
"def",
"set_handler",
"(",
"self",
",",
"handler",
")",
":",
"if",
"self",
".",
"handler",
"is",
"not",
"None",
":",
"raise",
"Exception",
"(",
"'Attempted to overwrite BaseSession handler'",
")",
"self",
".",
"handler",
"=",
"handler",
"self",
".",
"transport... | Set transport handler
@param handler: Handler, should derive from the
C{sockjs.cyclone.transports.base.BaseTransportMixin} | [
"Set",
"transport",
"handler"
] | train | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/session.py#L48-L64 |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/session.py | BaseSession.verify_state | def verify_state(self):
""" Verify if session was not yet opened. If it is, open it and call
connection's C{connectionMade} """
if self.state == SESSION_STATE.CONNECTING:
self.state = SESSION_STATE.OPEN
self.conn.connectionMade(self.conn_info) | python | def verify_state(self):
""" Verify if session was not yet opened. If it is, open it and call
connection's C{connectionMade} """
if self.state == SESSION_STATE.CONNECTING:
self.state = SESSION_STATE.OPEN
self.conn.connectionMade(self.conn_info) | [
"def",
"verify_state",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
"==",
"SESSION_STATE",
".",
"CONNECTING",
":",
"self",
".",
"state",
"=",
"SESSION_STATE",
".",
"OPEN",
"self",
".",
"conn",
".",
"connectionMade",
"(",
"self",
".",
"conn_info",
"... | Verify if session was not yet opened. If it is, open it and call
connection's C{connectionMade} | [
"Verify",
"if",
"session",
"was",
"not",
"yet",
"opened",
".",
"If",
"it",
"is",
"open",
"it",
"and",
"call",
"connection",
"s",
"C",
"{",
"connectionMade",
"}"
] | train | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/session.py#L66-L72 |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/session.py | BaseSession.close | def close(self, code=3000, message='Go away!'):
""" Close session or endpoint connection.
@param code: Closing code
@param message: Close message
"""
if self.state != SESSION_STATE.CLOSED:
try:
self.conn.connectionLost()
except Exception as e:
log.msg("Failed to call connectionLost(): %r." % e)
finally:
self.state = SESSION_STATE.CLOSED
self.close_reason = (code, message)
# Bump stats
self.stats.sessionClosed(self.transport_name)
# If we have active handler, notify that session was closed
if self.handler is not None:
self.handler.session_closed() | python | def close(self, code=3000, message='Go away!'):
""" Close session or endpoint connection.
@param code: Closing code
@param message: Close message
"""
if self.state != SESSION_STATE.CLOSED:
try:
self.conn.connectionLost()
except Exception as e:
log.msg("Failed to call connectionLost(): %r." % e)
finally:
self.state = SESSION_STATE.CLOSED
self.close_reason = (code, message)
# Bump stats
self.stats.sessionClosed(self.transport_name)
# If we have active handler, notify that session was closed
if self.handler is not None:
self.handler.session_closed() | [
"def",
"close",
"(",
"self",
",",
"code",
"=",
"3000",
",",
"message",
"=",
"'Go away!'",
")",
":",
"if",
"self",
".",
"state",
"!=",
"SESSION_STATE",
".",
"CLOSED",
":",
"try",
":",
"self",
".",
"conn",
".",
"connectionLost",
"(",
")",
"except",
"Ex... | Close session or endpoint connection.
@param code: Closing code
@param message: Close message | [
"Close",
"session",
"or",
"endpoint",
"connection",
"."
] | train | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/session.py#L85-L106 |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/session.py | BaseSession.delayed_close | def delayed_close(self):
""" Delayed close - won't close immediately, but on the next reactor
loop. """
self.state = SESSION_STATE.CLOSING
reactor.callLater(0, self.close) | python | def delayed_close(self):
""" Delayed close - won't close immediately, but on the next reactor
loop. """
self.state = SESSION_STATE.CLOSING
reactor.callLater(0, self.close) | [
"def",
"delayed_close",
"(",
"self",
")",
":",
"self",
".",
"state",
"=",
"SESSION_STATE",
".",
"CLOSING",
"reactor",
".",
"callLater",
"(",
"0",
",",
"self",
".",
"close",
")"
] | Delayed close - won't close immediately, but on the next reactor
loop. | [
"Delayed",
"close",
"-",
"won",
"t",
"close",
"immediately",
"but",
"on",
"the",
"next",
"reactor",
"loop",
"."
] | train | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/session.py#L108-L112 |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/session.py | BaseSession.is_closed | def is_closed(self):
""" Check if session was closed. """
return (self.state == SESSION_STATE.CLOSED
or self.state == SESSION_STATE.CLOSING) | python | def is_closed(self):
""" Check if session was closed. """
return (self.state == SESSION_STATE.CLOSED
or self.state == SESSION_STATE.CLOSING) | [
"def",
"is_closed",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"state",
"==",
"SESSION_STATE",
".",
"CLOSED",
"or",
"self",
".",
"state",
"==",
"SESSION_STATE",
".",
"CLOSING",
")"
] | Check if session was closed. | [
"Check",
"if",
"session",
"was",
"closed",
"."
] | train | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/session.py#L129-L132 |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/session.py | SessionMixin._random_key | def _random_key(self):
""" Return random session key """
hashstr = '%s%s' % (random.random(), self.time_module.time())
return hashlib.md5(hashstr).hexdigest() | python | def _random_key(self):
""" Return random session key """
hashstr = '%s%s' % (random.random(), self.time_module.time())
return hashlib.md5(hashstr).hexdigest() | [
"def",
"_random_key",
"(",
"self",
")",
":",
"hashstr",
"=",
"'%s%s'",
"%",
"(",
"random",
".",
"random",
"(",
")",
",",
"self",
".",
"time_module",
".",
"time",
"(",
")",
")",
"return",
"hashlib",
".",
"md5",
"(",
"hashstr",
")",
".",
"hexdigest",
... | Return random session key | [
"Return",
"random",
"session",
"key"
] | train | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/session.py#L192-L195 |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/session.py | SessionMixin.promote | def promote(self):
""" Mark object as alive, so it won't be collected during next
run of the garbage collector.
"""
if self.expiry is not None:
self.promoted = self.time_module.time() + self.expiry | python | def promote(self):
""" Mark object as alive, so it won't be collected during next
run of the garbage collector.
"""
if self.expiry is not None:
self.promoted = self.time_module.time() + self.expiry | [
"def",
"promote",
"(",
"self",
")",
":",
"if",
"self",
".",
"expiry",
"is",
"not",
"None",
":",
"self",
".",
"promoted",
"=",
"self",
".",
"time_module",
".",
"time",
"(",
")",
"+",
"self",
".",
"expiry"
] | Mark object as alive, so it won't be collected during next
run of the garbage collector. | [
"Mark",
"object",
"as",
"alive",
"so",
"it",
"won",
"t",
"be",
"collected",
"during",
"next",
"run",
"of",
"the",
"garbage",
"collector",
"."
] | train | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/session.py#L201-L206 |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/session.py | Session.set_handler | def set_handler(self, handler, start_heartbeat=True):
""" Set active handler for the session
@param handler: Associate active cyclone handler with the session
@param start_heartbeat: Should session start heartbeat immediately
"""
# Check if session already has associated handler
if self.handler is not None:
handler.send_pack(proto.disconnect(2010,
"Another connection still open"))
return False
if self._verify_ip and self.conn_info is not None:
# If IP address doesn't match - refuse connection
if handler.request.remote_ip != self.conn_info.ip:
log.msg('Attempted to attach to session %s (%s) from '
'different IP (%s)' % ( self.session_id,
self.conn_info.ip,
handler.request.remote_ip
)
)
handler.send_pack(proto.disconnect(2010, 'Attempted to connect '
'to session from different IP'))
return False
if ( self.state == SESSION_STATE.CLOSING
or self.state == SESSION_STATE.CLOSED):
handler.send_pack(proto.disconnect(*self.get_close_reason()))
return False
# Associate handler and promote session
super(Session, self).set_handler(handler)
self.promote()
if start_heartbeat:
self.start_heartbeat()
return True | python | def set_handler(self, handler, start_heartbeat=True):
""" Set active handler for the session
@param handler: Associate active cyclone handler with the session
@param start_heartbeat: Should session start heartbeat immediately
"""
# Check if session already has associated handler
if self.handler is not None:
handler.send_pack(proto.disconnect(2010,
"Another connection still open"))
return False
if self._verify_ip and self.conn_info is not None:
# If IP address doesn't match - refuse connection
if handler.request.remote_ip != self.conn_info.ip:
log.msg('Attempted to attach to session %s (%s) from '
'different IP (%s)' % ( self.session_id,
self.conn_info.ip,
handler.request.remote_ip
)
)
handler.send_pack(proto.disconnect(2010, 'Attempted to connect '
'to session from different IP'))
return False
if ( self.state == SESSION_STATE.CLOSING
or self.state == SESSION_STATE.CLOSED):
handler.send_pack(proto.disconnect(*self.get_close_reason()))
return False
# Associate handler and promote session
super(Session, self).set_handler(handler)
self.promote()
if start_heartbeat:
self.start_heartbeat()
return True | [
"def",
"set_handler",
"(",
"self",
",",
"handler",
",",
"start_heartbeat",
"=",
"True",
")",
":",
"# Check if session already has associated handler",
"if",
"self",
".",
"handler",
"is",
"not",
"None",
":",
"handler",
".",
"send_pack",
"(",
"proto",
".",
"discon... | Set active handler for the session
@param handler: Associate active cyclone handler with the session
@param start_heartbeat: Should session start heartbeat immediately | [
"Set",
"active",
"handler",
"for",
"the",
"session"
] | train | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/session.py#L268-L308 |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/session.py | Session.verify_state | def verify_state(self):
""" Verify if session was not yet opened. If it is, open it and call
connections C{connectionMade} """
# If we're in CONNECTING state - send 'o' message to the client
if self.state == SESSION_STATE.CONNECTING:
self.handler.send_pack(proto.CONNECT)
# Call parent implementation
super(Session, self).verify_state() | python | def verify_state(self):
""" Verify if session was not yet opened. If it is, open it and call
connections C{connectionMade} """
# If we're in CONNECTING state - send 'o' message to the client
if self.state == SESSION_STATE.CONNECTING:
self.handler.send_pack(proto.CONNECT)
# Call parent implementation
super(Session, self).verify_state() | [
"def",
"verify_state",
"(",
"self",
")",
":",
"# If we're in CONNECTING state - send 'o' message to the client",
"if",
"self",
".",
"state",
"==",
"SESSION_STATE",
".",
"CONNECTING",
":",
"self",
".",
"handler",
".",
"send_pack",
"(",
"proto",
".",
"CONNECT",
")",
... | Verify if session was not yet opened. If it is, open it and call
connections C{connectionMade} | [
"Verify",
"if",
"session",
"was",
"not",
"yet",
"opened",
".",
"If",
"it",
"is",
"open",
"it",
"and",
"call",
"connections",
"C",
"{",
"connectionMade",
"}"
] | train | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/session.py#L310-L318 |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/session.py | Session.send_message | def send_message(self, msg, stats=True):
""" Send or queue outgoing message
@param msg: Message to send
@param stats: If set to True, will update statistics after operation
completes
"""
self.send_jsonified(proto.json_encode(msg), stats) | python | def send_message(self, msg, stats=True):
""" Send or queue outgoing message
@param msg: Message to send
@param stats: If set to True, will update statistics after operation
completes
"""
self.send_jsonified(proto.json_encode(msg), stats) | [
"def",
"send_message",
"(",
"self",
",",
"msg",
",",
"stats",
"=",
"True",
")",
":",
"self",
".",
"send_jsonified",
"(",
"proto",
".",
"json_encode",
"(",
"msg",
")",
",",
"stats",
")"
] | Send or queue outgoing message
@param msg: Message to send
@param stats: If set to True, will update statistics after operation
completes | [
"Send",
"or",
"queue",
"outgoing",
"message"
] | train | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/session.py#L330-L338 |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/session.py | Session.send_jsonified | def send_jsonified(self, msg, stats=True):
""" Send JSON-encoded message
@param msg: JSON encoded string to send
@param stats: If set to True, will update statistics after operation
completes
"""
assert isinstance(msg, basestring), 'Can only send strings'
if isinstance(msg, unicode):
msg = msg.encode('utf-8')
if self._immediate_flush:
if self.handler and self.send_queue.is_empty():
# Send message right away
self.handler.send_pack('a[%s]' % msg)
else:
self.send_queue.push(msg)
self.flush()
else:
self.send_queue.push(msg)
if not self._pending_flush:
reactor.callLater(0, self.flush)
self._pending_flush = True
if stats:
self.stats.packSent(1) | python | def send_jsonified(self, msg, stats=True):
""" Send JSON-encoded message
@param msg: JSON encoded string to send
@param stats: If set to True, will update statistics after operation
completes
"""
assert isinstance(msg, basestring), 'Can only send strings'
if isinstance(msg, unicode):
msg = msg.encode('utf-8')
if self._immediate_flush:
if self.handler and self.send_queue.is_empty():
# Send message right away
self.handler.send_pack('a[%s]' % msg)
else:
self.send_queue.push(msg)
self.flush()
else:
self.send_queue.push(msg)
if not self._pending_flush:
reactor.callLater(0, self.flush)
self._pending_flush = True
if stats:
self.stats.packSent(1) | [
"def",
"send_jsonified",
"(",
"self",
",",
"msg",
",",
"stats",
"=",
"True",
")",
":",
"assert",
"isinstance",
"(",
"msg",
",",
"basestring",
")",
",",
"'Can only send strings'",
"if",
"isinstance",
"(",
"msg",
",",
"unicode",
")",
":",
"msg",
"=",
"msg"... | Send JSON-encoded message
@param msg: JSON encoded string to send
@param stats: If set to True, will update statistics after operation
completes | [
"Send",
"JSON",
"-",
"encoded",
"message"
] | train | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/session.py#L340-L367 |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/session.py | Session.flush | def flush(self):
""" Flush message queue if there's an active connection running """
self._pending_flush = False
if self.handler is None:
return
if self.send_queue.is_empty():
return
self.handler.send_pack('a[%s]' % self.send_queue.get())
self.send_queue.clear() | python | def flush(self):
""" Flush message queue if there's an active connection running """
self._pending_flush = False
if self.handler is None:
return
if self.send_queue.is_empty():
return
self.handler.send_pack('a[%s]' % self.send_queue.get())
self.send_queue.clear() | [
"def",
"flush",
"(",
"self",
")",
":",
"self",
".",
"_pending_flush",
"=",
"False",
"if",
"self",
".",
"handler",
"is",
"None",
":",
"return",
"if",
"self",
".",
"send_queue",
".",
"is_empty",
"(",
")",
":",
"return",
"self",
".",
"handler",
".",
"se... | Flush message queue if there's an active connection running | [
"Flush",
"message",
"queue",
"if",
"there",
"s",
"an",
"active",
"connection",
"running"
] | train | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/session.py#L369-L380 |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/session.py | Session.close | def close(self, code=3000, message='Go away!'):
""" Close session.
@param code: Closing code
@param message: Closing message
"""
if self.state != SESSION_STATE.CLOSED:
# Notify handler
if self.handler is not None:
self.handler.send_pack(proto.disconnect(code, message))
super(Session, self).close(code, message) | python | def close(self, code=3000, message='Go away!'):
""" Close session.
@param code: Closing code
@param message: Closing message
"""
if self.state != SESSION_STATE.CLOSED:
# Notify handler
if self.handler is not None:
self.handler.send_pack(proto.disconnect(code, message))
super(Session, self).close(code, message) | [
"def",
"close",
"(",
"self",
",",
"code",
"=",
"3000",
",",
"message",
"=",
"'Go away!'",
")",
":",
"if",
"self",
".",
"state",
"!=",
"SESSION_STATE",
".",
"CLOSED",
":",
"# Notify handler",
"if",
"self",
".",
"handler",
"is",
"not",
"None",
":",
"self... | Close session.
@param code: Closing code
@param message: Closing message | [
"Close",
"session",
"."
] | train | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/session.py#L382-L394 |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/session.py | Session.start_heartbeat | def start_heartbeat(self):
""" Reset hearbeat timer """
self.stop_heartbeat()
self._heartbeat_timer = task.LoopingCall(self._heartbeat)
self._heartbeat_timer.start(self._heartbeat_interval, False) | python | def start_heartbeat(self):
""" Reset hearbeat timer """
self.stop_heartbeat()
self._heartbeat_timer = task.LoopingCall(self._heartbeat)
self._heartbeat_timer.start(self._heartbeat_interval, False) | [
"def",
"start_heartbeat",
"(",
"self",
")",
":",
"self",
".",
"stop_heartbeat",
"(",
")",
"self",
".",
"_heartbeat_timer",
"=",
"task",
".",
"LoopingCall",
"(",
"self",
".",
"_heartbeat",
")",
"self",
".",
"_heartbeat_timer",
".",
"start",
"(",
"self",
"."... | Reset hearbeat timer | [
"Reset",
"hearbeat",
"timer"
] | train | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/session.py#L397-L402 |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/session.py | Session.messagesReceived | def messagesReceived(self, msg_list):
""" Handle incoming messages
@param msg_list: Message list to process
"""
self.stats.packReceived(len(msg_list))
for msg in msg_list:
self.conn.messageReceived(msg) | python | def messagesReceived(self, msg_list):
""" Handle incoming messages
@param msg_list: Message list to process
"""
self.stats.packReceived(len(msg_list))
for msg in msg_list:
self.conn.messageReceived(msg) | [
"def",
"messagesReceived",
"(",
"self",
",",
"msg_list",
")",
":",
"self",
".",
"stats",
".",
"packReceived",
"(",
"len",
"(",
"msg_list",
")",
")",
"for",
"msg",
"in",
"msg_list",
":",
"self",
".",
"conn",
".",
"messageReceived",
"(",
"msg",
")"
] | Handle incoming messages
@param msg_list: Message list to process | [
"Handle",
"incoming",
"messages"
] | train | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/session.py#L422-L430 |
CivicSpleen/ambry | ambry/valuetype/census/__init__.py | CensusStateGeoid.parser | def parser(cls, v):
"""Ensure that the upstream parser gets two digits. """
return geoid.census.State.parse(str(v).zfill(2)) | python | def parser(cls, v):
"""Ensure that the upstream parser gets two digits. """
return geoid.census.State.parse(str(v).zfill(2)) | [
"def",
"parser",
"(",
"cls",
",",
"v",
")",
":",
"return",
"geoid",
".",
"census",
".",
"State",
".",
"parse",
"(",
"str",
"(",
"v",
")",
".",
"zfill",
"(",
"2",
")",
")"
] | Ensure that the upstream parser gets two digits. | [
"Ensure",
"that",
"the",
"upstream",
"parser",
"gets",
"two",
"digits",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/valuetype/census/__init__.py#L97-L99 |
project-ncl/pnc-cli | pnc_cli/tools/config_utils.py | ConfigReader.get_dependency_structure | def get_dependency_structure(self, artifact=None, include_dependencies=False):
"""
Reads dependency structure. If an artifact is passed in you get only its dependencies otherwise the complete
structure is returned.
:param artifact: an artifact task or artifact name if only an artifact's deps are needed
:param include_dependencies: flag to include also dependencies in returned artifacts and their dependencies in
dependencies dict
:return: tuple of artifact names list and dependencies dictionary where value is a Task list
"""
artifacts = []
dependencies_dict = {}
if artifact:
if isinstance(artifact, str):
artifact = self.get_tasks().get_task(artifact)
artifacts.append(artifact.name)
dependencies_dict[artifact.name] = artifact.ordered_dependencies()
if include_dependencies:
for dep in dependencies_dict[artifact.name]:
artifacts.append(dep.name)
dependencies_dict[dep.name] = dep.ordered_dependencies()
else:
for key, task in self.get_tasks().tasks.iteritems():
artifacts.append(task.name)
dependencies_dict[task.name] = task.ordered_dependencies()
return artifacts, dependencies_dict | python | def get_dependency_structure(self, artifact=None, include_dependencies=False):
"""
Reads dependency structure. If an artifact is passed in you get only its dependencies otherwise the complete
structure is returned.
:param artifact: an artifact task or artifact name if only an artifact's deps are needed
:param include_dependencies: flag to include also dependencies in returned artifacts and their dependencies in
dependencies dict
:return: tuple of artifact names list and dependencies dictionary where value is a Task list
"""
artifacts = []
dependencies_dict = {}
if artifact:
if isinstance(artifact, str):
artifact = self.get_tasks().get_task(artifact)
artifacts.append(artifact.name)
dependencies_dict[artifact.name] = artifact.ordered_dependencies()
if include_dependencies:
for dep in dependencies_dict[artifact.name]:
artifacts.append(dep.name)
dependencies_dict[dep.name] = dep.ordered_dependencies()
else:
for key, task in self.get_tasks().tasks.iteritems():
artifacts.append(task.name)
dependencies_dict[task.name] = task.ordered_dependencies()
return artifacts, dependencies_dict | [
"def",
"get_dependency_structure",
"(",
"self",
",",
"artifact",
"=",
"None",
",",
"include_dependencies",
"=",
"False",
")",
":",
"artifacts",
"=",
"[",
"]",
"dependencies_dict",
"=",
"{",
"}",
"if",
"artifact",
":",
"if",
"isinstance",
"(",
"artifact",
","... | Reads dependency structure. If an artifact is passed in you get only its dependencies otherwise the complete
structure is returned.
:param artifact: an artifact task or artifact name if only an artifact's deps are needed
:param include_dependencies: flag to include also dependencies in returned artifacts and their dependencies in
dependencies dict
:return: tuple of artifact names list and dependencies dictionary where value is a Task list | [
"Reads",
"dependency",
"structure",
".",
"If",
"an",
"artifact",
"is",
"passed",
"in",
"you",
"get",
"only",
"its",
"dependencies",
"otherwise",
"the",
"complete",
"structure",
"is",
"returned",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/config_utils.py#L149-L176 |
project-ncl/pnc-cli | pnc_cli/tools/config_utils.py | ConfigReader._do_read_config | def _do_read_config(self, config_file, pommanipext):
"""Reads config for a single job defined by section."""
parser = InterpolationConfigParser()
dataset = parser.read(config_file)
if config_file not in dataset:
raise IOError("Config file %s not found." % config_file)
if parser.has_option('common','include'):
include = parser.get('common', 'include')
if include is not "":
sections_ = self.read_and_load(include)
for section_ in sections_:
if parser.has_section(section_):
raise DuplicateSectionError( "The config section [%s] is existed in %s and include %s cfg file" % ( section_, config_file, re.split("\\s+", include.strip())[1]))
parser._sections.update(sections_)
pom_manipulator_config = {}
common_section = {}
package_configs = {}
if pommanipext and pommanipext != '' and pommanipext != 'None': #TODO ref: remove none check, it is passed over cmd line in jenkins build
parse_pom_manipulator_ext(pom_manipulator_config, parser, pommanipext)
if not parser.has_section('common'):
logging.error('Mandatory common section missing from configuration file.')
raise NoSectionError('Mandatory common section missing from configuration file.')
common_section['tag'] = parser.get('common', 'tag')
common_section['target'] = parser.get('common', 'target')
common_section['jobprefix'] = parser.get('common', 'jobprefix')
common_section['jobciprefix'] = parser.get('common', 'jobciprefix')
common_section['jobjdk'] = parser.get('common', 'jobjdk')
if parser.has_option('common', 'mvnver'):
common_section['mvnver'] = parser.get('common', 'mvnver')
if parser.has_option('common', 'skiptests'):
common_section['skiptests'] = parser.get('common', 'skiptests')
if parser.has_option('common', 'base'):
common_section['base'] = parser.get('common', 'base')
if parser.has_option('common', 'citemplate'):
common_section['citemplate'] = parser.get('common', 'citemplate')
if parser.has_option('common', 'jenkinstemplate'):
common_section['jenkinstemplate'] = parser.get('common', 'jenkinstemplate')
if parser.has_option('common', 'product_name'):
common_section['product_name'] = parser.get('common', 'product_name')
if parser.has_option('common', 'include'):
common_section['include'] = parser.get('common', 'include')
common_section['jobfailureemail'] = parser.get('common', 'jobfailureemail')
config_dir = utils.get_dir(config_file)
#Jira
if parser.has_option('common', 'shared_config') and parser.get('common', 'shared_config') is not "":
parse_shared_config(common_section, config_dir, parser)
common_section['jobtimeout'] = parser.getint('common', 'jobtimeout')
common_section['options'] = {}
# If the configuration file has global properties insert these into the common properties map.
# These may be overridden later by particular properties.
if parser.has_option('common', 'globalproperties'):
common_section['options']['properties'] = dict(x.strip().split('=') for x in parser.get('common', 'globalproperties').replace(",\n", ",").split(','))
else:
# Always ensure properties has a valid dictionary so code below doesn't need multiple checks.
common_section['options']['properties'] = {}
# The same for global profiles
if parser.has_option('common', 'globalprofiles'):
common_section['options']['profiles'] = [x.strip() for x in parser.get('common', 'globalprofiles').split(',')]
else:
# Always ensure profiles has a valid list so code below doesn't need multiple checks.
common_section['options']['profiles'] = []
if os.path.dirname(config_file):
config_path = os.path.dirname(config_file)
else:
config_path = os.getcwd()
logging.info("Configuration file is %s and path %s", os.path.basename(config_file), config_path)
for section in parser.sections():
config_type = self.read_config_type(parser, section)
if section == 'common' or config_type == "bom-builder-meta":
logging.debug ('Skipping section due to meta-type %s', section)
continue
self._do_read_section(config_path, os.path.basename(config_file), package_configs, parser, section)
return (common_section, package_configs, pom_manipulator_config) | python | def _do_read_config(self, config_file, pommanipext):
"""Reads config for a single job defined by section."""
parser = InterpolationConfigParser()
dataset = parser.read(config_file)
if config_file not in dataset:
raise IOError("Config file %s not found." % config_file)
if parser.has_option('common','include'):
include = parser.get('common', 'include')
if include is not "":
sections_ = self.read_and_load(include)
for section_ in sections_:
if parser.has_section(section_):
raise DuplicateSectionError( "The config section [%s] is existed in %s and include %s cfg file" % ( section_, config_file, re.split("\\s+", include.strip())[1]))
parser._sections.update(sections_)
pom_manipulator_config = {}
common_section = {}
package_configs = {}
if pommanipext and pommanipext != '' and pommanipext != 'None': #TODO ref: remove none check, it is passed over cmd line in jenkins build
parse_pom_manipulator_ext(pom_manipulator_config, parser, pommanipext)
if not parser.has_section('common'):
logging.error('Mandatory common section missing from configuration file.')
raise NoSectionError('Mandatory common section missing from configuration file.')
common_section['tag'] = parser.get('common', 'tag')
common_section['target'] = parser.get('common', 'target')
common_section['jobprefix'] = parser.get('common', 'jobprefix')
common_section['jobciprefix'] = parser.get('common', 'jobciprefix')
common_section['jobjdk'] = parser.get('common', 'jobjdk')
if parser.has_option('common', 'mvnver'):
common_section['mvnver'] = parser.get('common', 'mvnver')
if parser.has_option('common', 'skiptests'):
common_section['skiptests'] = parser.get('common', 'skiptests')
if parser.has_option('common', 'base'):
common_section['base'] = parser.get('common', 'base')
if parser.has_option('common', 'citemplate'):
common_section['citemplate'] = parser.get('common', 'citemplate')
if parser.has_option('common', 'jenkinstemplate'):
common_section['jenkinstemplate'] = parser.get('common', 'jenkinstemplate')
if parser.has_option('common', 'product_name'):
common_section['product_name'] = parser.get('common', 'product_name')
if parser.has_option('common', 'include'):
common_section['include'] = parser.get('common', 'include')
common_section['jobfailureemail'] = parser.get('common', 'jobfailureemail')
config_dir = utils.get_dir(config_file)
#Jira
if parser.has_option('common', 'shared_config') and parser.get('common', 'shared_config') is not "":
parse_shared_config(common_section, config_dir, parser)
common_section['jobtimeout'] = parser.getint('common', 'jobtimeout')
common_section['options'] = {}
# If the configuration file has global properties insert these into the common properties map.
# These may be overridden later by particular properties.
if parser.has_option('common', 'globalproperties'):
common_section['options']['properties'] = dict(x.strip().split('=') for x in parser.get('common', 'globalproperties').replace(",\n", ",").split(','))
else:
# Always ensure properties has a valid dictionary so code below doesn't need multiple checks.
common_section['options']['properties'] = {}
# The same for global profiles
if parser.has_option('common', 'globalprofiles'):
common_section['options']['profiles'] = [x.strip() for x in parser.get('common', 'globalprofiles').split(',')]
else:
# Always ensure profiles has a valid list so code below doesn't need multiple checks.
common_section['options']['profiles'] = []
if os.path.dirname(config_file):
config_path = os.path.dirname(config_file)
else:
config_path = os.getcwd()
logging.info("Configuration file is %s and path %s", os.path.basename(config_file), config_path)
for section in parser.sections():
config_type = self.read_config_type(parser, section)
if section == 'common' or config_type == "bom-builder-meta":
logging.debug ('Skipping section due to meta-type %s', section)
continue
self._do_read_section(config_path, os.path.basename(config_file), package_configs, parser, section)
return (common_section, package_configs, pom_manipulator_config) | [
"def",
"_do_read_config",
"(",
"self",
",",
"config_file",
",",
"pommanipext",
")",
":",
"parser",
"=",
"InterpolationConfigParser",
"(",
")",
"dataset",
"=",
"parser",
".",
"read",
"(",
"config_file",
")",
"if",
"config_file",
"not",
"in",
"dataset",
":",
"... | Reads config for a single job defined by section. | [
"Reads",
"config",
"for",
"a",
"single",
"job",
"defined",
"by",
"section",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/config_utils.py#L360-L445 |
CivicSpleen/ambry | ambry/valuetype/types.py | transform_generator | def transform_generator(fn):
"""A decorator that marks transform pipes that should be called to create the real transform"""
if six.PY2:
fn.func_dict['is_transform_generator'] = True
else:
# py3
fn.__dict__['is_transform_generator'] = True
return fn | python | def transform_generator(fn):
"""A decorator that marks transform pipes that should be called to create the real transform"""
if six.PY2:
fn.func_dict['is_transform_generator'] = True
else:
# py3
fn.__dict__['is_transform_generator'] = True
return fn | [
"def",
"transform_generator",
"(",
"fn",
")",
":",
"if",
"six",
".",
"PY2",
":",
"fn",
".",
"func_dict",
"[",
"'is_transform_generator'",
"]",
"=",
"True",
"else",
":",
"# py3",
"fn",
".",
"__dict__",
"[",
"'is_transform_generator'",
"]",
"=",
"True",
"ret... | A decorator that marks transform pipes that should be called to create the real transform | [
"A",
"decorator",
"that",
"marks",
"transform",
"pipes",
"that",
"should",
"be",
"called",
"to",
"create",
"the",
"real",
"transform"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/valuetype/types.py#L19-L26 |
CivicSpleen/ambry | ambry/valuetype/types.py | is_transform_generator | def is_transform_generator(fn):
"""Return true of the function has been marked with @transform_generator"""
try:
if six.PY2:
fn.func_dict['is_transform_generator'] = True
else:
# py3
return fn.__dict__.get('is_transform_generator', False)
except AttributeError:
return False | python | def is_transform_generator(fn):
"""Return true of the function has been marked with @transform_generator"""
try:
if six.PY2:
fn.func_dict['is_transform_generator'] = True
else:
# py3
return fn.__dict__.get('is_transform_generator', False)
except AttributeError:
return False | [
"def",
"is_transform_generator",
"(",
"fn",
")",
":",
"try",
":",
"if",
"six",
".",
"PY2",
":",
"fn",
".",
"func_dict",
"[",
"'is_transform_generator'",
"]",
"=",
"True",
"else",
":",
"# py3",
"return",
"fn",
".",
"__dict__",
".",
"get",
"(",
"'is_transf... | Return true of the function has been marked with @transform_generator | [
"Return",
"true",
"of",
"the",
"function",
"has",
"been",
"marked",
"with"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/valuetype/types.py#L29-L38 |
CivicSpleen/ambry | ambry/valuetype/types.py | nullify | def nullify(v):
"""Convert empty strings and strings with only spaces to None values. """
if isinstance(v, six.string_types):
v = v.strip()
if v is None or v == '':
return None
else:
return v | python | def nullify(v):
"""Convert empty strings and strings with only spaces to None values. """
if isinstance(v, six.string_types):
v = v.strip()
if v is None or v == '':
return None
else:
return v | [
"def",
"nullify",
"(",
"v",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"six",
".",
"string_types",
")",
":",
"v",
"=",
"v",
".",
"strip",
"(",
")",
"if",
"v",
"is",
"None",
"or",
"v",
"==",
"''",
":",
"return",
"None",
"else",
":",
"return",
... | Convert empty strings and strings with only spaces to None values. | [
"Convert",
"empty",
"strings",
"and",
"strings",
"with",
"only",
"spaces",
"to",
"None",
"values",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/valuetype/types.py#L45-L54 |
CivicSpleen/ambry | ambry/valuetype/types.py | clean_float | def clean_float(v):
"""Remove commas from a float"""
if v is None or not str(v).strip():
return None
return float(str(v).replace(',', '')) | python | def clean_float(v):
"""Remove commas from a float"""
if v is None or not str(v).strip():
return None
return float(str(v).replace(',', '')) | [
"def",
"clean_float",
"(",
"v",
")",
":",
"if",
"v",
"is",
"None",
"or",
"not",
"str",
"(",
"v",
")",
".",
"strip",
"(",
")",
":",
"return",
"None",
"return",
"float",
"(",
"str",
"(",
"v",
")",
".",
"replace",
"(",
"','",
",",
"''",
")",
")"... | Remove commas from a float | [
"Remove",
"commas",
"from",
"a",
"float"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/valuetype/types.py#L57-L63 |
CivicSpleen/ambry | ambry/valuetype/types.py | clean_int | def clean_int(v):
"""Remove commas from a float"""
if v is None or not str(v).strip():
return None
return int(str(v).replace(',', '')) | python | def clean_int(v):
"""Remove commas from a float"""
if v is None or not str(v).strip():
return None
return int(str(v).replace(',', '')) | [
"def",
"clean_int",
"(",
"v",
")",
":",
"if",
"v",
"is",
"None",
"or",
"not",
"str",
"(",
"v",
")",
".",
"strip",
"(",
")",
":",
"return",
"None",
"return",
"int",
"(",
"str",
"(",
"v",
")",
".",
"replace",
"(",
"','",
",",
"''",
")",
")"
] | Remove commas from a float | [
"Remove",
"commas",
"from",
"a",
"float"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/valuetype/types.py#L66-L72 |
CivicSpleen/ambry | ambry/valuetype/types.py | parse_int | def parse_int(v, header_d):
"""Parse as an integer, or a subclass of Int."""
v = nullify(v)
if v is None:
return None
try:
# The converson to float allows converting float strings to ints.
# The conversion int('2.134') will fail.
return int(round(float(v), 0))
except (TypeError, ValueError) as e:
raise CastingError(int, header_d, v, 'Failed to cast to integer') | python | def parse_int(v, header_d):
"""Parse as an integer, or a subclass of Int."""
v = nullify(v)
if v is None:
return None
try:
# The converson to float allows converting float strings to ints.
# The conversion int('2.134') will fail.
return int(round(float(v), 0))
except (TypeError, ValueError) as e:
raise CastingError(int, header_d, v, 'Failed to cast to integer') | [
"def",
"parse_int",
"(",
"v",
",",
"header_d",
")",
":",
"v",
"=",
"nullify",
"(",
"v",
")",
"if",
"v",
"is",
"None",
":",
"return",
"None",
"try",
":",
"# The converson to float allows converting float strings to ints.",
"# The conversion int('2.134') will fail.",
... | Parse as an integer, or a subclass of Int. | [
"Parse",
"as",
"an",
"integer",
"or",
"a",
"subclass",
"of",
"Int",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/valuetype/types.py#L127-L140 |
CivicSpleen/ambry | ambry/valuetype/types.py | _parse_text | def _parse_text(v, header_d):
""" Parses unicode.
Note:
unicode types for py2 and str types for py3.
"""
v = nullify(v)
if v is None:
return None
try:
return six.text_type(v).strip()
except Exception as e:
raise CastingError(six.text_type, header_d, v, str(e)) | python | def _parse_text(v, header_d):
""" Parses unicode.
Note:
unicode types for py2 and str types for py3.
"""
v = nullify(v)
if v is None:
return None
try:
return six.text_type(v).strip()
except Exception as e:
raise CastingError(six.text_type, header_d, v, str(e)) | [
"def",
"_parse_text",
"(",
"v",
",",
"header_d",
")",
":",
"v",
"=",
"nullify",
"(",
"v",
")",
"if",
"v",
"is",
"None",
":",
"return",
"None",
"try",
":",
"return",
"six",
".",
"text_type",
"(",
"v",
")",
".",
"strip",
"(",
")",
"except",
"Except... | Parses unicode.
Note:
unicode types for py2 and str types for py3. | [
"Parses",
"unicode",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/valuetype/types.py#L338-L354 |
CivicSpleen/ambry | ambry/valuetype/types.py | _parse_binary | def _parse_binary(v, header_d):
""" Parses binary string.
Note:
<str> for py2 and <binary> for py3.
"""
# This is often a no-op, but it ocassionally converts numbers into strings
v = nullify(v)
if v is None:
return None
if six.PY2:
try:
return six.binary_type(v).strip()
except UnicodeEncodeError:
return six.text_type(v).strip()
else:
# py3
try:
return six.binary_type(v, 'utf-8').strip()
except UnicodeEncodeError:
return six.text_type(v).strip() | python | def _parse_binary(v, header_d):
""" Parses binary string.
Note:
<str> for py2 and <binary> for py3.
"""
# This is often a no-op, but it ocassionally converts numbers into strings
v = nullify(v)
if v is None:
return None
if six.PY2:
try:
return six.binary_type(v).strip()
except UnicodeEncodeError:
return six.text_type(v).strip()
else:
# py3
try:
return six.binary_type(v, 'utf-8').strip()
except UnicodeEncodeError:
return six.text_type(v).strip() | [
"def",
"_parse_binary",
"(",
"v",
",",
"header_d",
")",
":",
"# This is often a no-op, but it ocassionally converts numbers into strings",
"v",
"=",
"nullify",
"(",
"v",
")",
"if",
"v",
"is",
"None",
":",
"return",
"None",
"if",
"six",
".",
"PY2",
":",
"try",
... | Parses binary string.
Note:
<str> for py2 and <binary> for py3. | [
"Parses",
"binary",
"string",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/valuetype/types.py#L357-L382 |
twisted/epsilon | epsilon/juice.py | parseJuiceHeaders | def parseJuiceHeaders(lines):
"""
Create a JuiceBox from a list of header lines.
@param lines: a list of lines.
"""
b = JuiceBox()
bodylen = 0
key = None
for L in lines:
if L[0] == ' ':
# continuation
assert key is not None
b[key] += '\r\n'+L[1:]
continue
parts = L.split(': ', 1)
if len(parts) != 2:
raise MalformedJuiceBox("Wrong number of parts: %r" % (L,))
key, value = parts
key = normalizeKey(key)
b[key] = value
return int(b.pop(LENGTH, 0)), b | python | def parseJuiceHeaders(lines):
"""
Create a JuiceBox from a list of header lines.
@param lines: a list of lines.
"""
b = JuiceBox()
bodylen = 0
key = None
for L in lines:
if L[0] == ' ':
# continuation
assert key is not None
b[key] += '\r\n'+L[1:]
continue
parts = L.split(': ', 1)
if len(parts) != 2:
raise MalformedJuiceBox("Wrong number of parts: %r" % (L,))
key, value = parts
key = normalizeKey(key)
b[key] = value
return int(b.pop(LENGTH, 0)), b | [
"def",
"parseJuiceHeaders",
"(",
"lines",
")",
":",
"b",
"=",
"JuiceBox",
"(",
")",
"bodylen",
"=",
"0",
"key",
"=",
"None",
"for",
"L",
"in",
"lines",
":",
"if",
"L",
"[",
"0",
"]",
"==",
"' '",
":",
"# continuation",
"assert",
"key",
"is",
"not",... | Create a JuiceBox from a list of header lines.
@param lines: a list of lines. | [
"Create",
"a",
"JuiceBox",
"from",
"a",
"list",
"of",
"header",
"lines",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/juice.py#L283-L304 |
twisted/epsilon | epsilon/juice.py | DispatchMixin.lookupFunction | def lookupFunction(self, proto, name, namespace):
"""Return a callable to invoke when executing the named command.
"""
# Try to find a method to be invoked in a transaction first
# Otherwise fallback to a "regular" method
fName = self.autoDispatchPrefix + name
fObj = getattr(self, fName, None)
if fObj is not None:
# pass the namespace along
return self._auto(fObj, proto, namespace)
assert namespace is None, 'Old-style parsing'
# Fall back to simplistic command dispatching - we probably want to get
# rid of this eventually, there's no reason to do extra work and write
# fewer docs all the time.
fName = self.baseDispatchPrefix + name
return getattr(self, fName, None) | python | def lookupFunction(self, proto, name, namespace):
"""Return a callable to invoke when executing the named command.
"""
# Try to find a method to be invoked in a transaction first
# Otherwise fallback to a "regular" method
fName = self.autoDispatchPrefix + name
fObj = getattr(self, fName, None)
if fObj is not None:
# pass the namespace along
return self._auto(fObj, proto, namespace)
assert namespace is None, 'Old-style parsing'
# Fall back to simplistic command dispatching - we probably want to get
# rid of this eventually, there's no reason to do extra work and write
# fewer docs all the time.
fName = self.baseDispatchPrefix + name
return getattr(self, fName, None) | [
"def",
"lookupFunction",
"(",
"self",
",",
"proto",
",",
"name",
",",
"namespace",
")",
":",
"# Try to find a method to be invoked in a transaction first",
"# Otherwise fallback to a \"regular\" method",
"fName",
"=",
"self",
".",
"autoDispatchPrefix",
"+",
"name",
"fObj",
... | Return a callable to invoke when executing the named command. | [
"Return",
"a",
"callable",
"to",
"invoke",
"when",
"executing",
"the",
"named",
"command",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/juice.py#L246-L262 |
twisted/epsilon | epsilon/juice.py | JuiceParserBase.sendBoxCommand | def sendBoxCommand(self, command, box, requiresAnswer=True):
"""
Send a command across the wire with the given C{juice.Box}.
Returns a Deferred which fires with the response C{juice.Box} when it
is received, or fails with a C{juice.RemoteJuiceError} if an error is
received.
If the Deferred fails and the error is not handled by the caller of
this method, the failure will be logged and the connection dropped.
"""
if self._outstandingRequests is None:
return fail(CONNECTION_LOST)
box[COMMAND] = command
tag = self._nextTag()
if requiresAnswer:
box[ASK] = tag
result = self._outstandingRequests[tag] = Deferred()
else:
result = None
box.sendTo(self)
return result | python | def sendBoxCommand(self, command, box, requiresAnswer=True):
"""
Send a command across the wire with the given C{juice.Box}.
Returns a Deferred which fires with the response C{juice.Box} when it
is received, or fails with a C{juice.RemoteJuiceError} if an error is
received.
If the Deferred fails and the error is not handled by the caller of
this method, the failure will be logged and the connection dropped.
"""
if self._outstandingRequests is None:
return fail(CONNECTION_LOST)
box[COMMAND] = command
tag = self._nextTag()
if requiresAnswer:
box[ASK] = tag
result = self._outstandingRequests[tag] = Deferred()
else:
result = None
box.sendTo(self)
return result | [
"def",
"sendBoxCommand",
"(",
"self",
",",
"command",
",",
"box",
",",
"requiresAnswer",
"=",
"True",
")",
":",
"if",
"self",
".",
"_outstandingRequests",
"is",
"None",
":",
"return",
"fail",
"(",
"CONNECTION_LOST",
")",
"box",
"[",
"COMMAND",
"]",
"=",
... | Send a command across the wire with the given C{juice.Box}.
Returns a Deferred which fires with the response C{juice.Box} when it
is received, or fails with a C{juice.RemoteJuiceError} if an error is
received.
If the Deferred fails and the error is not handled by the caller of
this method, the failure will be logged and the connection dropped. | [
"Send",
"a",
"command",
"across",
"the",
"wire",
"with",
"the",
"given",
"C",
"{",
"juice",
".",
"Box",
"}",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/juice.py#L386-L407 |
twisted/epsilon | epsilon/juice.py | Juice._switchTo | def _switchTo(self, newProto, clientFactory=None):
""" Switch this Juice instance to a new protocol. You need to do this
'simultaneously' on both ends of a connection; the easiest way to do
this is to use a subclass of ProtocolSwitchCommand.
"""
assert self.innerProtocol is None, "Protocol can only be safely switched once."
self.setRawMode()
self.innerProtocol = newProto
self.innerProtocolClientFactory = clientFactory
newProto.makeConnection(self.transport) | python | def _switchTo(self, newProto, clientFactory=None):
""" Switch this Juice instance to a new protocol. You need to do this
'simultaneously' on both ends of a connection; the easiest way to do
this is to use a subclass of ProtocolSwitchCommand.
"""
assert self.innerProtocol is None, "Protocol can only be safely switched once."
self.setRawMode()
self.innerProtocol = newProto
self.innerProtocolClientFactory = clientFactory
newProto.makeConnection(self.transport) | [
"def",
"_switchTo",
"(",
"self",
",",
"newProto",
",",
"clientFactory",
"=",
"None",
")",
":",
"assert",
"self",
".",
"innerProtocol",
"is",
"None",
",",
"\"Protocol can only be safely switched once.\"",
"self",
".",
"setRawMode",
"(",
")",
"self",
".",
"innerPr... | Switch this Juice instance to a new protocol. You need to do this
'simultaneously' on both ends of a connection; the easiest way to do
this is to use a subclass of ProtocolSwitchCommand. | [
"Switch",
"this",
"Juice",
"instance",
"to",
"a",
"new",
"protocol",
".",
"You",
"need",
"to",
"do",
"this",
"simultaneously",
"on",
"both",
"ends",
"of",
"a",
"connection",
";",
"the",
"easiest",
"way",
"to",
"do",
"this",
"is",
"to",
"use",
"a",
"sub... | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/juice.py#L784-L794 |
twisted/epsilon | epsilon/juice.py | Juice.sendPacket | def sendPacket(self, completeBox):
"""
Send a juice.Box to my peer.
Note: transport.write is never called outside of this method.
"""
assert not self.__locked, "You cannot send juice packets when a connection is locked"
if self._startingTLSBuffer is not None:
self._startingTLSBuffer.append(completeBox)
else:
if debug:
log.msg("Juice send: %s" % pprint.pformat(dict(completeBox.iteritems())))
self.transport.write(completeBox.serialize()) | python | def sendPacket(self, completeBox):
"""
Send a juice.Box to my peer.
Note: transport.write is never called outside of this method.
"""
assert not self.__locked, "You cannot send juice packets when a connection is locked"
if self._startingTLSBuffer is not None:
self._startingTLSBuffer.append(completeBox)
else:
if debug:
log.msg("Juice send: %s" % pprint.pformat(dict(completeBox.iteritems())))
self.transport.write(completeBox.serialize()) | [
"def",
"sendPacket",
"(",
"self",
",",
"completeBox",
")",
":",
"assert",
"not",
"self",
".",
"__locked",
",",
"\"You cannot send juice packets when a connection is locked\"",
"if",
"self",
".",
"_startingTLSBuffer",
"is",
"not",
"None",
":",
"self",
".",
"_starting... | Send a juice.Box to my peer.
Note: transport.write is never called outside of this method. | [
"Send",
"a",
"juice",
".",
"Box",
"to",
"my",
"peer",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/juice.py#L805-L818 |
CivicSpleen/ambry | ambry/orm/plot.py | Plot.dataframe | def dataframe(self, filtered_dims={}, unstack=False, df_class=None, add_code=False):
"""
Yield rows in a reduced format, with one dimension as an index, one measure column per
secondary dimension, and all other dimensions filtered.
:param measure: The column names of one or more measures
:param p_dim: The primary dimension. This will be the index of the dataframe.
:param s_dim: a secondary dimension. The returned frame will be unstacked on this dimension
:param unstack:
:param filtered_dims: A dict of dimension columns names that are filtered, mapped to the dimension value
to select.
:param add_code: When substitution a label for a column, also add the code value.
:return:
"""
measure = self.table.column(measure)
p_dim = self.table.column(p_dim)
assert measure
assert p_dim
if s_dim:
s_dim = self.table.column(s_dim)
from six import text_type
def maybe_quote(v):
from six import string_types
if isinstance(v, string_types):
return '"{}"'.format(v)
else:
return v
all_dims = [p_dim.name] + filtered_dims.keys()
if s_dim:
all_dims.append(s_dim.name)
if filtered_dims:
all_dims += filtered_dims.keys()
all_dims = [text_type(c) for c in all_dims]
# "primary_dimensions" means something different here, all of the dimensions in the
# dataset that do not have children.
primary_dims = [text_type(c.name) for c in self.primary_dimensions]
if set(all_dims) != set(primary_dims):
raise ValueError("The primary, secondary and filtered dimensions must cover all dimensions" +
" {} != {}".format(sorted(all_dims), sorted(primary_dims)))
columns = []
p_dim_label = None
s_dim_label = None
if p_dim.label:
# For geographic datasets, also need the gvid
if p_dim.type_is_gvid:
columns.append(p_dim.name)
p_dim = p_dim_label = p_dim.label
columns.append(p_dim_label.name)
else:
columns.append(p_dim.name)
if s_dim:
if s_dim.label:
s_dim = s_dim_label = s_dim.label
columns.append(s_dim_label.name)
else:
columns.append(s_dim.name)
columns.append(measure.name)
# Create the predicate to filter out the filtered dimensions
if filtered_dims:
code = ' and '.join("row.{} == {}".format(k, maybe_quote(v)) for k, v in filtered_dims.items())
predicate = eval('lambda row: {}'.format(code))
else:
predicate = lambda row: True
df = self.analysis.dataframe(predicate, columns=columns, df_class=df_class)
if unstack:
# Need to set the s_dim in the index to get a hierarchical index, required for unstacking.
# The final df will have only the p_dim as an index.
if s_dim:
df = df.set_index([p_dim.name, s_dim.name])
df = df.unstack()
df.columns = df.columns.get_level_values(1) # [' '.join(col).strip() for col in df.columns.values]
else:
# Can't actually unstack without a second dimension.
df = df.set_index(p_dim.name)
df.reset_index()
return df | python | def dataframe(self, filtered_dims={}, unstack=False, df_class=None, add_code=False):
"""
Yield rows in a reduced format, with one dimension as an index, one measure column per
secondary dimension, and all other dimensions filtered.
:param measure: The column names of one or more measures
:param p_dim: The primary dimension. This will be the index of the dataframe.
:param s_dim: a secondary dimension. The returned frame will be unstacked on this dimension
:param unstack:
:param filtered_dims: A dict of dimension columns names that are filtered, mapped to the dimension value
to select.
:param add_code: When substitution a label for a column, also add the code value.
:return:
"""
measure = self.table.column(measure)
p_dim = self.table.column(p_dim)
assert measure
assert p_dim
if s_dim:
s_dim = self.table.column(s_dim)
from six import text_type
def maybe_quote(v):
from six import string_types
if isinstance(v, string_types):
return '"{}"'.format(v)
else:
return v
all_dims = [p_dim.name] + filtered_dims.keys()
if s_dim:
all_dims.append(s_dim.name)
if filtered_dims:
all_dims += filtered_dims.keys()
all_dims = [text_type(c) for c in all_dims]
# "primary_dimensions" means something different here, all of the dimensions in the
# dataset that do not have children.
primary_dims = [text_type(c.name) for c in self.primary_dimensions]
if set(all_dims) != set(primary_dims):
raise ValueError("The primary, secondary and filtered dimensions must cover all dimensions" +
" {} != {}".format(sorted(all_dims), sorted(primary_dims)))
columns = []
p_dim_label = None
s_dim_label = None
if p_dim.label:
# For geographic datasets, also need the gvid
if p_dim.type_is_gvid:
columns.append(p_dim.name)
p_dim = p_dim_label = p_dim.label
columns.append(p_dim_label.name)
else:
columns.append(p_dim.name)
if s_dim:
if s_dim.label:
s_dim = s_dim_label = s_dim.label
columns.append(s_dim_label.name)
else:
columns.append(s_dim.name)
columns.append(measure.name)
# Create the predicate to filter out the filtered dimensions
if filtered_dims:
code = ' and '.join("row.{} == {}".format(k, maybe_quote(v)) for k, v in filtered_dims.items())
predicate = eval('lambda row: {}'.format(code))
else:
predicate = lambda row: True
df = self.analysis.dataframe(predicate, columns=columns, df_class=df_class)
if unstack:
# Need to set the s_dim in the index to get a hierarchical index, required for unstacking.
# The final df will have only the p_dim as an index.
if s_dim:
df = df.set_index([p_dim.name, s_dim.name])
df = df.unstack()
df.columns = df.columns.get_level_values(1) # [' '.join(col).strip() for col in df.columns.values]
else:
# Can't actually unstack without a second dimension.
df = df.set_index(p_dim.name)
df.reset_index()
return df | [
"def",
"dataframe",
"(",
"self",
",",
"filtered_dims",
"=",
"{",
"}",
",",
"unstack",
"=",
"False",
",",
"df_class",
"=",
"None",
",",
"add_code",
"=",
"False",
")",
":",
"measure",
"=",
"self",
".",
"table",
".",
"column",
"(",
"measure",
")",
"p_di... | Yield rows in a reduced format, with one dimension as an index, one measure column per
secondary dimension, and all other dimensions filtered.
:param measure: The column names of one or more measures
:param p_dim: The primary dimension. This will be the index of the dataframe.
:param s_dim: a secondary dimension. The returned frame will be unstacked on this dimension
:param unstack:
:param filtered_dims: A dict of dimension columns names that are filtered, mapped to the dimension value
to select.
:param add_code: When substitution a label for a column, also add the code value.
:return: | [
"Yield",
"rows",
"in",
"a",
"reduced",
"format",
"with",
"one",
"dimension",
"as",
"an",
"index",
"one",
"measure",
"column",
"per",
"secondary",
"dimension",
"and",
"all",
"other",
"dimensions",
"filtered",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/plot.py#L52-L160 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigsetrecords_api.py | BuildconfigsetrecordsApi.get_dependency_graph_for_set | def get_dependency_graph_for_set(self, id, **kwargs):
"""
Gets dependency graph for a Build Group Record (running and completed).
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_dependency_graph_for_set(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build record set id. (required)
:return: BuildRecordPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_dependency_graph_for_set_with_http_info(id, **kwargs)
else:
(data) = self.get_dependency_graph_for_set_with_http_info(id, **kwargs)
return data | python | def get_dependency_graph_for_set(self, id, **kwargs):
"""
Gets dependency graph for a Build Group Record (running and completed).
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_dependency_graph_for_set(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build record set id. (required)
:return: BuildRecordPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_dependency_graph_for_set_with_http_info(id, **kwargs)
else:
(data) = self.get_dependency_graph_for_set_with_http_info(id, **kwargs)
return data | [
"def",
"get_dependency_graph_for_set",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_dependency_gra... | Gets dependency graph for a Build Group Record (running and completed).
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_dependency_graph_for_set(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build record set id. (required)
:return: BuildRecordPage
If the method is called asynchronously,
returns the request thread. | [
"Gets",
"dependency",
"graph",
"for",
"a",
"Build",
"Group",
"Record",
"(",
"running",
"and",
"completed",
")",
".",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request"... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigsetrecords_api.py#L385-L409 |
CivicSpleen/ambry | ambry/library/search_backends/sqlite_backend.py | DatasetSQLiteIndex.search | def search(self, search_phrase, limit=None):
""" Finds datasets by search phrase.
Args:
search_phrase (str or unicode):
limit (int, optional): how many results to return. None means without limit.
Returns:
list of DatasetSearchResult instances.
"""
# SQLite FTS can't find terms with `-`, therefore all hyphens were replaced with underscore
# before save. Now to get appropriate result we need to replace all hyphens in the search phrase.
# See http://stackoverflow.com/questions/3865733/how-do-i-escape-the-character-in-sqlite-fts3-queries
search_phrase = search_phrase.replace('-', '_')
query, query_params = self._make_query_from_terms(search_phrase)
self._parsed_query = (query, query_params)
connection = self.backend.library.database.connection
# Operate on the raw connection
connection.connection.create_function('rank', 1, _make_rank_func((1., .1, 0, 0)))
logger.debug('Searching datasets using `{}` query.'.format(query))
results = connection.execute(query,
**query_params).fetchall() # Query on the Sqlite proxy to the raw connection
datasets = defaultdict(DatasetSearchResult)
for result in results:
vid, score = result
datasets[vid] = DatasetSearchResult()
datasets[vid].vid = vid
datasets[vid].b_score = score
logger.debug('Extending datasets with partitions.')
for partition in self.backend.partition_index.search(search_phrase):
datasets[partition.dataset_vid].p_score += partition.score
datasets[partition.dataset_vid].partitions.add(partition)
return list(datasets.values()) | python | def search(self, search_phrase, limit=None):
""" Finds datasets by search phrase.
Args:
search_phrase (str or unicode):
limit (int, optional): how many results to return. None means without limit.
Returns:
list of DatasetSearchResult instances.
"""
# SQLite FTS can't find terms with `-`, therefore all hyphens were replaced with underscore
# before save. Now to get appropriate result we need to replace all hyphens in the search phrase.
# See http://stackoverflow.com/questions/3865733/how-do-i-escape-the-character-in-sqlite-fts3-queries
search_phrase = search_phrase.replace('-', '_')
query, query_params = self._make_query_from_terms(search_phrase)
self._parsed_query = (query, query_params)
connection = self.backend.library.database.connection
# Operate on the raw connection
connection.connection.create_function('rank', 1, _make_rank_func((1., .1, 0, 0)))
logger.debug('Searching datasets using `{}` query.'.format(query))
results = connection.execute(query,
**query_params).fetchall() # Query on the Sqlite proxy to the raw connection
datasets = defaultdict(DatasetSearchResult)
for result in results:
vid, score = result
datasets[vid] = DatasetSearchResult()
datasets[vid].vid = vid
datasets[vid].b_score = score
logger.debug('Extending datasets with partitions.')
for partition in self.backend.partition_index.search(search_phrase):
datasets[partition.dataset_vid].p_score += partition.score
datasets[partition.dataset_vid].partitions.add(partition)
return list(datasets.values()) | [
"def",
"search",
"(",
"self",
",",
"search_phrase",
",",
"limit",
"=",
"None",
")",
":",
"# SQLite FTS can't find terms with `-`, therefore all hyphens were replaced with underscore",
"# before save. Now to get appropriate result we need to replace all hyphens in the search phrase.",
"# ... | Finds datasets by search phrase.
Args:
search_phrase (str or unicode):
limit (int, optional): how many results to return. None means without limit.
Returns:
list of DatasetSearchResult instances. | [
"Finds",
"datasets",
"by",
"search",
"phrase",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/sqlite_backend.py#L104-L142 |
CivicSpleen/ambry | ambry/library/search_backends/sqlite_backend.py | DatasetSQLiteIndex._as_document | def _as_document(self, dataset):
""" Converts dataset to document indexed by to FTS index.
Args:
dataset (orm.Dataset): dataset to convert.
Returns:
dict with structure matches to BaseDatasetIndex._schema.
"""
assert isinstance(dataset, Dataset)
doc = super(self.__class__, self)._as_document(dataset)
# SQLite FTS can't find terms with `-`, replace it with underscore here and while searching.
# See http://stackoverflow.com/questions/3865733/how-do-i-escape-the-character-in-sqlite-fts3-queries
doc['keywords'] = doc['keywords'].replace('-', '_')
doc['doc'] = doc['doc'].replace('-', '_')
doc['title'] = doc['title'].replace('-', '_')
return doc | python | def _as_document(self, dataset):
""" Converts dataset to document indexed by to FTS index.
Args:
dataset (orm.Dataset): dataset to convert.
Returns:
dict with structure matches to BaseDatasetIndex._schema.
"""
assert isinstance(dataset, Dataset)
doc = super(self.__class__, self)._as_document(dataset)
# SQLite FTS can't find terms with `-`, replace it with underscore here and while searching.
# See http://stackoverflow.com/questions/3865733/how-do-i-escape-the-character-in-sqlite-fts3-queries
doc['keywords'] = doc['keywords'].replace('-', '_')
doc['doc'] = doc['doc'].replace('-', '_')
doc['title'] = doc['title'].replace('-', '_')
return doc | [
"def",
"_as_document",
"(",
"self",
",",
"dataset",
")",
":",
"assert",
"isinstance",
"(",
"dataset",
",",
"Dataset",
")",
"doc",
"=",
"super",
"(",
"self",
".",
"__class__",
",",
"self",
")",
".",
"_as_document",
"(",
"dataset",
")",
"# SQLite FTS can't f... | Converts dataset to document indexed by to FTS index.
Args:
dataset (orm.Dataset): dataset to convert.
Returns:
dict with structure matches to BaseDatasetIndex._schema. | [
"Converts",
"dataset",
"to",
"document",
"indexed",
"by",
"to",
"FTS",
"index",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/sqlite_backend.py#L165-L184 |
CivicSpleen/ambry | ambry/library/search_backends/sqlite_backend.py | DatasetSQLiteIndex._index_document | def _index_document(self, document, force=False):
""" Adds document to the index. """
query = text("""
INSERT INTO dataset_index(vid, title, keywords, doc)
VALUES(:vid, :title, :keywords, :doc);
""")
self.backend.library.database.connection.execute(query, **document) | python | def _index_document(self, document, force=False):
""" Adds document to the index. """
query = text("""
INSERT INTO dataset_index(vid, title, keywords, doc)
VALUES(:vid, :title, :keywords, :doc);
""")
self.backend.library.database.connection.execute(query, **document) | [
"def",
"_index_document",
"(",
"self",
",",
"document",
",",
"force",
"=",
"False",
")",
":",
"query",
"=",
"text",
"(",
"\"\"\"\n INSERT INTO dataset_index(vid, title, keywords, doc)\n VALUES(:vid, :title, :keywords, :doc);\n \"\"\"",
")",
"self",
... | Adds document to the index. | [
"Adds",
"document",
"to",
"the",
"index",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/sqlite_backend.py#L186-L192 |
CivicSpleen/ambry | ambry/library/search_backends/sqlite_backend.py | DatasetSQLiteIndex._delete | def _delete(self, vid=None):
""" Deletes given dataset from index.
Args:
vid (str): dataset vid.
"""
query = text("""
DELETE FROM dataset_index
WHERE vid = :vid;
""")
self.backend.library.database.connection.execute(query, vid=vid) | python | def _delete(self, vid=None):
""" Deletes given dataset from index.
Args:
vid (str): dataset vid.
"""
query = text("""
DELETE FROM dataset_index
WHERE vid = :vid;
""")
self.backend.library.database.connection.execute(query, vid=vid) | [
"def",
"_delete",
"(",
"self",
",",
"vid",
"=",
"None",
")",
":",
"query",
"=",
"text",
"(",
"\"\"\"\n DELETE FROM dataset_index\n WHERE vid = :vid;\n \"\"\"",
")",
"self",
".",
"backend",
".",
"library",
".",
"database",
".",
"connection"... | Deletes given dataset from index.
Args:
vid (str): dataset vid. | [
"Deletes",
"given",
"dataset",
"from",
"index",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/sqlite_backend.py#L201-L212 |
CivicSpleen/ambry | ambry/library/search_backends/sqlite_backend.py | DatasetSQLiteIndex.is_indexed | def is_indexed(self, dataset):
""" Returns True if dataset is already indexed. Otherwise returns False. """
query = text("""
SELECT vid
FROM dataset_index
WHERE vid = :vid;
""")
result = self.backend.library.database.connection.execute(query, vid=dataset.vid)
return bool(result.fetchall()) | python | def is_indexed(self, dataset):
""" Returns True if dataset is already indexed. Otherwise returns False. """
query = text("""
SELECT vid
FROM dataset_index
WHERE vid = :vid;
""")
result = self.backend.library.database.connection.execute(query, vid=dataset.vid)
return bool(result.fetchall()) | [
"def",
"is_indexed",
"(",
"self",
",",
"dataset",
")",
":",
"query",
"=",
"text",
"(",
"\"\"\"\n SELECT vid\n FROM dataset_index\n WHERE vid = :vid;\n \"\"\"",
")",
"result",
"=",
"self",
".",
"backend",
".",
"library",
".",
"databa... | Returns True if dataset is already indexed. Otherwise returns False. | [
"Returns",
"True",
"if",
"dataset",
"is",
"already",
"indexed",
".",
"Otherwise",
"returns",
"False",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/sqlite_backend.py#L214-L222 |
CivicSpleen/ambry | ambry/library/search_backends/sqlite_backend.py | DatasetSQLiteIndex.all | def all(self):
""" Returns list with all indexed datasets. """
datasets = []
query = text("""
SELECT vid
FROM dataset_index;""")
for result in self.backend.library.database.connection.execute(query):
res = DatasetSearchResult()
res.vid = result[0]
res.b_score = 1
datasets.append(res)
return datasets | python | def all(self):
""" Returns list with all indexed datasets. """
datasets = []
query = text("""
SELECT vid
FROM dataset_index;""")
for result in self.backend.library.database.connection.execute(query):
res = DatasetSearchResult()
res.vid = result[0]
res.b_score = 1
datasets.append(res)
return datasets | [
"def",
"all",
"(",
"self",
")",
":",
"datasets",
"=",
"[",
"]",
"query",
"=",
"text",
"(",
"\"\"\"\n SELECT vid\n FROM dataset_index;\"\"\"",
")",
"for",
"result",
"in",
"self",
".",
"backend",
".",
"library",
".",
"database",
".",
"connect... | Returns list with all indexed datasets. | [
"Returns",
"list",
"with",
"all",
"indexed",
"datasets",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/sqlite_backend.py#L224-L237 |
CivicSpleen/ambry | ambry/library/search_backends/sqlite_backend.py | IdentifierSQLiteIndex.list_documents | def list_documents(self, limit=None):
""" Generates vids of all indexed identifiers.
Args:
limit (int, optional): If not empty, the maximum number of results to return
Generates:
str: vid of the document.
"""
limit_str = ''
if limit:
try:
limit_str = 'LIMIT {}'.format(int(limit))
except (TypeError, ValueError):
pass
query = ('SELECT identifier FROM identifier_index ' + limit_str)
for row in self.backend.library.database.connection.execute(query).fetchall():
yield row['identifier'] | python | def list_documents(self, limit=None):
""" Generates vids of all indexed identifiers.
Args:
limit (int, optional): If not empty, the maximum number of results to return
Generates:
str: vid of the document.
"""
limit_str = ''
if limit:
try:
limit_str = 'LIMIT {}'.format(int(limit))
except (TypeError, ValueError):
pass
query = ('SELECT identifier FROM identifier_index ' + limit_str)
for row in self.backend.library.database.connection.execute(query).fetchall():
yield row['identifier'] | [
"def",
"list_documents",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"limit_str",
"=",
"''",
"if",
"limit",
":",
"try",
":",
"limit_str",
"=",
"'LIMIT {}'",
".",
"format",
"(",
"int",
"(",
"limit",
")",
")",
"except",
"(",
"TypeError",
",",
"Va... | Generates vids of all indexed identifiers.
Args:
limit (int, optional): If not empty, the maximum number of results to return
Generates:
str: vid of the document. | [
"Generates",
"vids",
"of",
"all",
"indexed",
"identifiers",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/sqlite_backend.py#L289-L308 |
CivicSpleen/ambry | ambry/library/search_backends/sqlite_backend.py | IdentifierSQLiteIndex.reset | def reset(self):
""" Drops index table. """
query = """
DROP TABLE identifier_index;
"""
self.backend.library.database.connection.execute(query) | python | def reset(self):
""" Drops index table. """
query = """
DROP TABLE identifier_index;
"""
self.backend.library.database.connection.execute(query) | [
"def",
"reset",
"(",
"self",
")",
":",
"query",
"=",
"\"\"\"\n DROP TABLE identifier_index;\n \"\"\"",
"self",
".",
"backend",
".",
"library",
".",
"database",
".",
"connection",
".",
"execute",
"(",
"query",
")"
] | Drops index table. | [
"Drops",
"index",
"table",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/sqlite_backend.py#L318-L323 |
CivicSpleen/ambry | ambry/library/search_backends/sqlite_backend.py | IdentifierSQLiteIndex._delete | def _delete(self, identifier=None):
""" Deletes given identifier from index.
Args:
identifier (str): identifier of the document to delete.
"""
query = text("""
DELETE FROM identifier_index
WHERE identifier = :identifier;
""")
self.backend.library.database.connection.execute(query, identifier=identifier) | python | def _delete(self, identifier=None):
""" Deletes given identifier from index.
Args:
identifier (str): identifier of the document to delete.
"""
query = text("""
DELETE FROM identifier_index
WHERE identifier = :identifier;
""")
self.backend.library.database.connection.execute(query, identifier=identifier) | [
"def",
"_delete",
"(",
"self",
",",
"identifier",
"=",
"None",
")",
":",
"query",
"=",
"text",
"(",
"\"\"\"\n DELETE FROM identifier_index\n WHERE identifier = :identifier;\n \"\"\"",
")",
"self",
".",
"backend",
".",
"library",
".",
"database... | Deletes given identifier from index.
Args:
identifier (str): identifier of the document to delete. | [
"Deletes",
"given",
"identifier",
"from",
"index",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/sqlite_backend.py#L325-L336 |
CivicSpleen/ambry | ambry/library/search_backends/sqlite_backend.py | IdentifierSQLiteIndex.is_indexed | def is_indexed(self, identifier):
""" Returns True if identifier is already indexed. Otherwise returns False. """
query = text("""
SELECT identifier
FROM identifier_index
WHERE identifier = :identifier;
""")
result = self.backend.library.database.connection.execute(query, identifier=identifier['identifier'])
return bool(result.fetchall()) | python | def is_indexed(self, identifier):
""" Returns True if identifier is already indexed. Otherwise returns False. """
query = text("""
SELECT identifier
FROM identifier_index
WHERE identifier = :identifier;
""")
result = self.backend.library.database.connection.execute(query, identifier=identifier['identifier'])
return bool(result.fetchall()) | [
"def",
"is_indexed",
"(",
"self",
",",
"identifier",
")",
":",
"query",
"=",
"text",
"(",
"\"\"\"\n SELECT identifier\n FROM identifier_index\n WHERE identifier = :identifier;\n \"\"\"",
")",
"result",
"=",
"self",
".",
"backend",
".",
... | Returns True if identifier is already indexed. Otherwise returns False. | [
"Returns",
"True",
"if",
"identifier",
"is",
"already",
"indexed",
".",
"Otherwise",
"returns",
"False",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/sqlite_backend.py#L338-L346 |
CivicSpleen/ambry | ambry/library/search_backends/sqlite_backend.py | IdentifierSQLiteIndex.all | def all(self):
""" Returns list with all indexed identifiers. """
identifiers = []
query = text("""
SELECT identifier, type, name
FROM identifier_index;""")
for result in self.backend.library.database.connection.execute(query):
vid, type_, name = result
res = IdentifierSearchResult(
score=1, vid=vid, type=type_, name=name)
identifiers.append(res)
return identifiers | python | def all(self):
""" Returns list with all indexed identifiers. """
identifiers = []
query = text("""
SELECT identifier, type, name
FROM identifier_index;""")
for result in self.backend.library.database.connection.execute(query):
vid, type_, name = result
res = IdentifierSearchResult(
score=1, vid=vid, type=type_, name=name)
identifiers.append(res)
return identifiers | [
"def",
"all",
"(",
"self",
")",
":",
"identifiers",
"=",
"[",
"]",
"query",
"=",
"text",
"(",
"\"\"\"\n SELECT identifier, type, name\n FROM identifier_index;\"\"\"",
")",
"for",
"result",
"in",
"self",
".",
"backend",
".",
"library",
".",
"dat... | Returns list with all indexed identifiers. | [
"Returns",
"list",
"with",
"all",
"indexed",
"identifiers",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/sqlite_backend.py#L348-L361 |
CivicSpleen/ambry | ambry/library/search_backends/sqlite_backend.py | PartitionSQLiteIndex.search | def search(self, search_phrase, limit=None):
""" Finds partitions by search phrase.
Args:
search_phrase (str or unicode):
limit (int, optional): how many results to generate. None means without limit.
Generates:
PartitionSearchResult instances.
"""
# SQLite FTS can't find terms with `-`, therefore all hyphens replaced with underscore before save.
# Now to make proper query we need to replace all hyphens in the search phrase.
# See http://stackoverflow.com/questions/3865733/how-do-i-escape-the-character-in-sqlite-fts3-queries
search_phrase = search_phrase.replace('-', '_')
terms = SearchTermParser().parse(search_phrase)
from_year = terms.pop('from', None)
to_year = terms.pop('to', None)
query, query_params = self._make_query_from_terms(terms)
self._parsed_query = (query, query_params)
connection = self.backend.library.database.connection
connection.connection.create_function('rank', 1, _make_rank_func((1., .1, 0, 0)))
# SQLite FTS implementation does not allow to create indexes on FTS tables.
# see https://sqlite.org/fts3.html 1.5. Summary, p 1:
# ... it is not possible to create indices ...
#
# So, filter years range here.
results = connection.execute(query, query_params).fetchall()
for result in results:
vid, dataset_vid, score, db_from_year, db_to_year = result
if from_year and from_year < db_from_year:
continue
if to_year and to_year > db_to_year:
continue
yield PartitionSearchResult(
vid=vid, dataset_vid=dataset_vid, score=score) | python | def search(self, search_phrase, limit=None):
""" Finds partitions by search phrase.
Args:
search_phrase (str or unicode):
limit (int, optional): how many results to generate. None means without limit.
Generates:
PartitionSearchResult instances.
"""
# SQLite FTS can't find terms with `-`, therefore all hyphens replaced with underscore before save.
# Now to make proper query we need to replace all hyphens in the search phrase.
# See http://stackoverflow.com/questions/3865733/how-do-i-escape-the-character-in-sqlite-fts3-queries
search_phrase = search_phrase.replace('-', '_')
terms = SearchTermParser().parse(search_phrase)
from_year = terms.pop('from', None)
to_year = terms.pop('to', None)
query, query_params = self._make_query_from_terms(terms)
self._parsed_query = (query, query_params)
connection = self.backend.library.database.connection
connection.connection.create_function('rank', 1, _make_rank_func((1., .1, 0, 0)))
# SQLite FTS implementation does not allow to create indexes on FTS tables.
# see https://sqlite.org/fts3.html 1.5. Summary, p 1:
# ... it is not possible to create indices ...
#
# So, filter years range here.
results = connection.execute(query, query_params).fetchall()
for result in results:
vid, dataset_vid, score, db_from_year, db_to_year = result
if from_year and from_year < db_from_year:
continue
if to_year and to_year > db_to_year:
continue
yield PartitionSearchResult(
vid=vid, dataset_vid=dataset_vid, score=score) | [
"def",
"search",
"(",
"self",
",",
"search_phrase",
",",
"limit",
"=",
"None",
")",
":",
"# SQLite FTS can't find terms with `-`, therefore all hyphens replaced with underscore before save.",
"# Now to make proper query we need to replace all hyphens in the search phrase.",
"# See http:/... | Finds partitions by search phrase.
Args:
search_phrase (str or unicode):
limit (int, optional): how many results to generate. None means without limit.
Generates:
PartitionSearchResult instances. | [
"Finds",
"partitions",
"by",
"search",
"phrase",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/sqlite_backend.py#L385-L427 |
CivicSpleen/ambry | ambry/library/search_backends/sqlite_backend.py | PartitionSQLiteIndex._as_document | def _as_document(self, partition):
""" Converts partition to document indexed by to FTS index.
Args:
partition (orm.Partition): partition to convert.
Returns:
dict with structure matches to BasePartitionIndex._schema.
"""
doc = super(self.__class__, self)._as_document(partition)
# SQLite FTS can't find terms with `-`, replace it with underscore here and while searching.
# See http://stackoverflow.com/questions/3865733/how-do-i-escape-the-character-in-sqlite-fts3-queries
doc['keywords'] = doc['keywords'].replace('-', '_')
doc['doc'] = doc['doc'].replace('-', '_')
doc['title'] = doc['title'].replace('-', '_')
# pass time_coverage to the _index_document.
doc['time_coverage'] = partition.time_coverage
return doc | python | def _as_document(self, partition):
""" Converts partition to document indexed by to FTS index.
Args:
partition (orm.Partition): partition to convert.
Returns:
dict with structure matches to BasePartitionIndex._schema.
"""
doc = super(self.__class__, self)._as_document(partition)
# SQLite FTS can't find terms with `-`, replace it with underscore here and while searching.
# See http://stackoverflow.com/questions/3865733/how-do-i-escape-the-character-in-sqlite-fts3-queries
doc['keywords'] = doc['keywords'].replace('-', '_')
doc['doc'] = doc['doc'].replace('-', '_')
doc['title'] = doc['title'].replace('-', '_')
# pass time_coverage to the _index_document.
doc['time_coverage'] = partition.time_coverage
return doc | [
"def",
"_as_document",
"(",
"self",
",",
"partition",
")",
":",
"doc",
"=",
"super",
"(",
"self",
".",
"__class__",
",",
"self",
")",
".",
"_as_document",
"(",
"partition",
")",
"# SQLite FTS can't find terms with `-`, replace it with underscore here and while searching... | Converts partition to document indexed by to FTS index.
Args:
partition (orm.Partition): partition to convert.
Returns:
dict with structure matches to BasePartitionIndex._schema. | [
"Converts",
"partition",
"to",
"document",
"indexed",
"by",
"to",
"FTS",
"index",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/sqlite_backend.py#L451-L471 |
CivicSpleen/ambry | ambry/library/search_backends/sqlite_backend.py | PartitionSQLiteIndex._make_query_from_terms | def _make_query_from_terms(self, terms):
""" Creates a query for partition from decomposed search terms.
Args:
terms (dict or unicode or string):
Returns:
tuple of (str, dict): First element is str with FTS query, second is parameters of the query.
"""
match_query = ''
expanded_terms = self._expand_terms(terms)
if expanded_terms['doc']:
match_query = self.backend._and_join(expanded_terms['doc'])
if expanded_terms['keywords']:
if match_query:
match_query = self.backend._and_join(
[match_query, self.backend._join_keywords(expanded_terms['keywords'])])
else:
match_query = self.backend._join_keywords(expanded_terms['keywords'])
if match_query:
query = text("""
SELECT vid, dataset_vid, rank(matchinfo(partition_index)) AS score, from_year, to_year
FROM partition_index
WHERE partition_index MATCH :match_query
ORDER BY score DESC;
""")
query_params = {
'match_query': match_query}
else:
query = text("""
SELECT vid, dataset_vid, rank(matchinfo(partition_index)), from_year, to_year AS score
FROM partition_index""")
query_params = {}
return query, query_params | python | def _make_query_from_terms(self, terms):
""" Creates a query for partition from decomposed search terms.
Args:
terms (dict or unicode or string):
Returns:
tuple of (str, dict): First element is str with FTS query, second is parameters of the query.
"""
match_query = ''
expanded_terms = self._expand_terms(terms)
if expanded_terms['doc']:
match_query = self.backend._and_join(expanded_terms['doc'])
if expanded_terms['keywords']:
if match_query:
match_query = self.backend._and_join(
[match_query, self.backend._join_keywords(expanded_terms['keywords'])])
else:
match_query = self.backend._join_keywords(expanded_terms['keywords'])
if match_query:
query = text("""
SELECT vid, dataset_vid, rank(matchinfo(partition_index)) AS score, from_year, to_year
FROM partition_index
WHERE partition_index MATCH :match_query
ORDER BY score DESC;
""")
query_params = {
'match_query': match_query}
else:
query = text("""
SELECT vid, dataset_vid, rank(matchinfo(partition_index)), from_year, to_year AS score
FROM partition_index""")
query_params = {}
return query, query_params | [
"def",
"_make_query_from_terms",
"(",
"self",
",",
"terms",
")",
":",
"match_query",
"=",
"''",
"expanded_terms",
"=",
"self",
".",
"_expand_terms",
"(",
"terms",
")",
"if",
"expanded_terms",
"[",
"'doc'",
"]",
":",
"match_query",
"=",
"self",
".",
"backend"... | Creates a query for partition from decomposed search terms.
Args:
terms (dict or unicode or string):
Returns:
tuple of (str, dict): First element is str with FTS query, second is parameters of the query. | [
"Creates",
"a",
"query",
"for",
"partition",
"from",
"decomposed",
"search",
"terms",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/sqlite_backend.py#L473-L512 |
CivicSpleen/ambry | ambry/library/search_backends/sqlite_backend.py | PartitionSQLiteIndex._index_document | def _index_document(self, document, force=False):
""" Adds parition document to the index. """
from ambry.util import int_maybe
time_coverage = document.pop('time_coverage', [])
from_year = None
to_year = None
if time_coverage:
from_year = int_maybe(time_coverage[0])
to_year = int_maybe(time_coverage[-1])
query = text("""
INSERT INTO partition_index(vid, dataset_vid, title, keywords, doc, from_year, to_year)
VALUES(:vid, :dataset_vid, :title, :keywords, :doc, :from_year, :to_year); """)
self.backend.library.database.connection.execute(
query, from_year=from_year, to_year=to_year, **document) | python | def _index_document(self, document, force=False):
""" Adds parition document to the index. """
from ambry.util import int_maybe
time_coverage = document.pop('time_coverage', [])
from_year = None
to_year = None
if time_coverage:
from_year = int_maybe(time_coverage[0])
to_year = int_maybe(time_coverage[-1])
query = text("""
INSERT INTO partition_index(vid, dataset_vid, title, keywords, doc, from_year, to_year)
VALUES(:vid, :dataset_vid, :title, :keywords, :doc, :from_year, :to_year); """)
self.backend.library.database.connection.execute(
query, from_year=from_year, to_year=to_year, **document) | [
"def",
"_index_document",
"(",
"self",
",",
"document",
",",
"force",
"=",
"False",
")",
":",
"from",
"ambry",
".",
"util",
"import",
"int_maybe",
"time_coverage",
"=",
"document",
".",
"pop",
"(",
"'time_coverage'",
",",
"[",
"]",
")",
"from_year",
"=",
... | Adds parition document to the index. | [
"Adds",
"parition",
"document",
"to",
"the",
"index",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/sqlite_backend.py#L514-L528 |
CivicSpleen/ambry | ambry/library/search_backends/sqlite_backend.py | PartitionSQLiteIndex.all | def all(self):
""" Returns list with vids of all indexed partitions. """
partitions = []
query = text("""
SELECT dataset_vid, vid
FROM partition_index;""")
for result in self.backend.library.database.connection.execute(query):
dataset_vid, vid = result
partitions.append(PartitionSearchResult(dataset_vid=dataset_vid, vid=vid, score=1))
return partitions | python | def all(self):
""" Returns list with vids of all indexed partitions. """
partitions = []
query = text("""
SELECT dataset_vid, vid
FROM partition_index;""")
for result in self.backend.library.database.connection.execute(query):
dataset_vid, vid = result
partitions.append(PartitionSearchResult(dataset_vid=dataset_vid, vid=vid, score=1))
return partitions | [
"def",
"all",
"(",
"self",
")",
":",
"partitions",
"=",
"[",
"]",
"query",
"=",
"text",
"(",
"\"\"\"\n SELECT dataset_vid, vid\n FROM partition_index;\"\"\"",
")",
"for",
"result",
"in",
"self",
".",
"backend",
".",
"library",
".",
"database",
... | Returns list with vids of all indexed partitions. | [
"Returns",
"list",
"with",
"vids",
"of",
"all",
"indexed",
"partitions",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/sqlite_backend.py#L560-L571 |
kurtraschke/pyRFC3339 | pyrfc3339/utils.py | timedelta_seconds | def timedelta_seconds(td):
'''
Return the offset stored by a :class:`datetime.timedelta` object as an
integer number of seconds. Microseconds, if present, are rounded to
the nearest second.
Delegates to
:meth:`timedelta.total_seconds() <datetime.timedelta.total_seconds()>`
if available.
>>> timedelta_seconds(timedelta(hours=1))
3600
>>> timedelta_seconds(timedelta(hours=-1))
-3600
>>> timedelta_seconds(timedelta(hours=1, minutes=30))
5400
>>> timedelta_seconds(timedelta(hours=1, minutes=30,
... microseconds=300000))
5400
>>> timedelta_seconds(timedelta(hours=1, minutes=30,
... microseconds=900000))
5401
'''
try:
return int(round(td.total_seconds()))
except AttributeError:
days = td.days
seconds = td.seconds
microseconds = td.microseconds
return int(round((days * 86400) + seconds + (microseconds / 1000000))) | python | def timedelta_seconds(td):
'''
Return the offset stored by a :class:`datetime.timedelta` object as an
integer number of seconds. Microseconds, if present, are rounded to
the nearest second.
Delegates to
:meth:`timedelta.total_seconds() <datetime.timedelta.total_seconds()>`
if available.
>>> timedelta_seconds(timedelta(hours=1))
3600
>>> timedelta_seconds(timedelta(hours=-1))
-3600
>>> timedelta_seconds(timedelta(hours=1, minutes=30))
5400
>>> timedelta_seconds(timedelta(hours=1, minutes=30,
... microseconds=300000))
5400
>>> timedelta_seconds(timedelta(hours=1, minutes=30,
... microseconds=900000))
5401
'''
try:
return int(round(td.total_seconds()))
except AttributeError:
days = td.days
seconds = td.seconds
microseconds = td.microseconds
return int(round((days * 86400) + seconds + (microseconds / 1000000))) | [
"def",
"timedelta_seconds",
"(",
"td",
")",
":",
"try",
":",
"return",
"int",
"(",
"round",
"(",
"td",
".",
"total_seconds",
"(",
")",
")",
")",
"except",
"AttributeError",
":",
"days",
"=",
"td",
".",
"days",
"seconds",
"=",
"td",
".",
"seconds",
"m... | Return the offset stored by a :class:`datetime.timedelta` object as an
integer number of seconds. Microseconds, if present, are rounded to
the nearest second.
Delegates to
:meth:`timedelta.total_seconds() <datetime.timedelta.total_seconds()>`
if available.
>>> timedelta_seconds(timedelta(hours=1))
3600
>>> timedelta_seconds(timedelta(hours=-1))
-3600
>>> timedelta_seconds(timedelta(hours=1, minutes=30))
5400
>>> timedelta_seconds(timedelta(hours=1, minutes=30,
... microseconds=300000))
5400
>>> timedelta_seconds(timedelta(hours=1, minutes=30,
... microseconds=900000))
5401 | [
"Return",
"the",
"offset",
"stored",
"by",
"a",
":",
"class",
":",
"datetime",
".",
"timedelta",
"object",
"as",
"an",
"integer",
"number",
"of",
"seconds",
".",
"Microseconds",
"if",
"present",
"are",
"rounded",
"to",
"the",
"nearest",
"second",
"."
] | train | https://github.com/kurtraschke/pyRFC3339/blob/e30cc1555adce0ecc7bd65509a2249d47e5a41b4/pyrfc3339/utils.py#L87-L119 |
kurtraschke/pyRFC3339 | pyrfc3339/utils.py | timezone | def timezone(utcoffset):
'''
Return a string representing the timezone offset.
Remaining seconds are rounded to the nearest minute.
>>> timezone(3600)
'+01:00'
>>> timezone(5400)
'+01:30'
>>> timezone(-28800)
'-08:00'
'''
hours, seconds = divmod(abs(utcoffset), 3600)
minutes = round(float(seconds) / 60)
if utcoffset >= 0:
sign = '+'
else:
sign = '-'
return '{0}{1:02d}:{2:02d}'.format(sign, int(hours), int(minutes)) | python | def timezone(utcoffset):
'''
Return a string representing the timezone offset.
Remaining seconds are rounded to the nearest minute.
>>> timezone(3600)
'+01:00'
>>> timezone(5400)
'+01:30'
>>> timezone(-28800)
'-08:00'
'''
hours, seconds = divmod(abs(utcoffset), 3600)
minutes = round(float(seconds) / 60)
if utcoffset >= 0:
sign = '+'
else:
sign = '-'
return '{0}{1:02d}:{2:02d}'.format(sign, int(hours), int(minutes)) | [
"def",
"timezone",
"(",
"utcoffset",
")",
":",
"hours",
",",
"seconds",
"=",
"divmod",
"(",
"abs",
"(",
"utcoffset",
")",
",",
"3600",
")",
"minutes",
"=",
"round",
"(",
"float",
"(",
"seconds",
")",
"/",
"60",
")",
"if",
"utcoffset",
">=",
"0",
":... | Return a string representing the timezone offset.
Remaining seconds are rounded to the nearest minute.
>>> timezone(3600)
'+01:00'
>>> timezone(5400)
'+01:30'
>>> timezone(-28800)
'-08:00' | [
"Return",
"a",
"string",
"representing",
"the",
"timezone",
"offset",
".",
"Remaining",
"seconds",
"are",
"rounded",
"to",
"the",
"nearest",
"minute",
"."
] | train | https://github.com/kurtraschke/pyRFC3339/blob/e30cc1555adce0ecc7bd65509a2249d47e5a41b4/pyrfc3339/utils.py#L122-L143 |
project-ncl/pnc-cli | pnc_cli/common.py | id_exists | def id_exists(api, search_id):
"""
Test if an ID exists within any arbitrary API
:param api: api to search for search_id
:param search_id: id to test for
:return: True if an entity with ID search_id exists, false otherwise
"""
response = utils.checked_api_call(api, 'get_specific', id=search_id)
return response is not None | python | def id_exists(api, search_id):
"""
Test if an ID exists within any arbitrary API
:param api: api to search for search_id
:param search_id: id to test for
:return: True if an entity with ID search_id exists, false otherwise
"""
response = utils.checked_api_call(api, 'get_specific', id=search_id)
return response is not None | [
"def",
"id_exists",
"(",
"api",
",",
"search_id",
")",
":",
"response",
"=",
"utils",
".",
"checked_api_call",
"(",
"api",
",",
"'get_specific'",
",",
"id",
"=",
"search_id",
")",
"return",
"response",
"is",
"not",
"None"
] | Test if an ID exists within any arbitrary API
:param api: api to search for search_id
:param search_id: id to test for
:return: True if an entity with ID search_id exists, false otherwise | [
"Test",
"if",
"an",
"ID",
"exists",
"within",
"any",
"arbitrary",
"API",
":",
"param",
"api",
":",
"api",
"to",
"search",
"for",
"search_id",
":",
"param",
"search_id",
":",
"id",
"to",
"test",
"for",
":",
"return",
":",
"True",
"if",
"an",
"entity",
... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/common.py#L19-L27 |
project-ncl/pnc-cli | pnc_cli/common.py | get_id_by_name | def get_id_by_name(api, search_name):
"""
calls 'get_all' on the given API with a search name and returns the ID of the entity retrieved, if any, None otherwise
:param api: api to search
:param search_name: name to test for
:return ID of entity matching search_name, None otherwise
"""
entities = api.get_all(q='name==' + "'" + search_name + "'").content
if entities:
return entities[0].id
return | python | def get_id_by_name(api, search_name):
"""
calls 'get_all' on the given API with a search name and returns the ID of the entity retrieved, if any, None otherwise
:param api: api to search
:param search_name: name to test for
:return ID of entity matching search_name, None otherwise
"""
entities = api.get_all(q='name==' + "'" + search_name + "'").content
if entities:
return entities[0].id
return | [
"def",
"get_id_by_name",
"(",
"api",
",",
"search_name",
")",
":",
"entities",
"=",
"api",
".",
"get_all",
"(",
"q",
"=",
"'name=='",
"+",
"\"'\"",
"+",
"search_name",
"+",
"\"'\"",
")",
".",
"content",
"if",
"entities",
":",
"return",
"entities",
"[",
... | calls 'get_all' on the given API with a search name and returns the ID of the entity retrieved, if any, None otherwise
:param api: api to search
:param search_name: name to test for
:return ID of entity matching search_name, None otherwise | [
"calls",
"get_all",
"on",
"the",
"given",
"API",
"with",
"a",
"search",
"name",
"and",
"returns",
"the",
"ID",
"of",
"the",
"entity",
"retrieved",
"if",
"any",
"None",
"otherwise",
":",
"param",
"api",
":",
"api",
"to",
"search",
":",
"param",
"search_na... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/common.py#L30-L40 |
project-ncl/pnc-cli | pnc_cli/common.py | get_entity | def get_entity(api, entity_id):
"""
Generic "getSpecific" call that calls get_specific with the given id
:param api: api to call get_specific on
:param id: id of the entity to retrieve
:return: REST entity
"""
response = utils.checked_api_call(api, 'get_specific', id=entity_id)
if response:
return response.content
return | python | def get_entity(api, entity_id):
"""
Generic "getSpecific" call that calls get_specific with the given id
:param api: api to call get_specific on
:param id: id of the entity to retrieve
:return: REST entity
"""
response = utils.checked_api_call(api, 'get_specific', id=entity_id)
if response:
return response.content
return | [
"def",
"get_entity",
"(",
"api",
",",
"entity_id",
")",
":",
"response",
"=",
"utils",
".",
"checked_api_call",
"(",
"api",
",",
"'get_specific'",
",",
"id",
"=",
"entity_id",
")",
"if",
"response",
":",
"return",
"response",
".",
"content",
"return"
] | Generic "getSpecific" call that calls get_specific with the given id
:param api: api to call get_specific on
:param id: id of the entity to retrieve
:return: REST entity | [
"Generic",
"getSpecific",
"call",
"that",
"calls",
"get_specific",
"with",
"the",
"given",
"id",
":",
"param",
"api",
":",
"api",
"to",
"call",
"get_specific",
"on",
":",
"param",
"id",
":",
"id",
"of",
"the",
"entity",
"to",
"retrieve",
":",
"return",
"... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/common.py#L52-L62 |
CivicSpleen/ambry | ambry/orm/config.py | BuildConfigGroupAccessor.build_duration | def build_duration(self):
"""Return the difference between build and build_done states"""
return int(self.state.build_done) - int(self.state.build) | python | def build_duration(self):
"""Return the difference between build and build_done states"""
return int(self.state.build_done) - int(self.state.build) | [
"def",
"build_duration",
"(",
"self",
")",
":",
"return",
"int",
"(",
"self",
".",
"state",
".",
"build_done",
")",
"-",
"int",
"(",
"self",
".",
"state",
".",
"build",
")"
] | Return the difference between build and build_done states | [
"Return",
"the",
"difference",
"between",
"build",
"and",
"build_done",
"states"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/config.py#L228-L231 |
CivicSpleen/ambry | ambry/orm/config.py | BuildConfigGroupAccessor.build_duration_pretty | def build_duration_pretty(self):
"""Return the difference between build and build_done states, in a human readable format"""
from ambry.util import pretty_time
from time import time
if not self.state.building:
return None
built = self.state.built or time()
try:
return pretty_time(int(built) - int(self.state.building))
except TypeError: # one of the values is None or not a number
return None | python | def build_duration_pretty(self):
"""Return the difference between build and build_done states, in a human readable format"""
from ambry.util import pretty_time
from time import time
if not self.state.building:
return None
built = self.state.built or time()
try:
return pretty_time(int(built) - int(self.state.building))
except TypeError: # one of the values is None or not a number
return None | [
"def",
"build_duration_pretty",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"util",
"import",
"pretty_time",
"from",
"time",
"import",
"time",
"if",
"not",
"self",
".",
"state",
".",
"building",
":",
"return",
"None",
"built",
"=",
"self",
".",
"state",
... | Return the difference between build and build_done states, in a human readable format | [
"Return",
"the",
"difference",
"between",
"build",
"and",
"build_done",
"states",
"in",
"a",
"human",
"readable",
"format"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/config.py#L234-L247 |
CivicSpleen/ambry | ambry/orm/config.py | BuildConfigGroupAccessor.built_datetime | def built_datetime(self):
"""Return the built time as a datetime object"""
from datetime import datetime
try:
return datetime.fromtimestamp(self.state.build_done)
except TypeError:
# build_done is null
return None | python | def built_datetime(self):
"""Return the built time as a datetime object"""
from datetime import datetime
try:
return datetime.fromtimestamp(self.state.build_done)
except TypeError:
# build_done is null
return None | [
"def",
"built_datetime",
"(",
"self",
")",
":",
"from",
"datetime",
"import",
"datetime",
"try",
":",
"return",
"datetime",
".",
"fromtimestamp",
"(",
"self",
".",
"state",
".",
"build_done",
")",
"except",
"TypeError",
":",
"# build_done is null",
"return",
"... | Return the built time as a datetime object | [
"Return",
"the",
"built",
"time",
"as",
"a",
"datetime",
"object"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/config.py#L250-L257 |
CivicSpleen/ambry | ambry/orm/config.py | BuildConfigGroupAccessor.new_datetime | def new_datetime(self):
"""Return the time the bundle was created as a datetime object"""
from datetime import datetime
try:
return datetime.fromtimestamp(self.state.new)
except TypeError:
return None | python | def new_datetime(self):
"""Return the time the bundle was created as a datetime object"""
from datetime import datetime
try:
return datetime.fromtimestamp(self.state.new)
except TypeError:
return None | [
"def",
"new_datetime",
"(",
"self",
")",
":",
"from",
"datetime",
"import",
"datetime",
"try",
":",
"return",
"datetime",
".",
"fromtimestamp",
"(",
"self",
".",
"state",
".",
"new",
")",
"except",
"TypeError",
":",
"return",
"None"
] | Return the time the bundle was created as a datetime object | [
"Return",
"the",
"time",
"the",
"bundle",
"was",
"created",
"as",
"a",
"datetime",
"object"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/config.py#L260-L267 |
CivicSpleen/ambry | ambry/orm/config.py | BuildConfigGroupAccessor.last_datetime | def last_datetime(self):
"""Return the time of the last operation on the bundle as a datetime object"""
from datetime import datetime
try:
return datetime.fromtimestamp(self.state.lasttime)
except TypeError:
return None | python | def last_datetime(self):
"""Return the time of the last operation on the bundle as a datetime object"""
from datetime import datetime
try:
return datetime.fromtimestamp(self.state.lasttime)
except TypeError:
return None | [
"def",
"last_datetime",
"(",
"self",
")",
":",
"from",
"datetime",
"import",
"datetime",
"try",
":",
"return",
"datetime",
".",
"fromtimestamp",
"(",
"self",
".",
"state",
".",
"lasttime",
")",
"except",
"TypeError",
":",
"return",
"None"
] | Return the time of the last operation on the bundle as a datetime object | [
"Return",
"the",
"time",
"of",
"the",
"last",
"operation",
"on",
"the",
"bundle",
"as",
"a",
"datetime",
"object"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/config.py#L270-L277 |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/sessioncontainer.py | SessionContainer.add | def add(self, session):
""" Add session to the container.
@param session: Session object
"""
self._items[session.session_id] = session
if session.expiry is not None:
self._queue.push(session) | python | def add(self, session):
""" Add session to the container.
@param session: Session object
"""
self._items[session.session_id] = session
if session.expiry is not None:
self._queue.push(session) | [
"def",
"add",
"(",
"self",
",",
"session",
")",
":",
"self",
".",
"_items",
"[",
"session",
".",
"session_id",
"]",
"=",
"session",
"if",
"session",
".",
"expiry",
"is",
"not",
"None",
":",
"self",
".",
"_queue",
".",
"push",
"(",
"session",
")"
] | Add session to the container.
@param session: Session object | [
"Add",
"session",
"to",
"the",
"container",
"."
] | train | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/sessioncontainer.py#L12-L20 |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/sessioncontainer.py | SessionContainer.expire | def expire(self, current_time=None):
""" Expire any old entries
@param current_time: Optional time to be used to clean up queue (can be
used in unit tests)
"""
if self._queue.is_empty():
return
if current_time is None:
current_time = time.time()
while not self._queue.is_empty():
# Get top most item
top = self._queue.peek()
# Early exit if item was not promoted and its expiration time
# is greater than now.
if top.promoted is None and top.expiry_date > current_time:
break
# Pop item from the stack
top = self._queue.pop()
need_reschedule = (top.promoted is not None
and top.promoted > current_time)
# Give chance to reschedule
if not need_reschedule:
top.promoted = None
top.on_delete(False)
need_reschedule = (top.promoted is not None
and top.promoted > current_time)
# If item is promoted and expiration time somewhere in future
# just reschedule it
if need_reschedule:
top.expiry_date = top.promoted
top.promoted = None
self._queue.push(top)
else:
del self._items[top.session_id] | python | def expire(self, current_time=None):
""" Expire any old entries
@param current_time: Optional time to be used to clean up queue (can be
used in unit tests)
"""
if self._queue.is_empty():
return
if current_time is None:
current_time = time.time()
while not self._queue.is_empty():
# Get top most item
top = self._queue.peek()
# Early exit if item was not promoted and its expiration time
# is greater than now.
if top.promoted is None and top.expiry_date > current_time:
break
# Pop item from the stack
top = self._queue.pop()
need_reschedule = (top.promoted is not None
and top.promoted > current_time)
# Give chance to reschedule
if not need_reschedule:
top.promoted = None
top.on_delete(False)
need_reschedule = (top.promoted is not None
and top.promoted > current_time)
# If item is promoted and expiration time somewhere in future
# just reschedule it
if need_reschedule:
top.expiry_date = top.promoted
top.promoted = None
self._queue.push(top)
else:
del self._items[top.session_id] | [
"def",
"expire",
"(",
"self",
",",
"current_time",
"=",
"None",
")",
":",
"if",
"self",
".",
"_queue",
".",
"is_empty",
"(",
")",
":",
"return",
"if",
"current_time",
"is",
"None",
":",
"current_time",
"=",
"time",
".",
"time",
"(",
")",
"while",
"no... | Expire any old entries
@param current_time: Optional time to be used to clean up queue (can be
used in unit tests) | [
"Expire",
"any",
"old",
"entries"
] | train | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/sessioncontainer.py#L44-L86 |
CivicSpleen/ambry | ambry/util/mail.py | send_email | def send_email(recipients, subject, message, attachments=None):
""" Sends email.
Args:
recipients (list of str):
subject (str):
message (str):
attachments (list of str): list containing full paths (txt files only) to attach to email.
"""
if not attachments:
attachments = []
if os.path.exists(EMAIL_SETTINGS_FILE):
email_settings = json.load(open(EMAIL_SETTINGS_FILE))
sender = email_settings.get('sender', 'ambry@localhost')
use_tls = email_settings.get('use_tls')
username = email_settings['username']
password = email_settings['password']
server = email_settings['server']
else:
# use local smtp
server = 'localhost'
username = None
password = None
sender = 'ambry@localhost'
# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ','.join(recipients)
msg.attach(MIMEText(message, 'plain'))
# Add attachments.
for file_name in attachments:
if os.path.exists(file_name):
with open(file_name, 'r') as fp:
attachment = MIMEBase('application', 'text')
attachment.set_payload(fp.read())
attachment.add_header(
'Content-Disposition',
'attachment; filename="{}"'.format(os.path.basename(file_name)))
msg.attach(attachment)
# The actual mail send.
srv = smtplib.SMTP(server)
if use_tls:
srv.starttls()
if username:
srv.login(username, password)
srv.sendmail(sender, ','.join(recipients), msg.as_string())
srv.quit() | python | def send_email(recipients, subject, message, attachments=None):
""" Sends email.
Args:
recipients (list of str):
subject (str):
message (str):
attachments (list of str): list containing full paths (txt files only) to attach to email.
"""
if not attachments:
attachments = []
if os.path.exists(EMAIL_SETTINGS_FILE):
email_settings = json.load(open(EMAIL_SETTINGS_FILE))
sender = email_settings.get('sender', 'ambry@localhost')
use_tls = email_settings.get('use_tls')
username = email_settings['username']
password = email_settings['password']
server = email_settings['server']
else:
# use local smtp
server = 'localhost'
username = None
password = None
sender = 'ambry@localhost'
# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ','.join(recipients)
msg.attach(MIMEText(message, 'plain'))
# Add attachments.
for file_name in attachments:
if os.path.exists(file_name):
with open(file_name, 'r') as fp:
attachment = MIMEBase('application', 'text')
attachment.set_payload(fp.read())
attachment.add_header(
'Content-Disposition',
'attachment; filename="{}"'.format(os.path.basename(file_name)))
msg.attach(attachment)
# The actual mail send.
srv = smtplib.SMTP(server)
if use_tls:
srv.starttls()
if username:
srv.login(username, password)
srv.sendmail(sender, ','.join(recipients), msg.as_string())
srv.quit() | [
"def",
"send_email",
"(",
"recipients",
",",
"subject",
",",
"message",
",",
"attachments",
"=",
"None",
")",
":",
"if",
"not",
"attachments",
":",
"attachments",
"=",
"[",
"]",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"EMAIL_SETTINGS_FILE",
")",
":"... | Sends email.
Args:
recipients (list of str):
subject (str):
message (str):
attachments (list of str): list containing full paths (txt files only) to attach to email. | [
"Sends",
"email",
".",
"Args",
":",
"recipients",
"(",
"list",
"of",
"str",
")",
":",
"subject",
"(",
"str",
")",
":",
"message",
"(",
"str",
")",
":",
"attachments",
"(",
"list",
"of",
"str",
")",
":",
"list",
"containing",
"full",
"paths",
"(",
"... | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/mail.py#L13-L64 |
project-ncl/pnc-cli | pnc_cli/productversions.py | list_product_versions | def list_product_versions(page_size=200, page_index=0, sort="", q=""):
"""
List all ProductVersions
"""
content = list_product_versions_raw(page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | python | def list_product_versions(page_size=200, page_index=0, sort="", q=""):
"""
List all ProductVersions
"""
content = list_product_versions_raw(page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | [
"def",
"list_product_versions",
"(",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
",",
"q",
"=",
"\"\"",
")",
":",
"content",
"=",
"list_product_versions_raw",
"(",
"page_size",
",",
"page_index",
",",
"sort",
",",
"q",
... | List all ProductVersions | [
"List",
"all",
"ProductVersions"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/productversions.py#L34-L40 |
project-ncl/pnc-cli | pnc_cli/productversions.py | create_product_version | def create_product_version(product_id, version, **kwargs):
"""
Create a new ProductVersion.
Each ProductVersion represents a supported product release stream, which includes milestones and releases typically associated with a single major.minor version of a Product.
Follows the Red Hat product support cycle, and typically includes Alpha, Beta, GA, and CP releases with the same major.minor version.
Example:
ProductVersion 1.0 includes the following releases:
1.0.Beta1, 1.0.GA, 1.0.1, etc.
"""
data = create_product_version_raw(product_id, version, **kwargs)
if data:
return utils.format_json(data) | python | def create_product_version(product_id, version, **kwargs):
"""
Create a new ProductVersion.
Each ProductVersion represents a supported product release stream, which includes milestones and releases typically associated with a single major.minor version of a Product.
Follows the Red Hat product support cycle, and typically includes Alpha, Beta, GA, and CP releases with the same major.minor version.
Example:
ProductVersion 1.0 includes the following releases:
1.0.Beta1, 1.0.GA, 1.0.1, etc.
"""
data = create_product_version_raw(product_id, version, **kwargs)
if data:
return utils.format_json(data) | [
"def",
"create_product_version",
"(",
"product_id",
",",
"version",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"create_product_version_raw",
"(",
"product_id",
",",
"version",
",",
"*",
"*",
"kwargs",
")",
"if",
"data",
":",
"return",
"utils",
".",
"f... | Create a new ProductVersion.
Each ProductVersion represents a supported product release stream, which includes milestones and releases typically associated with a single major.minor version of a Product.
Follows the Red Hat product support cycle, and typically includes Alpha, Beta, GA, and CP releases with the same major.minor version.
Example:
ProductVersion 1.0 includes the following releases:
1.0.Beta1, 1.0.GA, 1.0.1, etc. | [
"Create",
"a",
"new",
"ProductVersion",
".",
"Each",
"ProductVersion",
"represents",
"a",
"supported",
"product",
"release",
"stream",
"which",
"includes",
"milestones",
"and",
"releases",
"typically",
"associated",
"with",
"a",
"single",
"major",
".",
"minor",
"v... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/productversions.py#L60-L72 |
project-ncl/pnc-cli | pnc_cli/productversions.py | update_product_version | def update_product_version(id, **kwargs):
"""
Update the ProductVersion with ID id with new values.
"""
content = update_product_version_raw(id, **kwargs)
if content:
return utils.format_json(content) | python | def update_product_version(id, **kwargs):
"""
Update the ProductVersion with ID id with new values.
"""
content = update_product_version_raw(id, **kwargs)
if content:
return utils.format_json(content) | [
"def",
"update_product_version",
"(",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"content",
"=",
"update_product_version_raw",
"(",
"id",
",",
"*",
"*",
"kwargs",
")",
"if",
"content",
":",
"return",
"utils",
".",
"format_json",
"(",
"content",
")"
] | Update the ProductVersion with ID id with new values. | [
"Update",
"the",
"ProductVersion",
"with",
"ID",
"id",
"with",
"new",
"values",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/productversions.py#L117-L123 |
SmartTeleMax/iktomi | iktomi/forms/widgets.py | Widget.prepare_data | def prepare_data(self):
'''
Method returning data passed to template.
Subclasses can override it.
'''
value = self.get_raw_value()
return dict(widget=self,
field=self.field,
value=value,
readonly=not self.field.writable) | python | def prepare_data(self):
'''
Method returning data passed to template.
Subclasses can override it.
'''
value = self.get_raw_value()
return dict(widget=self,
field=self.field,
value=value,
readonly=not self.field.writable) | [
"def",
"prepare_data",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"get_raw_value",
"(",
")",
"return",
"dict",
"(",
"widget",
"=",
"self",
",",
"field",
"=",
"self",
".",
"field",
",",
"value",
"=",
"value",
",",
"readonly",
"=",
"not",
"self"... | Method returning data passed to template.
Subclasses can override it. | [
"Method",
"returning",
"data",
"passed",
"to",
"template",
".",
"Subclasses",
"can",
"override",
"it",
"."
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/forms/widgets.py#L52-L61 |
SmartTeleMax/iktomi | iktomi/forms/widgets.py | Widget.render | def render(self):
'''
Renders widget to template
'''
data = self.prepare_data()
if self.field.readable:
return self.env.template.render(self.template, **data)
return '' | python | def render(self):
'''
Renders widget to template
'''
data = self.prepare_data()
if self.field.readable:
return self.env.template.render(self.template, **data)
return '' | [
"def",
"render",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"prepare_data",
"(",
")",
"if",
"self",
".",
"field",
".",
"readable",
":",
"return",
"self",
".",
"env",
".",
"template",
".",
"render",
"(",
"self",
".",
"template",
",",
"*",
"*",... | Renders widget to template | [
"Renders",
"widget",
"to",
"template"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/forms/widgets.py#L66-L73 |
vovanec/httputil | httputil/request_engines/async.py | AsyncRequestEngine._request | def _request(self, url, *,
method='GET', headers=None, data=None, result_callback=None):
"""Perform asynchronous request.
:param str url: request URL.
:param str method: request method.
:param dict headers: request headers.
:param object data: JSON-encodable object.
:param object -> object result_callback: result callback.
:rtype: dict
:raise: APIError
"""
request = self._prepare_request(url, method, headers, data)
retries_left = self._conn_retries
while True:
try:
response = yield self._client.fetch(request)
try:
if result_callback:
return result_callback(response.body)
except (ValueError, TypeError) as err:
raise MalformedResponse(err) from None
return response.body
except httpclient.HTTPError as err:
resp_body = err.response.body \
if err.response is not None else None
if err.code == 599:
if self._conn_retries is None or retries_left <= 0:
raise CommunicationError(err) from None
else:
retries_left -= 1
retry_in = (self._conn_retries - retries_left) * 2
self._log.warning('Server communication error: %s. '
'Retrying in %s seconds.', err,
retry_in)
yield gen.sleep(retry_in)
continue
elif 400 <= err.code < 500:
raise ClientError(err.code, resp_body) from None
raise ServerError(err.code, resp_body) from None | python | def _request(self, url, *,
method='GET', headers=None, data=None, result_callback=None):
"""Perform asynchronous request.
:param str url: request URL.
:param str method: request method.
:param dict headers: request headers.
:param object data: JSON-encodable object.
:param object -> object result_callback: result callback.
:rtype: dict
:raise: APIError
"""
request = self._prepare_request(url, method, headers, data)
retries_left = self._conn_retries
while True:
try:
response = yield self._client.fetch(request)
try:
if result_callback:
return result_callback(response.body)
except (ValueError, TypeError) as err:
raise MalformedResponse(err) from None
return response.body
except httpclient.HTTPError as err:
resp_body = err.response.body \
if err.response is not None else None
if err.code == 599:
if self._conn_retries is None or retries_left <= 0:
raise CommunicationError(err) from None
else:
retries_left -= 1
retry_in = (self._conn_retries - retries_left) * 2
self._log.warning('Server communication error: %s. '
'Retrying in %s seconds.', err,
retry_in)
yield gen.sleep(retry_in)
continue
elif 400 <= err.code < 500:
raise ClientError(err.code, resp_body) from None
raise ServerError(err.code, resp_body) from None | [
"def",
"_request",
"(",
"self",
",",
"url",
",",
"*",
",",
"method",
"=",
"'GET'",
",",
"headers",
"=",
"None",
",",
"data",
"=",
"None",
",",
"result_callback",
"=",
"None",
")",
":",
"request",
"=",
"self",
".",
"_prepare_request",
"(",
"url",
",",... | Perform asynchronous request.
:param str url: request URL.
:param str method: request method.
:param dict headers: request headers.
:param object data: JSON-encodable object.
:param object -> object result_callback: result callback.
:rtype: dict
:raise: APIError | [
"Perform",
"asynchronous",
"request",
"."
] | train | https://github.com/vovanec/httputil/blob/0b8dab5a23166cceb7dbc2a1dbc802ab5b311347/httputil/request_engines/async.py#L56-L102 |
vovanec/httputil | httputil/request_engines/async.py | AsyncRequestEngine._prepare_request | def _prepare_request(self, url, method, headers, data):
"""Prepare HTTP request.
:param str url: request URL.
:param str method: request method.
:param dict headers: request headers.
:param object data: JSON-encodable object.
:rtype: httpclient.HTTPRequest
"""
request = httpclient.HTTPRequest(
url=url, method=method, headers=headers, body=data,
connect_timeout=self._connect_timeout,
request_timeout=self._request_timeout,
auth_username=self._username, auth_password=self._password,
client_cert=self._client_cert, client_key=self._client_key,
ca_certs=self._ca_certs, validate_cert=self._verify_cert)
return request | python | def _prepare_request(self, url, method, headers, data):
"""Prepare HTTP request.
:param str url: request URL.
:param str method: request method.
:param dict headers: request headers.
:param object data: JSON-encodable object.
:rtype: httpclient.HTTPRequest
"""
request = httpclient.HTTPRequest(
url=url, method=method, headers=headers, body=data,
connect_timeout=self._connect_timeout,
request_timeout=self._request_timeout,
auth_username=self._username, auth_password=self._password,
client_cert=self._client_cert, client_key=self._client_key,
ca_certs=self._ca_certs, validate_cert=self._verify_cert)
return request | [
"def",
"_prepare_request",
"(",
"self",
",",
"url",
",",
"method",
",",
"headers",
",",
"data",
")",
":",
"request",
"=",
"httpclient",
".",
"HTTPRequest",
"(",
"url",
"=",
"url",
",",
"method",
"=",
"method",
",",
"headers",
"=",
"headers",
",",
"body... | Prepare HTTP request.
:param str url: request URL.
:param str method: request method.
:param dict headers: request headers.
:param object data: JSON-encodable object.
:rtype: httpclient.HTTPRequest | [
"Prepare",
"HTTP",
"request",
"."
] | train | https://github.com/vovanec/httputil/blob/0b8dab5a23166cceb7dbc2a1dbc802ab5b311347/httputil/request_engines/async.py#L104-L124 |
acorg/dark-matter | dark/blast/alignments.py | BlastReadsAlignments.iter | def iter(self):
"""
Extract BLAST records and yield C{ReadAlignments} instances.
For each file except the first, check that the BLAST parameters are
compatible with those found (above, in __init__) in the first file.
@return: A generator that yields C{ReadAlignments} instances.
"""
# Note that self._reader is already initialized (in __init__) for
# the first input file. This is less clean than it could be, but it
# makes testing easier, since open() is then only called once for
# each input file.
count = 0
reader = self._reader
reads = iter(self.reads)
first = True
for blastFilename in self.blastFilenames:
if first:
# No need to check params in the first file. We already read
# them in and stored them in __init__.
first = False
else:
reader = self._getReader(blastFilename, self.scoreClass)
differences = checkCompatibleParams(
self.params.applicationParams, reader.params)
if differences:
raise ValueError(
'Incompatible BLAST parameters found. The parameters '
'in %s differ from those originally found in %s. %s' %
(blastFilename, self.blastFilenames[0], differences))
for readAlignments in reader.readAlignments(reads):
count += 1
yield readAlignments
# Make sure all reads were used.
try:
read = next(reads)
except StopIteration:
pass
else:
raise ValueError(
'Reads iterator contained more reads than the number of BLAST '
'records found (%d). First unknown read id is %r.' %
(count, read.id)) | python | def iter(self):
"""
Extract BLAST records and yield C{ReadAlignments} instances.
For each file except the first, check that the BLAST parameters are
compatible with those found (above, in __init__) in the first file.
@return: A generator that yields C{ReadAlignments} instances.
"""
# Note that self._reader is already initialized (in __init__) for
# the first input file. This is less clean than it could be, but it
# makes testing easier, since open() is then only called once for
# each input file.
count = 0
reader = self._reader
reads = iter(self.reads)
first = True
for blastFilename in self.blastFilenames:
if first:
# No need to check params in the first file. We already read
# them in and stored them in __init__.
first = False
else:
reader = self._getReader(blastFilename, self.scoreClass)
differences = checkCompatibleParams(
self.params.applicationParams, reader.params)
if differences:
raise ValueError(
'Incompatible BLAST parameters found. The parameters '
'in %s differ from those originally found in %s. %s' %
(blastFilename, self.blastFilenames[0], differences))
for readAlignments in reader.readAlignments(reads):
count += 1
yield readAlignments
# Make sure all reads were used.
try:
read = next(reads)
except StopIteration:
pass
else:
raise ValueError(
'Reads iterator contained more reads than the number of BLAST '
'records found (%d). First unknown read id is %r.' %
(count, read.id)) | [
"def",
"iter",
"(",
"self",
")",
":",
"# Note that self._reader is already initialized (in __init__) for",
"# the first input file. This is less clean than it could be, but it",
"# makes testing easier, since open() is then only called once for",
"# each input file.",
"count",
"=",
"0",
"r... | Extract BLAST records and yield C{ReadAlignments} instances.
For each file except the first, check that the BLAST parameters are
compatible with those found (above, in __init__) in the first file.
@return: A generator that yields C{ReadAlignments} instances. | [
"Extract",
"BLAST",
"records",
"and",
"yield",
"C",
"{",
"ReadAlignments",
"}",
"instances",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/blast/alignments.py#L96-L143 |
acorg/dark-matter | dark/blast/alignments.py | BlastReadsAlignments.getSubjectSequence | def getSubjectSequence(self, title):
"""
Obtain information about a subject sequence given its title.
This information is cached in self._subjectTitleToSubject. It can
be obtained from either a) an sqlite database (given via the
sqliteDatabaseFilename argument to __init__), b) the FASTA that was
originally given to BLAST (via the databaseFilename argument), or
c) from the BLAST database using blastdbcmd (which can be
unreliable - occasionally failing to find subjects that are in its
database).
@param title: A C{str} sequence title from a BLAST hit. Of the form
'gi|63148399|gb|DQ011818.1| Description...'.
@return: An C{AARead} or C{DNARead} instance, depending on the type of
BLAST database in use.
"""
if self.params.application in {'blastp', 'blastx'}:
readClass = AARead
else:
readClass = DNARead
if self._subjectTitleToSubject is None:
if self._databaseFilename is None:
if self._sqliteDatabaseFilename is None:
# Fall back to blastdbcmd. ncbidb has to be imported
# as below so ncbidb.getSequence can be patched by our
# test suite.
from dark import ncbidb
seq = ncbidb.getSequence(
title, self.params.applicationParams['database'])
return readClass(seq.description, str(seq.seq))
else:
# An Sqlite3 database is used to look up subjects.
self._subjectTitleToSubject = SqliteIndex(
self._sqliteDatabaseFilename,
fastaDirectory=self._databaseDirectory,
readClass=readClass)
else:
# Build an in-memory dict to look up subjects. This only
# works for small databases, obviously.
titles = {}
for read in FastaReads(self._databaseFilename,
readClass=readClass):
titles[read.id] = read
self._subjectTitleToSubject = titles
return self._subjectTitleToSubject[title] | python | def getSubjectSequence(self, title):
"""
Obtain information about a subject sequence given its title.
This information is cached in self._subjectTitleToSubject. It can
be obtained from either a) an sqlite database (given via the
sqliteDatabaseFilename argument to __init__), b) the FASTA that was
originally given to BLAST (via the databaseFilename argument), or
c) from the BLAST database using blastdbcmd (which can be
unreliable - occasionally failing to find subjects that are in its
database).
@param title: A C{str} sequence title from a BLAST hit. Of the form
'gi|63148399|gb|DQ011818.1| Description...'.
@return: An C{AARead} or C{DNARead} instance, depending on the type of
BLAST database in use.
"""
if self.params.application in {'blastp', 'blastx'}:
readClass = AARead
else:
readClass = DNARead
if self._subjectTitleToSubject is None:
if self._databaseFilename is None:
if self._sqliteDatabaseFilename is None:
# Fall back to blastdbcmd. ncbidb has to be imported
# as below so ncbidb.getSequence can be patched by our
# test suite.
from dark import ncbidb
seq = ncbidb.getSequence(
title, self.params.applicationParams['database'])
return readClass(seq.description, str(seq.seq))
else:
# An Sqlite3 database is used to look up subjects.
self._subjectTitleToSubject = SqliteIndex(
self._sqliteDatabaseFilename,
fastaDirectory=self._databaseDirectory,
readClass=readClass)
else:
# Build an in-memory dict to look up subjects. This only
# works for small databases, obviously.
titles = {}
for read in FastaReads(self._databaseFilename,
readClass=readClass):
titles[read.id] = read
self._subjectTitleToSubject = titles
return self._subjectTitleToSubject[title] | [
"def",
"getSubjectSequence",
"(",
"self",
",",
"title",
")",
":",
"if",
"self",
".",
"params",
".",
"application",
"in",
"{",
"'blastp'",
",",
"'blastx'",
"}",
":",
"readClass",
"=",
"AARead",
"else",
":",
"readClass",
"=",
"DNARead",
"if",
"self",
".",
... | Obtain information about a subject sequence given its title.
This information is cached in self._subjectTitleToSubject. It can
be obtained from either a) an sqlite database (given via the
sqliteDatabaseFilename argument to __init__), b) the FASTA that was
originally given to BLAST (via the databaseFilename argument), or
c) from the BLAST database using blastdbcmd (which can be
unreliable - occasionally failing to find subjects that are in its
database).
@param title: A C{str} sequence title from a BLAST hit. Of the form
'gi|63148399|gb|DQ011818.1| Description...'.
@return: An C{AARead} or C{DNARead} instance, depending on the type of
BLAST database in use. | [
"Obtain",
"information",
"about",
"a",
"subject",
"sequence",
"given",
"its",
"title",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/blast/alignments.py#L145-L193 |
acorg/dark-matter | dark/blast/alignments.py | BlastReadsAlignments.adjustHspsForPlotting | def adjustHspsForPlotting(self, titleAlignments):
"""
Our HSPs are about to be plotted. If we are using e-values, these need
to be adjusted.
@param titleAlignments: An instance of L{TitleAlignment}.
"""
# If we're using bit scores, there's nothing to do.
if self.scoreClass is HigherIsBetterScore:
return
# Convert all e-values to high positive values, and keep track of the
# maximum converted value.
maxConvertedEValue = None
zeroHsps = []
# Note: don't call self.hsps() here because that will read them
# from disk again, which is not what's wanted.
for hsp in titleAlignments.hsps():
if hsp.score.score == 0.0:
zeroHsps.append(hsp)
else:
convertedEValue = -1.0 * log10(hsp.score.score)
hsp.score.score = convertedEValue
if (maxConvertedEValue is None or
convertedEValue > maxConvertedEValue):
maxConvertedEValue = convertedEValue
if zeroHsps:
# Save values so that we can use them in self.adjustPlot
self._maxConvertedEValue = maxConvertedEValue
self._zeroEValueFound = True
# Adjust all zero e-value HSPs to have numerically high values.
if self.randomizeZeroEValues:
for hsp in zeroHsps:
hsp.score.score = (maxConvertedEValue + 2 + uniform(
0, ZERO_EVALUE_UPPER_RANDOM_INCREMENT))
else:
for count, hsp in enumerate(zeroHsps, start=1):
hsp.score.score = maxConvertedEValue + count
else:
self._zeroEValueFound = False | python | def adjustHspsForPlotting(self, titleAlignments):
"""
Our HSPs are about to be plotted. If we are using e-values, these need
to be adjusted.
@param titleAlignments: An instance of L{TitleAlignment}.
"""
# If we're using bit scores, there's nothing to do.
if self.scoreClass is HigherIsBetterScore:
return
# Convert all e-values to high positive values, and keep track of the
# maximum converted value.
maxConvertedEValue = None
zeroHsps = []
# Note: don't call self.hsps() here because that will read them
# from disk again, which is not what's wanted.
for hsp in titleAlignments.hsps():
if hsp.score.score == 0.0:
zeroHsps.append(hsp)
else:
convertedEValue = -1.0 * log10(hsp.score.score)
hsp.score.score = convertedEValue
if (maxConvertedEValue is None or
convertedEValue > maxConvertedEValue):
maxConvertedEValue = convertedEValue
if zeroHsps:
# Save values so that we can use them in self.adjustPlot
self._maxConvertedEValue = maxConvertedEValue
self._zeroEValueFound = True
# Adjust all zero e-value HSPs to have numerically high values.
if self.randomizeZeroEValues:
for hsp in zeroHsps:
hsp.score.score = (maxConvertedEValue + 2 + uniform(
0, ZERO_EVALUE_UPPER_RANDOM_INCREMENT))
else:
for count, hsp in enumerate(zeroHsps, start=1):
hsp.score.score = maxConvertedEValue + count
else:
self._zeroEValueFound = False | [
"def",
"adjustHspsForPlotting",
"(",
"self",
",",
"titleAlignments",
")",
":",
"# If we're using bit scores, there's nothing to do.",
"if",
"self",
".",
"scoreClass",
"is",
"HigherIsBetterScore",
":",
"return",
"# Convert all e-values to high positive values, and keep track of the"... | Our HSPs are about to be plotted. If we are using e-values, these need
to be adjusted.
@param titleAlignments: An instance of L{TitleAlignment}. | [
"Our",
"HSPs",
"are",
"about",
"to",
"be",
"plotted",
".",
"If",
"we",
"are",
"using",
"e",
"-",
"values",
"these",
"need",
"to",
"be",
"adjusted",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/blast/alignments.py#L195-L237 |
acorg/dark-matter | dark/blast/alignments.py | BlastReadsAlignments.adjustPlot | def adjustPlot(self, readsAx):
"""
Add a horizontal line to the plotted reads if we're plotting e-values
and a zero e-value was found.
@param readsAx: A Matplotlib sub-plot instance, as returned by
matplotlib.pyplot.subplot.
"""
# If we're using bit scores, there's nothing to do.
if self.scoreClass is HigherIsBetterScore:
return
if self._zeroEValueFound:
readsAx.axhline(y=self._maxConvertedEValue + 0.5, color='#cccccc',
linewidth=0.5) | python | def adjustPlot(self, readsAx):
"""
Add a horizontal line to the plotted reads if we're plotting e-values
and a zero e-value was found.
@param readsAx: A Matplotlib sub-plot instance, as returned by
matplotlib.pyplot.subplot.
"""
# If we're using bit scores, there's nothing to do.
if self.scoreClass is HigherIsBetterScore:
return
if self._zeroEValueFound:
readsAx.axhline(y=self._maxConvertedEValue + 0.5, color='#cccccc',
linewidth=0.5) | [
"def",
"adjustPlot",
"(",
"self",
",",
"readsAx",
")",
":",
"# If we're using bit scores, there's nothing to do.",
"if",
"self",
".",
"scoreClass",
"is",
"HigherIsBetterScore",
":",
"return",
"if",
"self",
".",
"_zeroEValueFound",
":",
"readsAx",
".",
"axhline",
"("... | Add a horizontal line to the plotted reads if we're plotting e-values
and a zero e-value was found.
@param readsAx: A Matplotlib sub-plot instance, as returned by
matplotlib.pyplot.subplot. | [
"Add",
"a",
"horizontal",
"line",
"to",
"the",
"plotted",
"reads",
"if",
"we",
"re",
"plotting",
"e",
"-",
"values",
"and",
"a",
"zero",
"e",
"-",
"value",
"was",
"found",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/blast/alignments.py#L239-L253 |
flo-compbio/genometools | genometools/expression/matrix.py | ExpMatrix.sum | def sum(self, axis=0, dtype=None):
"""Sum over rows or columns.
Overrides the default `pandas.DataFrame.sum()` function to prevent
temporary in-memory copies.
"""
if axis not in [0, 1, 'index', 'columns']:
raise ValueError('"axis" parameter must be one of 0, 1, "index", '
'or "columns".')
sum_kwargs = {}
if dtype is not None:
sum_kwargs['dtype'] = dtype
y = self.values.sum(axis=axis, **sum_kwargs)
if axis == 0 or axis == 'index':
y = profile.ExpProfile(y, genes=self.cells)
else:
y = profile.ExpProfile(y, genes=self.genes)
return y | python | def sum(self, axis=0, dtype=None):
"""Sum over rows or columns.
Overrides the default `pandas.DataFrame.sum()` function to prevent
temporary in-memory copies.
"""
if axis not in [0, 1, 'index', 'columns']:
raise ValueError('"axis" parameter must be one of 0, 1, "index", '
'or "columns".')
sum_kwargs = {}
if dtype is not None:
sum_kwargs['dtype'] = dtype
y = self.values.sum(axis=axis, **sum_kwargs)
if axis == 0 or axis == 'index':
y = profile.ExpProfile(y, genes=self.cells)
else:
y = profile.ExpProfile(y, genes=self.genes)
return y | [
"def",
"sum",
"(",
"self",
",",
"axis",
"=",
"0",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"axis",
"not",
"in",
"[",
"0",
",",
"1",
",",
"'index'",
",",
"'columns'",
"]",
":",
"raise",
"ValueError",
"(",
"'\"axis\" parameter must be one of 0, 1, \"inde... | Sum over rows or columns.
Overrides the default `pandas.DataFrame.sum()` function to prevent
temporary in-memory copies. | [
"Sum",
"over",
"rows",
"or",
"columns",
".",
"Overrides",
"the",
"default",
"pandas",
".",
"DataFrame",
".",
"sum",
"()",
"function",
"to",
"prevent",
"temporary",
"in",
"-",
"memory",
"copies",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/matrix.py#L208-L228 |
flo-compbio/genometools | genometools/expression/matrix.py | ExpMatrix.get_heatmap | def get_heatmap(self, highlight_genes=None, highlight_samples=None,
highlight_color=None, **kwargs):
"""Generate a heatmap (`ExpHeatmap`) of the matrix.
See :class:`ExpHeatmap` constructor for keyword arguments.
Parameters
----------
highlight_genes : list of str
List of genes to highlight
highlight_color : str
Color to use for highlighting
Returns
-------
`ExpHeatmap`
The heatmap.
"""
from .visualize import ExpHeatmap
from .visualize import HeatmapGeneAnnotation
from .visualize import HeatmapSampleAnnotation
#if highlight_genes is not None:
# assert isinstance(highlight_genes, Iterable)
#if highlight_samples is not None:
# assert isinstance(highlight_genes, Iterable)
if highlight_color is not None:
assert isinstance(highlight_color, str)
if highlight_color is None:
highlight_color = 'blue'
if highlight_genes is None:
highlight_genes = []
if highlight_samples is None:
highlight_samples = []
gene_annotations = kwargs.pop('gene_annotations', [])
for g in highlight_genes:
gene_annotations.append(
HeatmapGeneAnnotation(g, highlight_color, label=g))
sample_annotations = kwargs.pop('sample_annotations', [])
for s in highlight_samples:
sample_annotations.append(
HeatmapSampleAnnotation(s, highlight_color, label=s)
)
return ExpHeatmap(self,
gene_annotations=gene_annotations,
sample_annotations=sample_annotations,
**kwargs) | python | def get_heatmap(self, highlight_genes=None, highlight_samples=None,
highlight_color=None, **kwargs):
"""Generate a heatmap (`ExpHeatmap`) of the matrix.
See :class:`ExpHeatmap` constructor for keyword arguments.
Parameters
----------
highlight_genes : list of str
List of genes to highlight
highlight_color : str
Color to use for highlighting
Returns
-------
`ExpHeatmap`
The heatmap.
"""
from .visualize import ExpHeatmap
from .visualize import HeatmapGeneAnnotation
from .visualize import HeatmapSampleAnnotation
#if highlight_genes is not None:
# assert isinstance(highlight_genes, Iterable)
#if highlight_samples is not None:
# assert isinstance(highlight_genes, Iterable)
if highlight_color is not None:
assert isinstance(highlight_color, str)
if highlight_color is None:
highlight_color = 'blue'
if highlight_genes is None:
highlight_genes = []
if highlight_samples is None:
highlight_samples = []
gene_annotations = kwargs.pop('gene_annotations', [])
for g in highlight_genes:
gene_annotations.append(
HeatmapGeneAnnotation(g, highlight_color, label=g))
sample_annotations = kwargs.pop('sample_annotations', [])
for s in highlight_samples:
sample_annotations.append(
HeatmapSampleAnnotation(s, highlight_color, label=s)
)
return ExpHeatmap(self,
gene_annotations=gene_annotations,
sample_annotations=sample_annotations,
**kwargs) | [
"def",
"get_heatmap",
"(",
"self",
",",
"highlight_genes",
"=",
"None",
",",
"highlight_samples",
"=",
"None",
",",
"highlight_color",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"visualize",
"import",
"ExpHeatmap",
"from",
".",
"visualize",... | Generate a heatmap (`ExpHeatmap`) of the matrix.
See :class:`ExpHeatmap` constructor for keyword arguments.
Parameters
----------
highlight_genes : list of str
List of genes to highlight
highlight_color : str
Color to use for highlighting
Returns
-------
`ExpHeatmap`
The heatmap. | [
"Generate",
"a",
"heatmap",
"(",
"ExpHeatmap",
")",
"of",
"the",
"matrix",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/matrix.py#L240-L292 |
flo-compbio/genometools | genometools/expression/matrix.py | ExpMatrix.get_figure | def get_figure(self, heatmap_kw=None, **kwargs):
"""Generate a plotly figure showing the matrix as a heatmap.
This is a shortcut for ``ExpMatrix.get_heatmap(...).get_figure(...)``.
See :func:`ExpHeatmap.get_figure` for keyword arguments.
Parameters
----------
heatmap_kw : dict or None
If not None, dictionary containing keyword arguments to be passed
to the `ExpHeatmap` constructor.
Returns
-------
`plotly.graph_objs.Figure`
The plotly figure.
"""
if heatmap_kw is not None:
assert isinstance(heatmap_kw, dict)
if heatmap_kw is None:
heatmap_kw = {}
return self.get_heatmap(**heatmap_kw).get_figure(**kwargs) | python | def get_figure(self, heatmap_kw=None, **kwargs):
"""Generate a plotly figure showing the matrix as a heatmap.
This is a shortcut for ``ExpMatrix.get_heatmap(...).get_figure(...)``.
See :func:`ExpHeatmap.get_figure` for keyword arguments.
Parameters
----------
heatmap_kw : dict or None
If not None, dictionary containing keyword arguments to be passed
to the `ExpHeatmap` constructor.
Returns
-------
`plotly.graph_objs.Figure`
The plotly figure.
"""
if heatmap_kw is not None:
assert isinstance(heatmap_kw, dict)
if heatmap_kw is None:
heatmap_kw = {}
return self.get_heatmap(**heatmap_kw).get_figure(**kwargs) | [
"def",
"get_figure",
"(",
"self",
",",
"heatmap_kw",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"heatmap_kw",
"is",
"not",
"None",
":",
"assert",
"isinstance",
"(",
"heatmap_kw",
",",
"dict",
")",
"if",
"heatmap_kw",
"is",
"None",
":",
"heat... | Generate a plotly figure showing the matrix as a heatmap.
This is a shortcut for ``ExpMatrix.get_heatmap(...).get_figure(...)``.
See :func:`ExpHeatmap.get_figure` for keyword arguments.
Parameters
----------
heatmap_kw : dict or None
If not None, dictionary containing keyword arguments to be passed
to the `ExpHeatmap` constructor.
Returns
-------
`plotly.graph_objs.Figure`
The plotly figure. | [
"Generate",
"a",
"plotly",
"figure",
"showing",
"the",
"matrix",
"as",
"a",
"heatmap",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/matrix.py#L295-L319 |
flo-compbio/genometools | genometools/expression/matrix.py | ExpMatrix.sort_genes | def sort_genes(self, stable=True, inplace=False, ascending=True):
"""Sort the rows of the matrix alphabetically by gene name.
Parameters
----------
stable: bool, optional
Whether to use a stable sorting algorithm. [True]
inplace: bool, optional
Whether to perform the operation in place.[False]
ascending: bool, optional
Whether to sort in ascending order [True]
Returns
-------
`ExpMatrix`
The sorted matrix.
"""
kind = 'quicksort'
if stable:
kind = 'mergesort'
return self.sort_index(kind=kind, inplace=inplace, ascending=ascending) | python | def sort_genes(self, stable=True, inplace=False, ascending=True):
"""Sort the rows of the matrix alphabetically by gene name.
Parameters
----------
stable: bool, optional
Whether to use a stable sorting algorithm. [True]
inplace: bool, optional
Whether to perform the operation in place.[False]
ascending: bool, optional
Whether to sort in ascending order [True]
Returns
-------
`ExpMatrix`
The sorted matrix.
"""
kind = 'quicksort'
if stable:
kind = 'mergesort'
return self.sort_index(kind=kind, inplace=inplace, ascending=ascending) | [
"def",
"sort_genes",
"(",
"self",
",",
"stable",
"=",
"True",
",",
"inplace",
"=",
"False",
",",
"ascending",
"=",
"True",
")",
":",
"kind",
"=",
"'quicksort'",
"if",
"stable",
":",
"kind",
"=",
"'mergesort'",
"return",
"self",
".",
"sort_index",
"(",
... | Sort the rows of the matrix alphabetically by gene name.
Parameters
----------
stable: bool, optional
Whether to use a stable sorting algorithm. [True]
inplace: bool, optional
Whether to perform the operation in place.[False]
ascending: bool, optional
Whether to sort in ascending order [True]
Returns
-------
`ExpMatrix`
The sorted matrix. | [
"Sort",
"the",
"rows",
"of",
"the",
"matrix",
"alphabetically",
"by",
"gene",
"name",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/matrix.py#L322-L342 |
flo-compbio/genometools | genometools/expression/matrix.py | ExpMatrix.sort_samples | def sort_samples(self, stable=True, inplace=False, ascending=True):
"""Sort the columns of the matrix alphabetically by sample name.
Parameters
----------
stable: bool, optional
Whether to use a stable sorting algorithm. [True]
inplace: bool, optional
Whether to perform the operation in place.[False]
ascending: bool, optional
Whether to sort in ascending order [True]
Returns
-------
`ExpMatrix`
The sorted matrix.
"""
kind = 'quicksort'
if stable:
kind = 'mergesort'
return self.sort_index(axis=1, kind=kind, inplace=inplace,
ascending=ascending) | python | def sort_samples(self, stable=True, inplace=False, ascending=True):
"""Sort the columns of the matrix alphabetically by sample name.
Parameters
----------
stable: bool, optional
Whether to use a stable sorting algorithm. [True]
inplace: bool, optional
Whether to perform the operation in place.[False]
ascending: bool, optional
Whether to sort in ascending order [True]
Returns
-------
`ExpMatrix`
The sorted matrix.
"""
kind = 'quicksort'
if stable:
kind = 'mergesort'
return self.sort_index(axis=1, kind=kind, inplace=inplace,
ascending=ascending) | [
"def",
"sort_samples",
"(",
"self",
",",
"stable",
"=",
"True",
",",
"inplace",
"=",
"False",
",",
"ascending",
"=",
"True",
")",
":",
"kind",
"=",
"'quicksort'",
"if",
"stable",
":",
"kind",
"=",
"'mergesort'",
"return",
"self",
".",
"sort_index",
"(",
... | Sort the columns of the matrix alphabetically by sample name.
Parameters
----------
stable: bool, optional
Whether to use a stable sorting algorithm. [True]
inplace: bool, optional
Whether to perform the operation in place.[False]
ascending: bool, optional
Whether to sort in ascending order [True]
Returns
-------
`ExpMatrix`
The sorted matrix. | [
"Sort",
"the",
"columns",
"of",
"the",
"matrix",
"alphabetically",
"by",
"sample",
"name",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/matrix.py#L344-L365 |
flo-compbio/genometools | genometools/expression/matrix.py | ExpMatrix.center_genes | def center_genes(self, use_median=False, inplace=False):
"""Center the expression of each gene (row)."""
if use_median:
X = self.X - \
np.tile(np.median(self.X, axis=1), (self.n, 1)).T
else:
X = self.X - \
np.tile(np.mean(self.X, axis=1), (self.n, 1)).T
if inplace:
self.X[:,:] = X
matrix = self
else:
matrix = ExpMatrix(genes=self.genes, samples=self.samples,
X=X)
return matrix | python | def center_genes(self, use_median=False, inplace=False):
"""Center the expression of each gene (row)."""
if use_median:
X = self.X - \
np.tile(np.median(self.X, axis=1), (self.n, 1)).T
else:
X = self.X - \
np.tile(np.mean(self.X, axis=1), (self.n, 1)).T
if inplace:
self.X[:,:] = X
matrix = self
else:
matrix = ExpMatrix(genes=self.genes, samples=self.samples,
X=X)
return matrix | [
"def",
"center_genes",
"(",
"self",
",",
"use_median",
"=",
"False",
",",
"inplace",
"=",
"False",
")",
":",
"if",
"use_median",
":",
"X",
"=",
"self",
".",
"X",
"-",
"np",
".",
"tile",
"(",
"np",
".",
"median",
"(",
"self",
".",
"X",
",",
"axis"... | Center the expression of each gene (row). | [
"Center",
"the",
"expression",
"of",
"each",
"gene",
"(",
"row",
")",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/matrix.py#L367-L382 |
flo-compbio/genometools | genometools/expression/matrix.py | ExpMatrix.standardize_genes | def standardize_genes(self, inplace=False):
"""Standardize the expression of each gene (row)."""
matrix = self.center_genes(inplace=inplace)
matrix.X[:,:] = matrix.X / \
np.tile(np.std(matrix.X, axis=1, ddof=1), (matrix.n, 1)).T
return matrix | python | def standardize_genes(self, inplace=False):
"""Standardize the expression of each gene (row)."""
matrix = self.center_genes(inplace=inplace)
matrix.X[:,:] = matrix.X / \
np.tile(np.std(matrix.X, axis=1, ddof=1), (matrix.n, 1)).T
return matrix | [
"def",
"standardize_genes",
"(",
"self",
",",
"inplace",
"=",
"False",
")",
":",
"matrix",
"=",
"self",
".",
"center_genes",
"(",
"inplace",
"=",
"inplace",
")",
"matrix",
".",
"X",
"[",
":",
",",
":",
"]",
"=",
"matrix",
".",
"X",
"/",
"np",
".",
... | Standardize the expression of each gene (row). | [
"Standardize",
"the",
"expression",
"of",
"each",
"gene",
"(",
"row",
")",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/matrix.py#L384-L389 |
flo-compbio/genometools | genometools/expression/matrix.py | ExpMatrix.filter_genes | def filter_genes(self, gene_names : Iterable[str], inplace=False):
"""Filter the expression matrix against a _genome (set of genes).
Parameters
----------
gene_names: list of str
The genome to filter the genes against.
inplace: bool, optional
Whether to perform the operation in-place.
Returns
-------
ExpMatrix
The filtered expression matrix.
"""
return self.drop(set(self.genes) - set(gene_names),
inplace=inplace) | python | def filter_genes(self, gene_names : Iterable[str], inplace=False):
"""Filter the expression matrix against a _genome (set of genes).
Parameters
----------
gene_names: list of str
The genome to filter the genes against.
inplace: bool, optional
Whether to perform the operation in-place.
Returns
-------
ExpMatrix
The filtered expression matrix.
"""
return self.drop(set(self.genes) - set(gene_names),
inplace=inplace) | [
"def",
"filter_genes",
"(",
"self",
",",
"gene_names",
":",
"Iterable",
"[",
"str",
"]",
",",
"inplace",
"=",
"False",
")",
":",
"return",
"self",
".",
"drop",
"(",
"set",
"(",
"self",
".",
"genes",
")",
"-",
"set",
"(",
"gene_names",
")",
",",
"in... | Filter the expression matrix against a _genome (set of genes).
Parameters
----------
gene_names: list of str
The genome to filter the genes against.
inplace: bool, optional
Whether to perform the operation in-place.
Returns
-------
ExpMatrix
The filtered expression matrix. | [
"Filter",
"the",
"expression",
"matrix",
"against",
"a",
"_genome",
"(",
"set",
"of",
"genes",
")",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/matrix.py#L391-L408 |
flo-compbio/genometools | genometools/expression/matrix.py | ExpMatrix.sample_correlations | def sample_correlations(self):
"""Returns an `ExpMatrix` containing all pairwise sample correlations.
Returns
-------
`ExpMatrix`
The sample correlation matrix.
"""
C = np.corrcoef(self.X.T)
corr_matrix = ExpMatrix(genes=self.samples, samples=self.samples, X=C)
return corr_matrix | python | def sample_correlations(self):
"""Returns an `ExpMatrix` containing all pairwise sample correlations.
Returns
-------
`ExpMatrix`
The sample correlation matrix.
"""
C = np.corrcoef(self.X.T)
corr_matrix = ExpMatrix(genes=self.samples, samples=self.samples, X=C)
return corr_matrix | [
"def",
"sample_correlations",
"(",
"self",
")",
":",
"C",
"=",
"np",
".",
"corrcoef",
"(",
"self",
".",
"X",
".",
"T",
")",
"corr_matrix",
"=",
"ExpMatrix",
"(",
"genes",
"=",
"self",
".",
"samples",
",",
"samples",
"=",
"self",
".",
"samples",
",",
... | Returns an `ExpMatrix` containing all pairwise sample correlations.
Returns
-------
`ExpMatrix`
The sample correlation matrix. | [
"Returns",
"an",
"ExpMatrix",
"containing",
"all",
"pairwise",
"sample",
"correlations",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/matrix.py#L411-L422 |
flo-compbio/genometools | genometools/expression/matrix.py | ExpMatrix.read_tsv | def read_tsv(cls, file_path: str, gene_table: ExpGeneTable = None,
encoding: str = 'UTF-8', sep: str = '\t'):
"""Read expression matrix from a tab-delimited text file.
Parameters
----------
file_path: str
The path of the text file.
gene_table: `ExpGeneTable` object, optional
The set of valid genes. If given, the genes in the text file will
be filtered against this set of genes. (None)
encoding: str, optional
The file encoding. ("UTF-8")
sep: str, optional
The separator. ("\t")
Returns
-------
`ExpMatrix`
The expression matrix.
"""
# use pd.read_csv to parse the tsv file into a DataFrame
matrix = cls(pd.read_csv(file_path, sep=sep, index_col=0, header=0,
encoding=encoding))
# parse index column separately
# (this seems to be the only way we can prevent pandas from converting
# "nan" or "NaN" to floats in the index)['1_cell_306.120', '1_cell_086.024', '1_cell_168.103']
#ind = pd.read_csv(file_path, sep=sep, usecols=[0, ], header=0,
# encoding=encoding, na_filter=False)
ind = pd.read_csv(file_path, sep=sep, usecols=[0, ], header=None,
skiprows=1, encoding=encoding, na_filter=False)
matrix.index = ind.iloc[:, 0]
matrix.index.name = 'Genes'
if gene_table is not None:
# filter genes
matrix = matrix.filter_genes(gene_table.gene_names)
return matrix | python | def read_tsv(cls, file_path: str, gene_table: ExpGeneTable = None,
encoding: str = 'UTF-8', sep: str = '\t'):
"""Read expression matrix from a tab-delimited text file.
Parameters
----------
file_path: str
The path of the text file.
gene_table: `ExpGeneTable` object, optional
The set of valid genes. If given, the genes in the text file will
be filtered against this set of genes. (None)
encoding: str, optional
The file encoding. ("UTF-8")
sep: str, optional
The separator. ("\t")
Returns
-------
`ExpMatrix`
The expression matrix.
"""
# use pd.read_csv to parse the tsv file into a DataFrame
matrix = cls(pd.read_csv(file_path, sep=sep, index_col=0, header=0,
encoding=encoding))
# parse index column separately
# (this seems to be the only way we can prevent pandas from converting
# "nan" or "NaN" to floats in the index)['1_cell_306.120', '1_cell_086.024', '1_cell_168.103']
#ind = pd.read_csv(file_path, sep=sep, usecols=[0, ], header=0,
# encoding=encoding, na_filter=False)
ind = pd.read_csv(file_path, sep=sep, usecols=[0, ], header=None,
skiprows=1, encoding=encoding, na_filter=False)
matrix.index = ind.iloc[:, 0]
matrix.index.name = 'Genes'
if gene_table is not None:
# filter genes
matrix = matrix.filter_genes(gene_table.gene_names)
return matrix | [
"def",
"read_tsv",
"(",
"cls",
",",
"file_path",
":",
"str",
",",
"gene_table",
":",
"ExpGeneTable",
"=",
"None",
",",
"encoding",
":",
"str",
"=",
"'UTF-8'",
",",
"sep",
":",
"str",
"=",
"'\\t'",
")",
":",
"# use pd.read_csv to parse the tsv file into a DataF... | Read expression matrix from a tab-delimited text file.
Parameters
----------
file_path: str
The path of the text file.
gene_table: `ExpGeneTable` object, optional
The set of valid genes. If given, the genes in the text file will
be filtered against this set of genes. (None)
encoding: str, optional
The file encoding. ("UTF-8")
sep: str, optional
The separator. ("\t")
Returns
-------
`ExpMatrix`
The expression matrix. | [
"Read",
"expression",
"matrix",
"from",
"a",
"tab",
"-",
"delimited",
"text",
"file",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/matrix.py#L426-L466 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.