_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q1700 | DataGenerator.from_config | train | def from_config(self, k, v):
"""
Hook method that allows converting values from the dictionary.
:param k: the key in the dictionary
:type k: str
:param v: the value
:type v: object
:return: the potentially parsed value
:rtype: object
"""
i... | python | {
"resource": ""
} |
q1701 | SimpleExperiment.configure_splitevaluator | train | def configure_splitevaluator(self):
"""
Configures and returns the SplitEvaluator and Classifier instance as tuple.
:return: evaluator and classifier
:rtype: tuple
"""
if self.classification:
speval = javabridge.make_instance("weka/experiment/ClassifierSplitE... | python | {
"resource": ""
} |
q1702 | SimpleExperiment.setup | train | def setup(self):
"""
Initializes the experiment.
"""
# basic options
javabridge.call(
self.jobject, "setPropertyArray", "(Ljava/lang/Object;)V",
javabridge.get_env().make_object_array(0, javabridge.get_env().find_class("weka/classifiers/Classifier")))
... | python | {
"resource": ""
} |
q1703 | SimpleExperiment.run | train | def run(self):
"""
Executes the experiment.
"""
logger.info("Initializing...")
javabridge.call(self.jobject, "initialize", "()V")
logger.info("Running...")
javabridge.call(self.jobject, "runExperiment", "()V")
logger.info("Finished...")
javabridge.... | python | {
"resource": ""
} |
q1704 | SimpleExperiment.load | train | def load(cls, filename):
"""
Loads the experiment from disk.
:param filename: the filename of the experiment to load
:type filename: str
:return: the experiment
:rtype: Experiment
"""
jobject = javabridge.static_call(
"weka/experiment/Experime... | python | {
"resource": ""
} |
q1705 | SimpleRandomSplitExperiment.configure_resultproducer | train | def configure_resultproducer(self):
"""
Configures and returns the ResultProducer and PropertyPath as tuple.
:return: producer and property path
:rtype: tuple
"""
rproducer = javabridge.make_instance("weka/experiment/RandomSplitResultProducer", "()V")
javabridge.... | python | {
"resource": ""
} |
q1706 | ResultMatrix.set_row_name | train | def set_row_name(self, index, name):
"""
Sets the row name.
:param index: the 0-based row index
:type index: int
:param name: the name of the row
:type name: str
"""
javabridge.call(self.jobject, "setRowName", "(ILjava/lang/String;)V", index, name) | python | {
"resource": ""
} |
q1707 | ResultMatrix.set_col_name | train | def set_col_name(self, index, name):
"""
Sets the column name.
:param index: the 0-based row index
:type index: int
:param name: the name of the column
:type name: str
"""
javabridge.call(self.jobject, "setColName", "(ILjava/lang/String;)V", index, name) | python | {
"resource": ""
} |
q1708 | RCRequest.validate | train | def validate(self):
"""Checks that at least required params exist"""
required = ['token', 'content']
valid_data = {
'exp_record': (['type', 'format'], 'record',
'Exporting record but content is not record'),
'imp_record': (['type', 'overwriteBehavior', 'da... | python | {
"resource": ""
} |
q1709 | RCRequest.execute | train | def execute(self, **kwargs):
"""Execute the API request and return data
Parameters
----------
kwargs :
passed to requests.post()
Returns
-------
response : list, str
data object from JSON decoding process if format=='json',
el... | python | {
"resource": ""
} |
q1710 | RCRequest.get_content | train | def get_content(self, r):
"""Abstraction for grabbing content from a returned response"""
if self.type == 'exp_file':
# don't use the decoded r.text
return r.content
elif self.type == 'version':
return r.content
else:
if self.fmt == 'json':... | python | {
"resource": ""
} |
q1711 | RCRequest.raise_for_status | train | def raise_for_status(self, r):
"""Given a response, raise for bad status for certain actions
Some redcap api methods don't return error messages
that the user could test for or otherwise use. Therefore, we
need to do the testing ourself
Raising for everything wouldn't let the u... | python | {
"resource": ""
} |
q1712 | Project.__basepl | train | def __basepl(self, content, rec_type='flat', format='json'):
"""Return a dictionary which can be used as is or added to for
payloads"""
d = {'token': self.token, 'content': content, 'format': format}
if content not in ['metadata', 'file']:
d['type'] = rec_type
return ... | python | {
"resource": ""
} |
q1713 | Project.filter_metadata | train | def filter_metadata(self, key):
"""
Return a list of values for the metadata key from each field
of the project's metadata.
Parameters
----------
key: str
A known key in the metadata structure
Returns
-------
filtered :
at... | python | {
"resource": ""
} |
q1714 | Project.export_fem | train | def export_fem(self, arms=None, format='json', df_kwargs=None):
"""
Export the project's form to event mapping
Parameters
----------
arms : list
Limit exported form event mappings to these arm numbers
format : (``'json'``), ``'csv'``, ``'xml'``
Re... | python | {
"resource": ""
} |
q1715 | Project.export_metadata | train | def export_metadata(self, fields=None, forms=None, format='json',
df_kwargs=None):
"""
Export the project's metadata
Parameters
----------
fields : list
Limit exported metadata to these fields
forms : list
Limit exported metadata to th... | python | {
"resource": ""
} |
q1716 | Project.export_records | train | def export_records(self, records=None, fields=None, forms=None,
events=None, raw_or_label='raw', event_name='label',
format='json', export_survey_fields=False,
export_data_access_groups=False, df_kwargs=None,
export_checkbox_labels=False, filter_logic=None):
"""
Export data from the REDC... | python | {
"resource": ""
} |
q1717 | Project.__meta_metadata | train | def __meta_metadata(self, field, key):
"""Return the value for key for the field in the metadata"""
mf = ''
try:
mf = str([f[key] for f in self.metadata
if f['field_name'] == field][0])
except IndexError:
print("%s not in metadata field:%s" % ... | python | {
"resource": ""
} |
q1718 | Project.filter | train | def filter(self, query, output_fields=None):
"""Query the database and return subject information for those
who match the query logic
Parameters
----------
query: Query or QueryGroup
Query(Group) object to process
output_fields: list
The fields de... | python | {
"resource": ""
} |
q1719 | Project.names_labels | train | def names_labels(self, do_print=False):
"""Simple helper function to get all field names and labels """
if do_print:
for name, label in zip(self.field_names, self.field_labels):
print('%s --> %s' % (str(name), str(label)))
return self.field_names, self.field_labels | python | {
"resource": ""
} |
q1720 | Project.import_records | train | def import_records(self, to_import, overwrite='normal', format='json',
return_format='json', return_content='count',
date_format='YMD', force_auto_number=False):
"""
Import data into the RedCap Project
Parameters
----------
to_import : array of dicts, csv/xml str... | python | {
"resource": ""
} |
q1721 | Project.export_file | train | def export_file(self, record, field, event=None, return_format='json'):
"""
Export the contents of a file stored for a particular record
Notes
-----
Unlike other export methods, this works on a single record.
Parameters
----------
record : str
... | python | {
"resource": ""
} |
q1722 | Project.import_file | train | def import_file(self, record, field, fname, fobj, event=None,
return_format='json'):
"""
Import the contents of a file represented by fobj to a
particular records field
Parameters
----------
record : str
record ID
field : str
f... | python | {
"resource": ""
} |
q1723 | Project.delete_file | train | def delete_file(self, record, field, return_format='json', event=None):
"""
Delete a file from REDCap
Notes
-----
There is no undo button to this.
Parameters
----------
record : str
record ID
field : str
field name
... | python | {
"resource": ""
} |
q1724 | Project._check_file_field | train | def _check_file_field(self, field):
"""Check that field exists and is a file field"""
is_field = field in self.field_names
is_file = self.__meta_metadata(field, 'field_type') == 'file'
if not (is_field and is_file):
msg = "'%s' is not a field or not a 'file' field" % field
... | python | {
"resource": ""
} |
q1725 | Project.export_users | train | def export_users(self, format='json'):
"""
Export the users of the Project
Notes
-----
Each user will have the following keys:
* ``'firstname'`` : User's first name
* ``'lastname'`` : User's last name
* ``'email'`` : Email address
... | python | {
"resource": ""
} |
q1726 | Project.export_survey_participant_list | train | def export_survey_participant_list(self, instrument, event=None, format='json'):
"""
Export the Survey Participant List
Notes
-----
The passed instrument must be set up as a survey instrument.
Parameters
----------
instrument: str
Name of ins... | python | {
"resource": ""
} |
q1727 | create_new_username | train | def create_new_username(ip, devicetype=None, timeout=_DEFAULT_TIMEOUT):
"""Interactive helper function to generate a new anonymous username.
Args:
ip: ip address of the bridge
devicetype (optional): devicetype to register with the bridge. If
unprovided, generates a device type based... | python | {
"resource": ""
} |
q1728 | GordonRouter.run | train | async def run(self):
"""Entrypoint to route messages between plugins."""
logging.info('Starting message router...')
coroutines = set()
while True:
coro = self._poll_channel()
coroutines.add(coro)
_, coroutines = await asyncio.wait(coroutines, timeout=... | python | {
"resource": ""
} |
q1729 | shutdown | train | async def shutdown(sig, loop):
"""Gracefully cancel current tasks when app receives a shutdown signal."""
logging.info(f'Received exit signal {sig.name}...')
tasks = [task for task in asyncio.Task.all_tasks() if task is not
asyncio.tasks.Task.current_task()]
for task in tasks:
logg... | python | {
"resource": ""
} |
q1730 | _deep_merge_dict | train | def _deep_merge_dict(a, b):
"""Additively merge right side dict into left side dict."""
for k, v in b.items():
if k in a and isinstance(a[k], dict) and isinstance(v, dict):
_deep_merge_dict(a[k], v)
else:
a[k] = v | python | {
"resource": ""
} |
q1731 | load_plugins | train | def load_plugins(config, plugin_kwargs):
"""
Discover and instantiate plugins.
Args:
config (dict): loaded configuration for the Gordon service.
plugin_kwargs (dict): keyword arguments to give to plugins
during instantiation.
Returns:
Tuple of 3 lists: list of names ... | python | {
"resource": ""
} |
q1732 | UDPClientProtocol.connection_made | train | def connection_made(self, transport):
"""Create connection, use to send message and close.
Args:
transport (asyncio.DatagramTransport): Transport used for sending.
"""
self.transport = transport
self.transport.sendto(self.message)
self.transport.close() | python | {
"resource": ""
} |
q1733 | UDPClient.send | train | async def send(self, metric):
"""Transform metric to JSON bytestring and send to server.
Args:
metric (dict): Complete metric to send as JSON.
"""
message = json.dumps(metric).encode('utf-8')
await self.loop.create_datagram_endpoint(
lambda: UDPClientProt... | python | {
"resource": ""
} |
q1734 | RecordChecker.check_record | train | async def check_record(self, record, timeout=60):
"""Measures the time for a DNS record to become available.
Query a provided DNS server multiple times until the reply matches the
information in the record or until timeout is reached.
Args:
record (dict): DNS record as a di... | python | {
"resource": ""
} |
q1735 | RecordChecker._check_resolver_ans | train | async def _check_resolver_ans(
self, dns_answer_list, record_name,
record_data_list, record_ttl, record_type_code):
"""Check if resolver answer is equal to record data.
Args:
dns_answer_list (list): DNS answer list contains record objects.
record_name (st... | python | {
"resource": ""
} |
q1736 | LoggerAdapter.log | train | def log(self, metric):
"""Format and output metric.
Args:
metric (dict): Complete metric.
"""
message = self.LOGFMT.format(**metric)
if metric['context']:
message += ' context: {context}'.format(context=metric['context'])
self._logger.log(self.lev... | python | {
"resource": ""
} |
q1737 | Atbash.encipher | train | def encipher(self,string,keep_punct=False):
"""Encipher string using Atbash cipher.
Example::
ciphertext = Atbash().encipher(plaintext)
:param string: The string to encipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed... | python | {
"resource": ""
} |
q1738 | PolybiusSquare.encipher | train | def encipher(self,string):
"""Encipher string using Polybius square cipher according to initialised key.
Example::
ciphertext = Polybius('APCZWRLFBDKOTYUQGENHXMIVS',5,'MKSBU').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string. ... | python | {
"resource": ""
} |
q1739 | PolybiusSquare.decipher | train | def decipher(self,string):
"""Decipher string using Polybius square cipher according to initialised key.
Example::
plaintext = Polybius('APCZWRLFBDKOTYUQGENHXMIVS',5,'MKSBU').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered string. ... | python | {
"resource": ""
} |
q1740 | ADFGVX.decipher | train | def decipher(self,string):
"""Decipher string using ADFGVX cipher according to initialised key information. Punctuation and whitespace
are removed from the input.
Example::
plaintext = ADFGVX('ph0qg64mea1yl2nofdxkr3cvs5zw7bj9uti8','HELLO').decipher(ciphertext)
... | python | {
"resource": ""
} |
q1741 | Enigma.encipher | train | def encipher(self,string):
"""Encipher string using Enigma M3 cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Enigma(settings=('A','A','A'),rotors=(1,2,3),reflector='B',
ringstellung=('F','V'... | python | {
"resource": ""
} |
q1742 | ic | train | def ic(ctext):
''' takes ciphertext, calculates index of coincidence.'''
counts = ngram_count(ctext,N=1)
icval = 0
for k in counts.keys():
icval += counts[k]*(counts[k]-1)
icval /= (len(ctext)*(len(ctext)-1))
return icval | python | {
"resource": ""
} |
q1743 | restore_punctuation | train | def restore_punctuation(original,modified):
''' If punctuation was accidently removed, use this function to restore it.
requires the orignial string with punctuation. '''
ret = ''
count = 0
try:
for c in original:
if c.isalpha():
ret+=modified[count]
... | python | {
"resource": ""
} |
q1744 | Playfair.encipher | train | def encipher(self, string):
"""Encipher string using Playfair cipher according to initialised key. Punctuation and whitespace
are removed from the input. If the input plaintext is not an even number of characters, an 'X' will be appended.
Example::
ciphertext = Playfair(key='zgptfo... | python | {
"resource": ""
} |
q1745 | Playfair.decipher | train | def decipher(self, string):
"""Decipher string using Playfair cipher according to initialised key. Punctuation and whitespace
are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an 'X' will be appended.
... | python | {
"resource": ""
} |
q1746 | Delastelle.encipher | train | def encipher(self,string):
"""Encipher string using Delastelle cipher according to initialised key.
Example::
ciphertext = Delastelle('APCZ WRLFBDKOTYUQGENHXMIVS').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string. The cipherte... | python | {
"resource": ""
} |
q1747 | Delastelle.decipher | train | def decipher(self,string):
"""Decipher string using Delastelle cipher according to initialised key.
Example::
plaintext = Delastelle('APCZ WRLFBDKOTYUQGENHXMIVS').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered string. The plaintex... | python | {
"resource": ""
} |
q1748 | Foursquare.encipher | train | def encipher(self,string):
"""Encipher string using Foursquare cipher according to initialised key. Punctuation and whitespace
are removed from the input. If the input plaintext is not an even number of characters, an 'X' will be appended.
Example::
ciphertext = Foursquare(key1='zg... | python | {
"resource": ""
} |
q1749 | Foursquare.decipher | train | def decipher(self,string):
"""Decipher string using Foursquare cipher according to initialised key. Punctuation and whitespace
are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an 'X' will be appended.
... | python | {
"resource": ""
} |
q1750 | Rot13.encipher | train | def encipher(self,string,keep_punct=False):
r"""Encipher string using rot13 cipher.
Example::
ciphertext = Rot13().encipher(plaintext)
:param string: The string to encipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed.... | python | {
"resource": ""
} |
q1751 | Porta.encipher | train | def encipher(self,string):
"""Encipher string using Porta cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Porta('HELLO').encipher(plaintext)
:param string: The string to encipher.
:retur... | python | {
"resource": ""
} |
q1752 | M209.encipher | train | def encipher(self,message):
"""Encipher string using M209 cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example (continuing from the example above)::
ciphertext = m.encipher(plaintext)
:param string: The str... | python | {
"resource": ""
} |
q1753 | FracMorse.encipher | train | def encipher(self,string):
"""Encipher string using FracMorse cipher according to initialised key.
Example::
ciphertext = FracMorse('ROUNDTABLECFGHIJKMPQSVWXYZ').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string.
""" ... | python | {
"resource": ""
} |
q1754 | FracMorse.decipher | train | def decipher(self,string):
"""Decipher string using FracMorse cipher according to initialised key.
Example::
plaintext = FracMorse('ROUNDTABLECFGHIJKMPQSVWXYZ').decipher(ciphertext)
:param string: The string to decipher.
:returns: The enciphered string.
""" ... | python | {
"resource": ""
} |
q1755 | ColTrans.encipher | train | def encipher(self,string):
"""Encipher string using Columnar Transposition cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = ColTrans('GERMAN').encipher(plaintext)
:param string: The string to enc... | python | {
"resource": ""
} |
q1756 | ColTrans.decipher | train | def decipher(self,string):
'''Decipher string using Columnar Transposition cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
plaintext = ColTrans('GERMAN').decipher(ciphertext)
:param string: The string to decipher.
... | python | {
"resource": ""
} |
q1757 | Railfence.encipher | train | def encipher(self,string,keep_punct=False):
"""Encipher string using Railfence cipher according to initialised key.
Example::
ciphertext = Railfence(3).encipher(plaintext)
:param string: The string to encipher.
:param keep_punct: if true, punctuation and spaci... | python | {
"resource": ""
} |
q1758 | Railfence.decipher | train | def decipher(self,string,keep_punct=False):
"""Decipher string using Railfence cipher according to initialised key.
Example::
plaintext = Railfence(3).decipher(ciphertext)
:param string: The string to decipher.
:param keep_punct: if true, punctuation and spaci... | python | {
"resource": ""
} |
q1759 | Affine.decipher | train | def decipher(self,string,keep_punct=False):
"""Decipher string using affine cipher according to initialised key.
Example::
plaintext = Affine(a,b).decipher(ciphertext)
:param string: The string to decipher.
:param keep_punct: if true, punctuation and spacing a... | python | {
"resource": ""
} |
q1760 | Autokey.encipher | train | def encipher(self,string):
"""Encipher string using Autokey cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Autokey('HELLO').encipher(plaintext)
:param string: The string to encipher.
:r... | python | {
"resource": ""
} |
q1761 | Bifid.encipher | train | def encipher(self,string):
"""Encipher string using Bifid cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Bifid('phqgmeaylnofdxkrcvszwbuti',5).encipher(plaintext)
:param string: The string to en... | python | {
"resource": ""
} |
q1762 | Bifid.decipher | train | def decipher(self,string):
"""Decipher string using Bifid cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
plaintext = Bifid('phqgmeaylnofdxkrcvszwbuti',5).decipher(ciphertext)
:param string: The string to decipher.... | python | {
"resource": ""
} |
q1763 | SimpleSubstitution.decipher | train | def decipher(self,string,keep_punct=False):
"""Decipher string using Simple Substitution cipher according to initialised key.
Example::
plaintext = SimpleSubstitution('AJPCZWRLFBDKOTYUQGENHXMIVS').decipher(ciphertext)
:param string: The string to decipher.
:param keep... | python | {
"resource": ""
} |
q1764 | kron | train | def kron(a, b):
"""Kronecker product of two TT-matrices or two TT-vectors"""
if hasattr(a, '__kron__'):
return a.__kron__(b)
if a is None:
return b
else:
raise ValueError(
'Kron is waiting for two TT-vectors or two TT-matrices') | python | {
"resource": ""
} |
q1765 | dot | train | def dot(a, b):
"""Dot product of two TT-matrices or two TT-vectors"""
if hasattr(a, '__dot__'):
return a.__dot__(b)
if a is None:
return b
else:
raise ValueError(
'Dot is waiting for two TT-vectors or two TT- matrices') | python | {
"resource": ""
} |
q1766 | mkron | train | def mkron(a, *args):
"""Kronecker product of all the arguments"""
if not isinstance(a, list):
a = [a]
a = list(a) # copy list
for i in args:
if isinstance(i, list):
a.extend(i)
else:
a.append(i)
c = _vector.vector()
c.d = 0
c.n = _np.array([]... | python | {
"resource": ""
} |
q1767 | concatenate | train | def concatenate(*args):
"""Concatenates given TT-vectors.
For two tensors :math:`X(i_1,\\ldots,i_d),Y(i_1,\\ldots,i_d)` returns :math:`(d+1)`-dimensional
tensor :math:`Z(i_0,i_1,\\ldots,i_d)`, :math:`i_0=\\overline{0,1}`, such that
.. math::
Z(0, i_1, \\ldots, i_d) = X(i_1, \\ldots, i_d),
... | python | {
"resource": ""
} |
q1768 | sum | train | def sum(a, axis=-1):
"""Sum TT-vector over specified axes"""
d = a.d
crs = _vector.vector.to_list(a.tt if isinstance(a, _matrix.matrix) else a)
if axis < 0:
axis = range(a.d)
elif isinstance(axis, int):
axis = [axis]
axis = list(axis)[::-1]
for ax in axis:
crs[ax] = _... | python | {
"resource": ""
} |
q1769 | ones | train | def ones(n, d=None):
""" Creates a TT-vector of all ones"""
c = _vector.vector()
if d is None:
c.n = _np.array(n, dtype=_np.int32)
c.d = c.n.size
else:
c.n = _np.array([n] * d, dtype=_np.int32)
c.d = d
c.r = _np.ones((c.d + 1,), dtype=_np.int32)
c.get_ps()
c.c... | python | {
"resource": ""
} |
q1770 | rand | train | def rand(n, d=None, r=2, samplefunc=_np.random.randn):
"""Generate a random d-dimensional TT-vector with ranks ``r``.
Distribution to sample cores is provided by the samplefunc.
Default is to sample from normal distribution.
"""
n0 = _np.asanyarray(n, dtype=_np.int32)
r0 = _np.asanyarray(r, dtyp... | python | {
"resource": ""
} |
q1771 | eye | train | def eye(n, d=None):
""" Creates an identity TT-matrix"""
c = _matrix.matrix()
c.tt = _vector.vector()
if d is None:
n0 = _np.asanyarray(n, dtype=_np.int32)
c.tt.d = n0.size
else:
n0 = _np.asanyarray([n] * d, dtype=_np.int32)
c.tt.d = d
c.n = n0.copy()
c.m = n0... | python | {
"resource": ""
} |
q1772 | cores_orthogonalization_step | train | def cores_orthogonalization_step(coresX, dim, left_to_right=True):
"""TT-Tensor X orthogonalization step.
The function can change the shape of some cores.
"""
cc = coresX[dim]
r1, n, r2 = cc.shape
if left_to_right:
# Left to right orthogonalization step.
assert(0 <= dim < len(co... | python | {
"resource": ""
} |
q1773 | unfolding | train | def unfolding(tens, i):
"""Compute the i-th unfolding of a tensor."""
return reshape(tens.full(), (np.prod(tens.n[0:(i+1)]), -1)) | python | {
"resource": ""
} |
q1774 | gcd | train | def gcd(a, b):
'''Greatest common divider'''
f = _np.frompyfunc(_fractions.gcd, 2, 1)
return f(a, b) | python | {
"resource": ""
} |
q1775 | ksl | train | def ksl(A, y0, tau, verb=1, scheme='symm', space=8, rmax=2000, use_normest=1):
""" Dynamical tensor-train approximation based on projector splitting
This function performs one step of dynamical tensor-train approximation
for the equation
.. math ::
\\frac{dy}{dt} = A y, \\quad y... | python | {
"resource": ""
} |
q1776 | diag_ksl | train | def diag_ksl(A, y0, tau, verb=1, scheme='symm', space=8, rmax=2000):
""" Dynamical tensor-train approximation based on projector splitting
This function performs one step of dynamical tensor-train approximation with diagonal matrix, i.e. it solves the equation
for the equation
.. math ::
... | python | {
"resource": ""
} |
q1777 | matrix.T | train | def T(self):
"""Transposed TT-matrix"""
mycrs = matrix.to_list(self)
trans_crs = []
for cr in mycrs:
trans_crs.append(_np.transpose(cr, [0, 2, 1, 3]))
return matrix.from_list(trans_crs) | python | {
"resource": ""
} |
q1778 | matrix.real | train | def real(self):
"""Return real part of a matrix."""
return matrix(self.tt.real(), n=self.n, m=self.m) | python | {
"resource": ""
} |
q1779 | matrix.imag | train | def imag(self):
"""Return imaginary part of a matrix."""
return matrix(self.tt.imag(), n=self.n, m=self.m) | python | {
"resource": ""
} |
q1780 | matrix.c2r | train | def c2r(self):
"""Get real matrix from complex one suitable for solving complex linear system with real solver.
For matrix :math:`M(i_1,j_1,\\ldots,i_d,j_d) = \\Re M + i\\Im M` returns (d+1)-dimensional matrix
:math:`\\tilde{M}(i_1,j_1,\\ldots,i_d,j_d,i_{d+1},j_{d+1})` of form
:math:`\\... | python | {
"resource": ""
} |
q1781 | matrix.round | train | def round(self, eps=1e-14, rmax=100000):
""" Computes an approximation to a
TT-matrix in with accuracy EPS
"""
c = matrix()
c.tt = self.tt.round(eps, rmax)
c.n = self.n.copy()
c.m = self.m.copy()
return c | python | {
"resource": ""
} |
q1782 | matrix.copy | train | def copy(self):
""" Creates a copy of the TT-matrix """
c = matrix()
c.tt = self.tt.copy()
c.n = self.n.copy()
c.m = self.m.copy()
return c | python | {
"resource": ""
} |
q1783 | matrix.full | train | def full(self):
""" Transforms a TT-matrix into a full matrix"""
N = self.n.prod()
M = self.m.prod()
a = self.tt.full()
d = self.tt.d
sz = _np.vstack((self.n, self.m)).flatten('F')
a = a.reshape(sz, order='F')
# Design a permutation
prm = _np.arang... | python | {
"resource": ""
} |
q1784 | vector.from_list | train | def from_list(a, order='F'):
"""Generate TT-vectorr object from given TT cores.
:param a: List of TT cores.
:type a: list
:returns: vector -- TT-vector constructed from the given cores.
"""
d = len(a) # Number of cores
res = vector()
n = _np.zeros(d, dt... | python | {
"resource": ""
} |
q1785 | vector.erank | train | def erank(self):
""" Effective rank of the TT-vector """
r = self.r
n = self.n
d = self.d
if d <= 1:
er = 0e0
else:
sz = _np.dot(n * r[0:d], r[1:])
if sz == 0:
er = 0e0
else:
b = r[0] * n[0] +... | python | {
"resource": ""
} |
q1786 | vector.rmean | train | def rmean(self):
""" Calculates the mean rank of a TT-vector."""
if not _np.all(self.n):
return 0
# Solving quadratic equation ar^2 + br + c = 0;
a = _np.sum(self.n[1:-1])
b = self.n[0] + self.n[-1]
c = - _np.sum(self.n * self.r[1:] * self.r[:-1])
D = ... | python | {
"resource": ""
} |
q1787 | eigb | train | def eigb(A, y0, eps, rmax=150, nswp=20, max_full_size=1000, verb=1):
""" Approximate computation of minimal eigenvalues in tensor train format
This function uses alternating least-squares algorithm for the computation of several
minimal eigenvalues. If you want maximal eigenvalues, just send -A to the funct... | python | {
"resource": ""
} |
q1788 | encode_for_locale | train | def encode_for_locale(s):
"""
Encode text items for system locale. If encoding fails, fall back to ASCII.
"""
try:
return s.encode(LOCALE_ENCODING, 'ignore')
except (AttributeError, UnicodeDecodeError):
return s.decode('ascii', 'ignore').encode(LOCALE_ENCODING) | python | {
"resource": ""
} |
q1789 | fib | train | def fib(n):
"""Terrible Fibonacci number generator."""
v = n.value
return v if v < 2 else fib2(PythonInt(v-1)) + fib(PythonInt(v-2)) | python | {
"resource": ""
} |
q1790 | Brain.format_message | train | def format_message(self, msg, botreply=False):
"""Format a user's message for safe processing.
This runs substitutions on the message and strips out any remaining
symbols (depending on UTF-8 mode).
:param str msg: The user's message.
:param bool botreply: Whether this formattin... | python | {
"resource": ""
} |
q1791 | Brain.do_expand_array | train | def do_expand_array(self, array_name, depth=0):
"""Do recurrent array expansion, returning a set of keywords.
Exception is thrown when there are cyclical dependencies between
arrays or if the ``@array`` name references an undefined array.
:param str array_name: The name of the array to... | python | {
"resource": ""
} |
q1792 | Brain.expand_array | train | def expand_array(self, array_name):
"""Expand variables and return a set of keywords.
:param str array_name: The name of the array to expand.
:return list: The final array contents.
Warning is issued when exceptions occur."""
ret = self.master._array[array_name] if array_name ... | python | {
"resource": ""
} |
q1793 | Brain.substitute | train | def substitute(self, msg, kind):
"""Run a kind of substitution on a message.
:param str msg: The message to run substitutions against.
:param str kind: The kind of substitution to run,
one of ``subs`` or ``person``.
"""
# Safety checking.
if 'lists' not in s... | python | {
"resource": ""
} |
q1794 | PyRiveObjects.load | train | def load(self, name, code):
"""Prepare a Python code object given by the RiveScript interpreter.
:param str name: The name of the Python object macro.
:param []str code: The Python source code for the object macro.
"""
# We need to make a dynamic Python method.
source = ... | python | {
"resource": ""
} |
q1795 | PyRiveObjects.call | train | def call(self, rs, name, user, fields):
"""Invoke a previously loaded object.
:param RiveScript rs: the parent RiveScript instance.
:param str name: The name of the object macro to be called.
:param str user: The user ID invoking the object macro.
:param []str fields: Array of w... | python | {
"resource": ""
} |
q1796 | get_topic_triggers | train | def get_topic_triggers(rs, topic, thats, depth=0, inheritance=0, inherited=False):
"""Recursively scan a topic and return a list of all triggers.
Arguments:
rs (RiveScript): A reference to the parent RiveScript instance.
topic (str): The original topic name.
thats (bool): Are we getting... | python | {
"resource": ""
} |
q1797 | word_count | train | def word_count(trigger, all=False):
"""Count the words that aren't wildcards or options in a trigger.
:param str trigger: The trigger to count words for.
:param bool all: Count purely based on whitespace separators, or
consider wildcards not to be their own words.
:return int: The word count."... | python | {
"resource": ""
} |
q1798 | PerlObject.load | train | def load(self, name, code):
"""Prepare a Perl code object given by the RS interpreter."""
source = "\n".join(code)
self._objects[name] = source | python | {
"resource": ""
} |
q1799 | hello_rivescript | train | def hello_rivescript():
"""Receive an inbound SMS and send a reply from RiveScript."""
from_number = request.values.get("From", "unknown")
message = request.values.get("Body")
reply = "(Internal error)"
# Get a reply from RiveScript.
if message:
reply = bot.reply(from_number,... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.