code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
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) | 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 ... | 1.673784 | 1.702709 | 0.983013 |
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) | 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 in... | 1.587381 | 1.700602 | 0.933423 |
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_group=False) | Create Build group based on Make-Mead configuration file
:param config: Make Mead config name
:return: | 2.299856 | 2.761941 | 0.832696 |
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.iden... | 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 bund... | 2.732615 | 2.635269 | 1.03694 |
# 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()
... | 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. | 2.413935 | 2.359886 | 1.022903 |
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:
... | 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 | 3.907642 | 3.923082 | 0.996064 |
content = update_project_raw(id, **kwargs)
if content:
return utils.format_json(content) | def update_project(id, **kwargs) | Update an existing Project with new information | 6.249269 | 7.238532 | 0.863334 |
content = get_project_raw(id, name)
if content:
return utils.format_json(content) | def get_project(id=None, name=None) | Get a specific Project by ID or name | 6.751878 | 6.805196 | 0.992165 |
content = delete_project_raw(id, name)
if content:
return utils.format_json(content) | def delete_project(id=None, name=None) | Delete a Project by ID or name. | 6.937507 | 7.270999 | 0.954134 |
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="") | List all Projects | 2.927157 | 2.991326 | 0.978548 |
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) | 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)
... | 1.459318 | 1.583941 | 0.92132 |
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) | 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... | 1.445163 | 1.617064 | 0.893695 |
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) | 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)
... | 1.656383 | 1.785881 | 0.927488 |
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) | 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)
... | 1.399938 | 1.579082 | 0.886552 |
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) | 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(respons... | 1.487132 | 1.676591 | 0.886998 |
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) | 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)
... | 1.481468 | 1.582028 | 0.936436 |
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.sessionO... | def set_handler(self, handler) | Set transport handler
@param handler: Handler, should derive from the
C{sockjs.cyclone.transports.base.BaseTransportMixin} | 5.374429 | 5.841447 | 0.920051 |
if self.state == SESSION_STATE.CONNECTING:
self.state = SESSION_STATE.OPEN
self.conn.connectionMade(self.conn_info) | def verify_state(self) | Verify if session was not yet opened. If it is, open it and call
connection's C{connectionMade} | 9.814208 | 6.366851 | 1.541454 |
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_rea... | def close(self, code=3000, message='Go away!') | Close session or endpoint connection.
@param code: Closing code
@param message: Close message | 4.994341 | 5.385893 | 0.9273 |
self.state = SESSION_STATE.CLOSING
reactor.callLater(0, self.close) | def delayed_close(self) | Delayed close - won't close immediately, but on the next reactor
loop. | 7.903571 | 6.724379 | 1.175361 |
return (self.state == SESSION_STATE.CLOSED
or self.state == SESSION_STATE.CLOSING) | def is_closed(self) | Check if session was closed. | 7.150054 | 4.686625 | 1.52563 |
hashstr = '%s%s' % (random.random(), self.time_module.time())
return hashlib.md5(hashstr).hexdigest() | def _random_key(self) | Return random session key | 6.052878 | 5.000212 | 1.210524 |
if self.expiry is not None:
self.promoted = self.time_module.time() + self.expiry | def promote(self) | Mark object as alive, so it won't be collected during next
run of the garbage collector. | 9.714468 | 9.218364 | 1.053817 |
# 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 Non... | 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 | 4.546831 | 4.576452 | 0.993527 |
# 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) | Verify if session was not yet opened. If it is, open it and call
connections C{connectionMade} | 10.29817 | 10.507211 | 0.980105 |
self.send_jsonified(proto.json_encode(msg), stats) | 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 | 21.679811 | 33.608429 | 0.645071 |
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.s... | 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 | 3.6967 | 3.985235 | 0.927599 |
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) | Flush message queue if there's an active connection running | 5.861042 | 5.230297 | 1.120595 |
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!') | Close session.
@param code: Closing code
@param message: Closing message | 7.066343 | 7.130238 | 0.991039 |
self.stop_heartbeat()
self._heartbeat_timer = task.LoopingCall(self._heartbeat)
self._heartbeat_timer.start(self._heartbeat_interval, False) | def start_heartbeat(self) | Reset hearbeat timer | 2.880081 | 2.553406 | 1.127937 |
self.stats.packReceived(len(msg_list))
for msg in msg_list:
self.conn.messageReceived(msg) | def messagesReceived(self, msg_list) | Handle incoming messages
@param msg_list: Message list to process | 6.14457 | 6.703757 | 0.916586 |
return geoid.census.State.parse(str(v).zfill(2)) | def parser(cls, v) | Ensure that the upstream parser gets two digits. | 21.898893 | 11.434543 | 1.915153 |
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()
... | 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... | 2.327604 | 2.100023 | 1.108371 |
if six.PY2:
fn.func_dict['is_transform_generator'] = True
else:
# py3
fn.__dict__['is_transform_generator'] = True
return fn | def transform_generator(fn) | A decorator that marks transform pipes that should be called to create the real transform | 4.12943 | 3.707148 | 1.11391 |
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) | Return true of the function has been marked with @transform_generator | 3.943178 | 3.442076 | 1.145581 |
if isinstance(v, six.string_types):
v = v.strip()
if v is None or v == '':
return None
else:
return v | def nullify(v) | Convert empty strings and strings with only spaces to None values. | 2.899178 | 2.506993 | 1.156436 |
if v is None or not str(v).strip():
return None
return float(str(v).replace(',', '')) | def clean_float(v) | Remove commas from a float | 4.70752 | 3.807012 | 1.23654 |
if v is None or not str(v).strip():
return None
return int(str(v).replace(',', '')) | def clean_int(v) | Remove commas from a float | 4.896447 | 3.955085 | 1.238013 |
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... | def parse_int(v, header_d) | Parse as an integer, or a subclass of Int. | 7.577396 | 7.176697 | 1.055833 |
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) | Parses unicode.
Note:
unicode types for py2 and str types for py3. | 4.691083 | 4.824493 | 0.972347 |
# 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:
# p... | def _parse_binary(v, header_d) | Parses binary string.
Note:
<str> for py2 and <binary> for py3. | 3.716453 | 3.655321 | 1.016724 |
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... | def parseJuiceHeaders(lines) | Create a JuiceBox from a list of header lines.
@param lines: a list of lines. | 4.242103 | 4.333959 | 0.978805 |
# 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,... | def lookupFunction(self, proto, name, namespace) | Return a callable to invoke when executing the named command. | 10.157286 | 9.5964 | 1.058447 |
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
... | 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
... | 5.224389 | 5.747811 | 0.908935 |
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) | 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. | 5.535243 | 5.462432 | 1.013329 |
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.it... | def sendPacket(self, completeBox) | Send a juice.Box to my peer.
Note: transport.write is never called outside of this method. | 7.103647 | 6.024932 | 1.179042 |
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
... | 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... | 3.399022 | 3.288466 | 1.033619 |
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) | 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(respons... | 1.401605 | 1.535941 | 0.912538 |
# 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-que... | 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. | 6.475407 | 6.493222 | 0.997256 |
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-fts... | 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. | 5.359803 | 5.824848 | 0.920162 |
query = text()
self.backend.library.database.connection.execute(query, **document) | def _index_document(self, document, force=False) | Adds document to the index. | 23.831873 | 21.883631 | 1.089027 |
query = text()
self.backend.library.database.connection.execute(query, vid=vid) | def _delete(self, vid=None) | Deletes given dataset from index.
Args:
vid (str): dataset vid. | 19.393297 | 33.462769 | 0.579548 |
query = text()
result = self.backend.library.database.connection.execute(query, vid=dataset.vid)
return bool(result.fetchall()) | def is_indexed(self, dataset) | Returns True if dataset is already indexed. Otherwise returns False. | 13.259951 | 11.814786 | 1.122318 |
datasets = []
query = text()
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) | Returns list with all indexed datasets. | 10.595819 | 8.891948 | 1.19162 |
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.connec... | 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. | 4.687927 | 4.506448 | 1.040271 |
query =
self.backend.library.database.connection.execute(query) | def reset(self) | Drops index table. | 37.030415 | 26.256956 | 1.410309 |
query = text()
self.backend.library.database.connection.execute(query, identifier=identifier) | def _delete(self, identifier=None) | Deletes given identifier from index.
Args:
identifier (str): identifier of the document to delete. | 19.215656 | 35.851913 | 0.535973 |
query = text()
result = self.backend.library.database.connection.execute(query, identifier=identifier['identifier'])
return bool(result.fetchall()) | def is_indexed(self, identifier) | Returns True if identifier is already indexed. Otherwise returns False. | 12.204452 | 11.459085 | 1.065046 |
identifiers = []
query = text()
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)
r... | def all(self) | Returns list with all indexed identifiers. | 10.008741 | 8.916563 | 1.122489 |
# 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
... | 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. | 5.991848 | 5.796769 | 1.033653 |
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['ke... | 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. | 6.015219 | 6.362894 | 0.945359 |
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(
... | 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. | 2.915265 | 2.935942 | 0.992957 |
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()
sel... | def _index_document(self, document, force=False) | Adds parition document to the index. | 4.491086 | 4.2097 | 1.066842 |
partitions = []
query = text()
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) | Returns list with vids of all indexed partitions. | 11.353806 | 9.258889 | 1.22626 |
'''
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(ti... | 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(hour... | 2.520945 | 1.323707 | 1.904458 |
'''
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(seco... | 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' | 2.26653 | 1.589007 | 1.426382 |
response = utils.checked_api_call(api, 'get_specific', id=search_id)
return response is not None | 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 | 6.665673 | 8.571163 | 0.777686 |
entities = api.get_all(q='name==' + "'" + search_name + "'").content
if entities:
return entities[0].id
return | 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 | 6.697095 | 6.15672 | 1.08777 |
response = utils.checked_api_call(api, 'get_specific', id=entity_id)
if response:
return response.content
return | 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 | 6.669138 | 6.653831 | 1.0023 |
return int(self.state.build_done) - int(self.state.build) | def build_duration(self) | Return the difference between build and build_done states | 16.935575 | 4.350994 | 3.892346 |
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... | def build_duration_pretty(self) | Return the difference between build and build_done states, in a human readable format | 5.929091 | 5.227553 | 1.1342 |
from datetime import datetime
try:
return datetime.fromtimestamp(self.state.build_done)
except TypeError:
# build_done is null
return None | def built_datetime(self) | Return the built time as a datetime object | 6.743461 | 6.029372 | 1.118435 |
from datetime import datetime
try:
return datetime.fromtimestamp(self.state.new)
except TypeError:
return None | def new_datetime(self) | Return the time the bundle was created as a datetime object | 7.471534 | 6.218438 | 1.201513 |
from datetime import datetime
try:
return datetime.fromtimestamp(self.state.lasttime)
except TypeError:
return None | def last_datetime(self) | Return the time of the last operation on the bundle as a datetime object | 7.09253 | 5.250753 | 1.350764 |
self._items[session.session_id] = session
if session.expiry is not None:
self._queue.push(session) | def add(self, session) | Add session to the container.
@param session: Session object | 7.655098 | 7.984575 | 0.958736 |
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 ti... | 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) | 3.562596 | 3.528317 | 1.009715 |
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']
... | 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. | 1.986902 | 2.004967 | 0.99099 |
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="") | List all ProductVersions | 3.66163 | 3.93186 | 0.931272 |
data = create_product_version_raw(product_id, version, **kwargs)
if data:
return utils.format_json(data) | 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 ... | 4.125454 | 6.649808 | 0.620387 |
content = update_product_version_raw(id, **kwargs)
if content:
return utils.format_json(content) | def update_product_version(id, **kwargs) | Update the ProductVersion with ID id with new values. | 5.894475 | 6.307751 | 0.934481 |
'''
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) | Method returning data passed to template.
Subclasses can override it. | 8.688194 | 4.143678 | 2.096735 |
'''
Renders widget to template
'''
data = self.prepare_data()
if self.field.readable:
return self.env.template.render(self.template, **data)
return '' | def render(self) | Renders widget to template | 9.010975 | 6.088786 | 1.47993 |
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_c... | 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 | 2.429741 | 2.589193 | 0.938416 |
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._... | 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 | 2.075072 | 2.231211 | 0.93002 |
# 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
rea... | 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. | 5.86387 | 4.983106 | 1.17675 |
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:
#... | 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 ... | 6.496426 | 4.87669 | 1.332138 |
# 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 = []
# ... | 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}. | 3.876547 | 3.871528 | 1.001296 |
# 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) | 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. | 10.792969 | 8.282361 | 1.303127 |
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, *... | 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. | 2.938946 | 2.884735 | 1.018792 |
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:
# asser... | 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
Return... | 1.944035 | 1.970055 | 0.986792 |
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) | 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 contain... | 2.700552 | 2.801989 | 0.963798 |
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) | 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
... | 3.849055 | 5.601395 | 0.68716 |
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) | 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, optiona... | 3.701663 | 5.840542 | 0.633788 |
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:
... | def center_genes(self, use_median=False, inplace=False) | Center the expression of each gene (row). | 2.395447 | 2.344698 | 1.021644 |
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) | Standardize the expression of each gene (row). | 4.882895 | 4.668601 | 1.045901 |
return self.drop(set(self.genes) - set(gene_names),
inplace=inplace) | 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
-------
ExpMat... | 7.095026 | 9.744692 | 0.728091 |
C = np.corrcoef(self.X.T)
corr_matrix = ExpMatrix(genes=self.samples, samples=self.samples, X=C)
return corr_matrix | def sample_correlations(self) | Returns an `ExpMatrix` containing all pairwise sample correlations.
Returns
-------
`ExpMatrix`
The sample correlation matrix. | 6.951663 | 5.437445 | 1.27848 |
# 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 converti... | 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 th... | 3.918429 | 4.02967 | 0.972395 |
#if six.PY2:
# sep = sep.encode('UTF-8')
self.to_csv(
file_path, sep=sep, float_format='%.5f', mode='w',
encoding=encoding, quoting=csv.QUOTE_NONE
)
_LOGGER.info('Wrote %d x %d expression matrix to "%s".',
self.p, self.n, ... | def write_tsv(self, file_path: str, encoding: str = 'UTF-8',
sep: str = '\t') | Write expression matrix to a tab-delimited text file.
Parameters
----------
file_path: str
The path of the output file.
encoding: str, optional
The file encoding. ("UTF-8")
Returns
-------
None | 4.279071 | 3.967585 | 1.078508 |
coo = sparse.coo_matrix(self.X)
data = OrderedDict([(0, coo.row+1), (1, coo.col+1), (2, coo.data)])
df = pd.DataFrame(data, columns=data.keys())
with open(file_path, 'w') as ofh:
ofh.write('%%MatrixMarket matrix coordinate real general\n')
ofh.write('%%%... | def write_sparse(self, file_path: str) | Write a sparse representation to a tab-delimited text file.
TODO: docstring | 2.519952 | 2.363195 | 1.066333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.