_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
"""
if k == "setup":
return from_commandline(v, classname=to_commandline(datagen.DataGenerator()))
return super(DataGenerator, self).from_config(k, v)
|
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/ClassifierSplitEvaluator", "()V")
else:
speval = javabridge.make_instance("weka/experiment/RegressionSplitEvaluator", "()V")
classifier = javabridge.call(speval, "getClassifier", "()Lweka/classifiers/Classifier;")
return speval, classifier
|
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")))
javabridge.call(
self.jobject, "setUsePropertyIterator", "(Z)V", True)
javabridge.call(
self.jobject, "setRunLower", "(I)V", 1)
javabridge.call(
self.jobject, "setRunUpper", "(I)V", self.runs)
# setup result producer
rproducer, prop_path = self.configure_resultproducer()
javabridge.call(
self.jobject, "setResultProducer", "(Lweka/experiment/ResultProducer;)V", rproducer)
javabridge.call(
self.jobject, "setPropertyPath", "([Lweka/experiment/PropertyNode;)V", prop_path)
# classifiers
classifiers = javabridge.get_env().make_object_array(
len(self.classifiers), javabridge.get_env().find_class("weka/classifiers/Classifier"))
for i, classifier in enumerate(self.classifiers):
if type(classifier) is Classifier:
javabridge.get_env().set_object_array_element(
classifiers, i, classifier.jobject)
else:
javabridge.get_env().set_object_array_element(
classifiers, i, from_commandline(classifier).jobject)
javabridge.call(
self.jobject, "setPropertyArray", "(Ljava/lang/Object;)V",
classifiers)
# datasets
datasets = javabridge.make_instance("javax/swing/DefaultListModel", "()V")
for dataset in self.datasets:
f = javabridge.make_instance("java/io/File", "(Ljava/lang/String;)V", dataset)
javabridge.call(datasets, "addElement", "(Ljava/lang/Object;)V", f)
javabridge.call(
self.jobject, "setDatasets", "(Ljavax/swing/DefaultListModel;)V", datasets)
# output file
if str(self.result).lower().endswith(".arff"):
rlistener = javabridge.make_instance("weka/experiment/InstancesResultListener", "()V")
elif str(self.result).lower().endswith(".csv"):
rlistener = javabridge.make_instance("weka/experiment/CSVResultListener", "()V")
else:
raise Exception("Unhandled output format for results: " + self.result)
rfile = javabridge.make_instance("java/io/File", "(Ljava/lang/String;)V", self.result)
javabridge.call(
rlistener, "setOutputFile", "(Ljava/io/File;)V", rfile)
javabridge.call(
self.jobject, "setResultListener", "(Lweka/experiment/ResultListener;)V", rlistener)
|
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.call(self.jobject, "postProcess", "()V")
|
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/Experiment", "read", "(Ljava/lang/String;)Lweka/experiment/Experiment;",
filename)
return Experiment(jobject=jobject)
|
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.call(rproducer, "setRandomizeData", "(Z)V", not self.preserve_order)
javabridge.call(rproducer, "setTrainPercent", "(D)V", self.percentage)
speval, classifier = self.configure_splitevaluator()
javabridge.call(rproducer, "setSplitEvaluator", "(Lweka/experiment/SplitEvaluator;)V", speval)
prop_path = javabridge.get_env().make_object_array(
2, javabridge.get_env().find_class("weka/experiment/PropertyNode"))
cls = javabridge.get_env().find_class("weka/experiment/RandomSplitResultProducer")
desc = javabridge.make_instance(
"java/beans/PropertyDescriptor", "(Ljava/lang/String;Ljava/lang/Class;)V", "splitEvaluator", cls)
node = javabridge.make_instance(
"weka/experiment/PropertyNode", "(Ljava/lang/Object;Ljava/beans/PropertyDescriptor;Ljava/lang/Class;)V",
speval, desc, cls)
javabridge.get_env().set_object_array_element(prop_path, 0, node)
cls = javabridge.get_env().get_object_class(speval)
desc = javabridge.make_instance(
"java/beans/PropertyDescriptor", "(Ljava/lang/String;Ljava/lang/Class;)V", "classifier", cls)
node = javabridge.make_instance(
"weka/experiment/PropertyNode", "(Ljava/lang/Object;Ljava/beans/PropertyDescriptor;Ljava/lang/Class;)V",
javabridge.call(speval, "getClass", "()Ljava/lang/Class;"), desc, cls)
javabridge.get_env().set_object_array_element(prop_path, 1, node)
return rproducer, prop_path
|
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', 'data', 'format'],
'record', 'Importing record but content is not record'),
'metadata': (['format'], 'metadata',
'Requesting metadata but content != metadata'),
'exp_file': (['action', 'record', 'field'], 'file',
'Exporting file but content is not file'),
'imp_file': (['action', 'record', 'field'], 'file',
'Importing file but content is not file'),
'del_file': (['action', 'record', 'field'], 'file',
'Deleteing file but content is not file'),
'exp_event': (['format'], 'event',
'Exporting events but content is not event'),
'exp_arm': (['format'], 'arm',
'Exporting arms but content is not arm'),
'exp_fem': (['format'], 'formEventMapping',
'Exporting form-event mappings but content != formEventMapping'),
'exp_user': (['format'], 'user',
'Exporting users but content is not user'),
'exp_survey_participant_list': (['instrument'], 'participantList',
'Exporting Survey Participant List but content != participantList'),
'version': (['format'], 'version',
'Requesting version but content != version')
}
extra, req_content, err_msg = valid_data[self.type]
required.extend(extra)
required = set(required)
pl_keys = set(self.payload.keys())
# if req is not subset of payload keys, this call is wrong
if not set(required) <= pl_keys:
# what is not in pl_keys?
not_pre = required - pl_keys
raise RCAPIError("Required keys: %s" % ', '.join(not_pre))
# Check content, raise with err_msg if not good
try:
if self.payload['content'] != req_content:
raise RCAPIError(err_msg)
except KeyError:
raise RCAPIError('content not in payload')
|
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',
else return raw string (ie format=='csv'|'xml')
"""
r = post(self.url, data=self.payload, **kwargs)
# Raise if we need to
self.raise_for_status(r)
content = self.get_content(r)
return content, r.headers
|
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':
content = {}
# Decode
try:
# Watch out for bad/empty json
content = json.loads(r.text, strict=False)
except ValueError as e:
if not self.expect_empty_json():
# reraise for requests that shouldn't send empty json
raise ValueError(e)
finally:
return content
else:
return r.text
|
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 user see the
(hopefully helpful) error message"""
if self.type in ('metadata', 'exp_file', 'imp_file', 'del_file'):
r.raise_for_status()
# see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
# specifically 10.5
if 500 <= r.status_code < 600:
raise RedcapError(r.content)
|
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 d
|
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 :
attribute list from each field
"""
filtered = [field[key] for field in self.metadata if key in field]
if len(filtered) == 0:
raise KeyError("Key not found in metadata")
return filtered
|
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'``
Return the form event mappings in native objects,
csv or xml, ``'df''`` will return a ``pandas.DataFrame``
df_kwargs : dict
Passed to pandas.read_csv to control construction of
returned DataFrame
Returns
-------
fem : list, str, ``pandas.DataFrame``
form-event mapping for the project
"""
ret_format = format
if format == 'df':
from pandas import read_csv
ret_format = 'csv'
pl = self.__basepl('formEventMapping', format=ret_format)
to_add = [arms]
str_add = ['arms']
for key, data in zip(str_add, to_add):
if data:
pl[key] = ','.join(data)
response, _ = self._call_api(pl, 'exp_fem')
if format in ('json', 'csv', 'xml'):
return response
elif format == 'df':
if not df_kwargs:
return read_csv(StringIO(response))
else:
return read_csv(StringIO(response), **df_kwargs)
|
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 these forms
format : (``'json'``), ``'csv'``, ``'xml'``, ``'df'``
Return the metadata in native objects, csv or xml.
``'df'`` will return a ``pandas.DataFrame``.
df_kwargs : dict
Passed to ``pandas.read_csv`` to control construction of
returned DataFrame.
by default ``{'index_col': 'field_name'}``
Returns
-------
metadata : list, str, ``pandas.DataFrame``
metadata sttructure for the project.
"""
ret_format = format
if format == 'df':
from pandas import read_csv
ret_format = 'csv'
pl = self.__basepl('metadata', format=ret_format)
to_add = [fields, forms]
str_add = ['fields', 'forms']
for key, data in zip(str_add, to_add):
if data:
pl[key] = ','.join(data)
response, _ = self._call_api(pl, 'metadata')
if format in ('json', 'csv', 'xml'):
return response
elif format == 'df':
if not df_kwargs:
df_kwargs = {'index_col': 'field_name'}
return read_csv(StringIO(response), **df_kwargs)
|
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 REDCap project.
Parameters
----------
records : list
array of record names specifying specific records to export.
by default, all records are exported
fields : list
array of field names specifying specific fields to pull
by default, all fields are exported
forms : list
array of form names to export. If in the web UI, the form
name has a space in it, replace the space with an underscore
by default, all forms are exported
events : list
an array of unique event names from which to export records
:note: this only applies to longitudinal projects
raw_or_label : (``'raw'``), ``'label'``, ``'both'``
export the raw coded values or labels for the options of
multiple choice fields, or both
event_name : (``'label'``), ``'unique'``
export the unique event name or the event label
format : (``'json'``), ``'csv'``, ``'xml'``, ``'df'``
Format of returned data. ``'json'`` returns json-decoded
objects while ``'csv'`` and ``'xml'`` return other formats.
``'df'`` will attempt to return a ``pandas.DataFrame``.
export_survey_fields : (``False``), True
specifies whether or not to export the survey identifier
field (e.g., "redcap_survey_identifier") or survey timestamp
fields (e.g., form_name+"_timestamp") when surveys are
utilized in the project.
export_data_access_groups : (``False``), ``True``
specifies whether or not to export the
``"redcap_data_access_group"`` field when data access groups
are utilized in the project.
:note: This flag is only viable if the user whose token is
being used to make the API request is *not* in a data
access group. If the user is in a group, then this flag
will revert to its default value.
df_kwargs : dict
Passed to ``pandas.read_csv`` to control construction of
returned DataFrame.
by default, ``{'index_col': self.def_field}``
export_checkbox_labels : (``False``), ``True``
specify whether to export checkbox values as their label on
export.
filter_logic : string
specify the filterLogic to be sent to the API.
Returns
-------
data : list, str, ``pandas.DataFrame``
exported data
"""
ret_format = format
if format == 'df':
from pandas import read_csv
ret_format = 'csv'
pl = self.__basepl('record', format=ret_format)
fields = self.backfill_fields(fields, forms)
keys_to_add = (records, fields, forms, events,
raw_or_label, event_name, export_survey_fields,
export_data_access_groups, export_checkbox_labels)
str_keys = ('records', 'fields', 'forms', 'events', 'rawOrLabel',
'eventName', 'exportSurveyFields', 'exportDataAccessGroups',
'exportCheckboxLabel')
for key, data in zip(str_keys, keys_to_add):
if data:
# Make a url-ok string
if key in ('fields', 'records', 'forms', 'events'):
pl[key] = ','.join(data)
else:
pl[key] = data
if filter_logic:
pl["filterLogic"] = filter_logic
response, _ = self._call_api(pl, 'exp_record')
if format in ('json', 'csv', 'xml'):
return response
elif format == 'df':
if not df_kwargs:
if self.is_longitudinal():
df_kwargs = {'index_col': [self.def_field,
'redcap_event_name']}
else:
df_kwargs = {'index_col': self.def_field}
buf = StringIO(response)
df = read_csv(buf, **df_kwargs)
buf.close()
return df
|
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" % (key, field))
return mf
else:
return mf
|
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 desired for matching subjects
Returns
-------
A list of dictionaries whose keys contains at least the default field
and at most each key passed in with output_fields, each dictionary
representing a surviving row in the database.
"""
query_keys = query.fields()
if not set(query_keys).issubset(set(self.field_names)):
raise ValueError("One or more query keys not in project keys")
query_keys.append(self.def_field)
data = self.export_records(fields=query_keys)
matches = query.filter(data, self.def_field)
if matches:
# if output_fields is empty, we'll download all fields, which is
# not desired, so we limit download to def_field
if not output_fields:
output_fields = [self.def_field]
# But if caller passed a string and not list, we need to listify
if isinstance(output_fields, basestring):
output_fields = [output_fields]
return self.export_records(records=matches, fields=output_fields)
else:
# If there are no matches, then sending an empty list to
# export_records will actually return all rows, which is not
# what we want
return []
|
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 string, ``pandas.DataFrame``
:note:
If you pass a csv or xml string, you should use the
``format`` parameter appropriately.
:note:
Keys of the dictionaries should be subset of project's,
fields, but this isn't a requirement. If you provide keys
that aren't defined fields, the returned response will
contain an ``'error'`` key.
overwrite : ('normal'), 'overwrite'
``'overwrite'`` will erase values previously stored in the
database if not specified in the to_import dictionaries.
format : ('json'), 'xml', 'csv'
Format of incoming data. By default, to_import will be json-encoded
return_format : ('json'), 'csv', 'xml'
Response format. By default, response will be json-decoded.
return_content : ('count'), 'ids', 'nothing'
By default, the response contains a 'count' key with the number of
records just imported. By specifying 'ids', a list of ids
imported will be returned. 'nothing' will only return
the HTTP status code and no message.
date_format : ('YMD'), 'DMY', 'MDY'
Describes the formatting of dates. By default, date strings
are formatted as 'YYYY-MM-DD' corresponding to 'YMD'. If date
strings are formatted as 'MM/DD/YYYY' set this parameter as
'MDY' and if formatted as 'DD/MM/YYYY' set as 'DMY'. No
other formattings are allowed.
force_auto_number : ('False') Enables automatic assignment of record IDs
of imported records by REDCap. If this is set to true, and auto-numbering
for records is enabled for the project, auto-numbering of imported records
will be enabled.
Returns
-------
response : dict, str
response from REDCap API, json-decoded if ``return_format`` == ``'json'``
"""
pl = self.__basepl('record')
if hasattr(to_import, 'to_csv'):
# We'll assume it's a df
buf = StringIO()
if self.is_longitudinal():
csv_kwargs = {'index_label': [self.def_field,
'redcap_event_name']}
else:
csv_kwargs = {'index_label': self.def_field}
to_import.to_csv(buf, **csv_kwargs)
pl['data'] = buf.getvalue()
buf.close()
format = 'csv'
elif format == 'json':
pl['data'] = json.dumps(to_import, separators=(',', ':'))
else:
# don't do anything to csv/xml
pl['data'] = to_import
pl['overwriteBehavior'] = overwrite
pl['format'] = format
pl['returnFormat'] = return_format
pl['returnContent'] = return_content
pl['dateFormat'] = date_format
pl['forceAutoNumber'] = force_auto_number
response = self._call_api(pl, 'imp_record')[0]
if 'error' in response:
raise RedcapError(str(response))
return response
|
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
record ID
field : str
field name containing the file to be exported.
event: str
for longitudinal projects, specify the unique event here
return_format: ('json'), 'csv', 'xml'
format of error message
Returns
-------
content : bytes
content of the file
content_map : dict
content-type dictionary
"""
self._check_file_field(field)
# load up payload
pl = self.__basepl(content='file', format=return_format)
# there's no format field in this call
del pl['format']
pl['returnFormat'] = return_format
pl['action'] = 'export'
pl['field'] = field
pl['record'] = record
if event:
pl['event'] = event
content, headers = self._call_api(pl, 'exp_file')
#REDCap adds some useful things in content-type
if 'content-type' in headers:
splat = [kv.strip() for kv in headers['content-type'].split(';')]
kv = [(kv.split('=')[0], kv.split('=')[1].replace('"', '')) for kv
in splat if '=' in kv]
content_map = dict(kv)
else:
content_map = {}
return content, content_map
|
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
field name where the file will go
fname : str
file name visible in REDCap UI
fobj : file object
file object as returned by `open`
event : str
for longitudinal projects, specify the unique event here
return_format : ('json'), 'csv', 'xml'
format of error message
Returns
-------
response :
response from server as specified by ``return_format``
"""
self._check_file_field(field)
# load up payload
pl = self.__basepl(content='file', format=return_format)
# no format in this call
del pl['format']
pl['returnFormat'] = return_format
pl['action'] = 'import'
pl['field'] = field
pl['record'] = record
if event:
pl['event'] = event
file_kwargs = {'files': {'file': (fname, fobj)}}
return self._call_api(pl, 'imp_file', **file_kwargs)[0]
|
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
return_format : (``'json'``), ``'csv'``, ``'xml'``
return format for error message
event : str
If longitudinal project, event to delete file from
Returns
-------
response : dict, str
response from REDCap after deleting file
"""
self._check_file_field(field)
# Load up payload
pl = self.__basepl(content='file', format=return_format)
del pl['format']
pl['returnFormat'] = return_format
pl['action'] = 'delete'
pl['record'] = record
pl['field'] = field
if event:
pl['event'] = event
return self._call_api(pl, 'del_file')[0]
|
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
raise ValueError(msg)
else:
return True
|
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
* ``'username'`` : User's username
* ``'expiration'`` : Project access expiration date
* ``'data_access_group'`` : data access group ID
* ``'data_export'`` : (0=no access, 2=De-Identified, 1=Full Data Set)
* ``'forms'`` : a list of dicts with a single key as the form name and
value is an integer describing that user's form rights,
where: 0=no access, 1=view records/responses and edit
records (survey responses are read-only), 2=read only, and
3=edit survey responses,
Parameters
----------
format : (``'json'``), ``'csv'``, ``'xml'``
response return format
Returns
-------
users: list, str
list of users dicts when ``'format'='json'``,
otherwise a string
"""
pl = self.__basepl(content='user', format=format)
return self._call_api(pl, 'exp_user')[0]
|
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 instrument as seen in second column of Data Dictionary.
event: str
Unique event name, only used in longitudinal projects
format: (json, xml, csv), json by default
Format of returned data
"""
pl = self.__basepl(content='participantList', format=format)
pl['instrument'] = instrument
if event:
pl['event'] = event
return self._call_api(pl, 'exp_survey_participant_list')
|
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 on the local hostname.
timeout (optional, default=5): request timeout in seconds
Raises:
QhueException if something went wrong with username generation (for
example, if the bridge button wasn't pressed).
"""
res = Resource(_api_url(ip), timeout)
prompt = "Press the Bridge button, then press Return: "
# Deal with one of the sillier python3 changes
if sys.version_info.major == 2:
_ = raw_input(prompt)
else:
_ = input(prompt)
if devicetype is None:
devicetype = "qhue#{}".format(getfqdn())
# raises QhueException if something went wrong
response = res(devicetype=devicetype, http_method="post")
return response[0]["success"]["username"]
|
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=0.1)
|
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:
logging.debug(f'Cancelling task: {task}')
task.cancel()
results = await asyncio.gather(*tasks, return_exceptions=True)
logging.debug(f'Done awaiting cancelled tasks, results: {results}')
loop.stop()
logging.info('Shutdown complete.')
|
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 of plugins, list of
instantiated plugin objects, and any errors encountered while
loading/instantiating plugins. A tuple of three empty lists is
returned if there are no plugins found or activated in gordon
config.
"""
installed_plugins = _gather_installed_plugins()
metrics_plugin = _get_metrics_plugin(config, installed_plugins)
if metrics_plugin:
plugin_kwargs['metrics'] = metrics_plugin
active_plugins = _get_activated_plugins(config, installed_plugins)
if not active_plugins:
return [], [], [], None
plugin_namespaces = _get_plugin_config_keys(active_plugins)
plugin_configs = _load_plugin_configs(plugin_namespaces, config)
plugin_names, plugins, errors = _init_plugins(
active_plugins, installed_plugins, plugin_configs, plugin_kwargs)
return plugin_names, plugins, errors, plugin_kwargs
|
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: UDPClientProtocol(message),
remote_addr=(self.ip, self.port))
|
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 dict with record properties.
timeout (int): Time threshold to query the DNS server.
"""
start_time = time.time()
name, rr_data, r_type, ttl = self._extract_record_data(record)
r_type_code = async_dns.types.get_code(r_type)
resolvable_record = False
retries = 0
sleep_time = 5
while not resolvable_record and \
timeout > retries * sleep_time:
retries += 1
resolver_res = await self._resolver.query(name, r_type_code)
possible_ans = resolver_res.an
resolvable_record = \
await self._check_resolver_ans(possible_ans, name,
rr_data, ttl, r_type_code)
if not resolvable_record:
await asyncio.sleep(sleep_time)
if not resolvable_record:
logging.info(
f'Sending metric record-checker-failed: {record}.')
else:
final_time = float(time.time() - start_time)
success_msg = (f'This record: {record} took {final_time} to '
'register.')
logging.info(success_msg)
|
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 (str): Record name.
record_data_list (list): List of data values for the record.
record_ttl (int): Record time-to-live info.
record_type_code (int): Record type code.
Returns:
boolean indicating if DNS answer data is equal to record data.
"""
type_filtered_list = [
ans for ans in dns_answer_list if ans.qtype == record_type_code
]
# check to see that type_filtered_lst has
# the same number of records as record_data_list
if len(type_filtered_list) != len(record_data_list):
return False
# check each record data is equal to the given data
for rec in type_filtered_list:
conditions = [rec.name == record_name,
rec.ttl == record_ttl,
rec.data in record_data_list]
# if ans record data is not equal
# to the given data return False
if not all(conditions):
return False
return True
|
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.level, message)
|
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. Default is False.
:returns: The enciphered string.
"""
if not keep_punct: string = self.remove_punctuation(string)
ret = ''
for c in string.upper():
if c.isalpha(): ret += self.key[self.a2i(c)]
else: ret += c
return ret
|
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. The ciphertext will be twice the length of the plaintext.
"""
string = self.remove_punctuation(string)#,filter='[^'+self.key+']')
ret = ''
for c in range(0,len(string)):
ret += self.encipher_char(string[c])
return ret
|
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. The plaintext will be half the length of the ciphertext.
"""
string = self.remove_punctuation(string)#,filter='[^'+self.chars+']')
ret = ''
for i in range(0,len(string),2):
ret += self.decipher_pair(string[i:i+2])
return ret
|
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)
:param string: The string to decipher.
:returns: The enciphered string.
"""
step2 = ColTrans(self.keyword).decipher(string)
step1 = PolybiusSquare(self.key,size=6,chars='ADFGVX').decipher(step2)
return step1
|
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','N'),steckers=[('P','O'),('M','L'),
('I','U'),('K','J'),('N','H'),('Y','T'),('G','B'),('V','F'),
('R','E'),('D','C')])).encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string.
"""
string = self.remove_punctuation(string)
ret = ''
for c in string.upper():
if c.isalpha(): ret += self.encipher_char(c)
else: ret += c
return ret
|
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]
count+=1
else: ret+=c
except IndexError:
print('restore_punctuation: strings must have same number of alphabetic chars')
raise
return ret
|
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='zgptfoihmuwdrcnykeqaxvsbl').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string.
"""
string = self.remove_punctuation(string)
string = re.sub(r'[J]', 'I', string)
if len(string) % 2 == 1:
string += 'X'
ret = ''
for c in range(0, len(string), 2):
ret += self.encipher_pair(string[c], string[c + 1])
return ret
|
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.
Example::
plaintext = Playfair(key='zgptfoihmuwdrcnykeqaxvsbl').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered string.
"""
string = self.remove_punctuation(string)
if len(string) % 2 == 1:
string += 'X'
ret = ''
for c in range(0, len(string), 2):
ret += self.decipher_pair(string[c], string[c + 1])
return ret
|
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 ciphertext will be 3 times the length of the plaintext.
"""
string = self.remove_punctuation(string,filter='[^'+self.key+']')
ctext = ""
for c in string:
ctext += ''.join([str(i) for i in L2IND[c]])
return ctext
|
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 plaintext will be 1/3 the length of the ciphertext.
"""
string = self.remove_punctuation(string,filter='[^'+self.chars+']')
ret = ''
for i in range(0,len(string),3):
ind = tuple([int(string[i+k]) for k in [0,1,2]])
ret += IND2L[ind]
return ret
|
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='zgptfoihmuwdrcnykeqaxvsbl',key2='mfnbdcrhsaxyogvituewlqzkp').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string.
"""
string = self.remove_punctuation(string)
if len(string)%2 == 1: string = string + 'X'
ret = ''
for c in range(0,len(string.upper()),2):
a,b = self.encipher_pair(string[c],string[c+1])
ret += a + b
return ret
|
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.
Example::
plaintext = Foursquare(key1='zgptfoihmuwdrcnykeqaxvsbl',key2='mfnbdcrhsaxyogvituewlqzkp').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered string.
"""
string = self.remove_punctuation(string)
if len(string)%2 == 1: string = string + 'X'
ret = ''
for c in range(0,len(string.upper()),2):
a,b = self.decipher_pair(string[c],string[c+1])
ret += a + b
return ret
|
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. Default is False.
:returns: The enciphered string.
"""
if not keep_punct: string = self.remove_punctuation(string)
ret = ''
for c in string:
if c.isalpha(): ret += self.i2a( self.a2i(c) + 13 )
else: ret += c
return ret
|
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.
:returns: The enciphered string.
"""
string = self.remove_punctuation(string)
ret = ''
for (i,c) in enumerate(string):
i = i%len(self.key)
if self.key[i] in 'AB': ret += 'NOPQRSTUVWXYZABCDEFGHIJKLM'[self.a2i(c)]
elif self.key[i] in 'YZ': ret += 'ZNOPQRSTUVWXYBCDEFGHIJKLMA'[self.a2i(c)]
elif self.key[i] in 'WX': ret += 'YZNOPQRSTUVWXCDEFGHIJKLMAB'[self.a2i(c)]
elif self.key[i] in 'UV': ret += 'XYZNOPQRSTUVWDEFGHIJKLMABC'[self.a2i(c)]
elif self.key[i] in 'ST': ret += 'WXYZNOPQRSTUVEFGHIJKLMABCD'[self.a2i(c)]
elif self.key[i] in 'QR': ret += 'VWXYZNOPQRSTUFGHIJKLMABCDE'[self.a2i(c)]
elif self.key[i] in 'OP': ret += 'UVWXYZNOPQRSTGHIJKLMABCDEF'[self.a2i(c)]
elif self.key[i] in 'MN': ret += 'TUVWXYZNOPQRSHIJKLMABCDEFG'[self.a2i(c)]
elif self.key[i] in 'KL': ret += 'STUVWXYZNOPQRIJKLMABCDEFGH'[self.a2i(c)]
elif self.key[i] in 'IJ': ret += 'RSTUVWXYZNOPQJKLMABCDEFGHI'[self.a2i(c)]
elif self.key[i] in 'GH': ret += 'QRSTUVWXYZNOPKLMABCDEFGHIJ'[self.a2i(c)]
elif self.key[i] in 'EF': ret += 'PQRSTUVWXYZNOLMABCDEFGHIJK'[self.a2i(c)]
elif self.key[i] in 'CD': ret += 'OPQRSTUVWXYZNMABCDEFGHIJKL'[self.a2i(c)]
return ret
|
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 string to encipher.
:returns: The enciphered string.
"""
message = self.remove_punctuation(message)
effective_ch = [0,0,0,0,0,0,0] # these are the wheels which are effective currently, 1 for yes, 0 no
# -the zero at the beginning is extra, indicates lug was in pos 0
ret = ''
# from now we no longer need the wheel starts, we can just increment the actual key
for j in range(len(message)):
shift = 0
effective_ch[0] = 0;
effective_ch[1] = self.wheel_1_settings[self.actual_key[0]]
effective_ch[2] = self.wheel_2_settings[self.actual_key[1]]
effective_ch[3] = self.wheel_3_settings[self.actual_key[2]]
effective_ch[4] = self.wheel_4_settings[self.actual_key[3]]
effective_ch[5] = self.wheel_5_settings[self.actual_key[4]]
effective_ch[6] = self.wheel_6_settings[self.actual_key[5]]
for i in range(0,27): # implements the cylindrical drum with lugs on it
if effective_ch[self.lug_positions[i][0]] or effective_ch[self.lug_positions[i][1]]: shift+=1
# shift has been found, now actually encrypt letter
ret += self.subst(message[j],key='ZYXWVUTSRQPONMLKJIHGFEDCBA',offset=-shift); # encrypt letter
self.advance_key(); # advance the key wheels
return ret
|
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.
"""
string = string.upper()
#print string
morsestr = self.enmorse(string)
# make sure the morse string is a multiple of 3 in length
if len(morsestr) % 3 == 1:
morsestr = morsestr[0:-1]
elif len(morsestr) % 3 == 2:
morsestr = morsestr + 'x'
#print morsestr
mapping = dict(zip(self.table,self.key))
ctext = ""
for i in range(0,len(morsestr),3):
ctext += mapping[morsestr[i:i+3]]
return ctext
|
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.
"""
string = string.upper()
mapping = dict(zip(self.key,self.table))
ptext = ""
for i in string:
ptext += mapping[i]
return self.demorse(ptext)
|
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 encipher.
:returns: The enciphered string.
"""
string = self.remove_punctuation(string)
ret = ''
ind = self.sortind(self.keyword)
for i in range(len(self.keyword)):
ret += string[ind.index(i)::len(self.keyword)]
return ret
|
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.
:returns: The deciphered string.
'''
string = self.remove_punctuation(string)
ret = ['_']*len(string)
L,M = len(string),len(self.keyword)
ind = self.unsortind(self.keyword)
upto = 0
for i in range(len(self.keyword)):
thiscollen = (int)(L/M)
if ind[i]< L%M: thiscollen += 1
ret[ind[i]::M] = string[upto:upto+thiscollen]
upto += thiscollen
return ''.join(ret)
|
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 spacing are retained. If false, it is all removed. Default is False.
:returns: The enciphered string.
"""
if not keep_punct: string = self.remove_punctuation(string)
return ''.join(self.buildfence(string, self.key))
|
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 spacing are retained. If false, it is all removed. Default is False.
:returns: The deciphered string.
"""
if not keep_punct: string = self.remove_punctuation(string)
ind = range(len(string))
pos = self.buildfence(ind, self.key)
return ''.join(string[pos.index(i)] for i in ind)
|
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 are retained. If false, it is all removed. Default is False.
:returns: The deciphered string.
"""
if not keep_punct: string = self.remove_punctuation(string)
ret = ''
for c in string:
if c.isalpha(): ret += self.i2a(self.inva*(self.a2i(c) - self.b))
else: ret += c
return ret
|
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.
:returns: The enciphered string.
"""
string = self.remove_punctuation(string)
ret = ''
for (i,c) in enumerate(string):
if i<len(self.key): offset = self.a2i(self.key[i])
else: offset = self.a2i(string[i-len(self.key)])
ret += self.i2a(self.a2i(c)+offset)
return ret
|
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 encipher.
:returns: The enciphered string.
"""
string = self.remove_punctuation(string)
step1 = self.pb.encipher(string)
evens = step1[::2]
odds = step1[1::2]
step2 = []
for i in range(0,len(string),self.period):
step2 += evens[i:int(i+self.period)]
step2 += odds[i:int(i+self.period)]
return self.pb.decipher(''.join(step2))
|
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.
:returns: The deciphered string.
"""
ret = ''
string = string.upper()
rowseq,colseq = [],[]
# take blocks of length period, reform rowseq,colseq from them
for i in range(0,len(string),self.period):
tempseq = []
for j in range(0,self.period):
if i+j >= len(string): continue
tempseq.append(int(self.key.index(string[i + j]) / 5))
tempseq.append(int(self.key.index(string[i + j]) % 5))
rowseq.extend(tempseq[0:int(len(tempseq)/2)])
colseq.extend(tempseq[int(len(tempseq)/2):])
for i in range(len(rowseq)):
ret += self.key[rowseq[i]*5 + colseq[i]]
return ret
|
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_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default is False.
:returns: The deciphered string.
"""
# if we have not yet calculated the inverse key, calculate it now
if self.invkey == '':
for i in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
self.invkey += self.i2a(self.key.index(i))
if not keep_punct: string = self.remove_punctuation(string)
ret = ''
for c in string.upper():
if c.isalpha(): ret += self.invkey[self.a2i(c)]
else: ret += c
return ret
|
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([], dtype=_np.int32)
c.r = _np.array([], dtype=_np.int32)
c.core = []
for t in a:
thetensor = t.tt if isinstance(t, _matrix.matrix) else t
c.d += thetensor.d
c.n = _np.concatenate((c.n, thetensor.n))
c.r = _np.concatenate((c.r[:-1], thetensor.r))
c.core = _np.concatenate((c.core, thetensor.core))
c.get_ps()
return c
|
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),
Z(1, i_1, \\ldots, i_d) = Y(i_1, \\ldots, i_d).
"""
tmp = _np.array([[1] + [0] * (len(args) - 1)])
result = kron(_vector.vector(tmp), args[0])
for i in range(1, len(args)):
result += kron(_vector.vector(_np.array([[0] * i +
[1] + [0] * (len(args) - i - 1)])), args[i])
return result
|
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] = _np.sum(crs[ax], axis=1)
rleft, rright = crs[ax].shape
if (rleft >= rright or rleft < rright and ax + 1 >= d) and ax > 0:
crs[ax - 1] = _np.tensordot(crs[ax - 1], crs[ax], axes=(2, 0))
elif ax + 1 < d:
crs[ax + 1] = _np.tensordot(crs[ax], crs[ax + 1], axes=(1, 0))
else:
return _np.sum(crs[ax])
crs.pop(ax)
d -= 1
return _vector.vector.from_list(crs)
|
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.core = _np.ones(c.ps[c.d] - 1)
return 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, dtype=_np.int32)
if d is None:
d = n.size
if n0.size is 1:
n0 = _np.ones((d,), dtype=_np.int32) * n0
if r0.size is 1:
r0 = _np.ones((d + 1,), dtype=_np.int32) * r0
r0[0] = 1
r0[d] = 1
c = _vector.vector()
c.d = d
c.n = n0
c.r = r0
c.get_ps()
c.core = samplefunc(c.ps[d] - 1)
return c
|
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.copy()
c.tt.n = (c.n) * (c.m)
c.tt.r = _np.ones((c.tt.d + 1,), dtype=_np.int32)
c.tt.get_ps()
c.tt.alloc_core()
for i in xrange(c.tt.d):
c.tt.core[
c.tt.ps[i] -
1:c.tt.ps[
i +
1] -
1] = _np.eye(
c.n[i]).flatten()
return c
|
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(coresX) - 1)
cc, rr = np.linalg.qr(reshape(cc, (-1, r2)))
r2 = cc.shape[1]
coresX[dim] = reshape(cc, (r1, n, r2))
coresX[dim+1] = np.tensordot(rr, coresX[dim+1], 1)
else:
# Right to left orthogonalization step.
assert(0 < dim < len(coresX))
cc, rr = np.linalg.qr(reshape(cc, (r1, -1)).T)
r1 = cc.shape[1]
coresX[dim] = reshape(cc.T, (r1, n, r2))
coresX[dim-1] = np.tensordot(coresX[dim-1], rr.T, 1)
return coresX
|
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(0) = y_0
and outputs approximation for :math:`y(\\tau)`
:References:
1. Christian Lubich, Ivan Oseledets, and Bart Vandereycken.
Time integration of tensor trains. arXiv preprint 1407.2042, 2014.
http://arxiv.org/abs/1407.2042
2. Christian Lubich and Ivan V. Oseledets. A projector-splitting integrator
for dynamical low-rank approximation. BIT, 54(1):171-188, 2014.
http://dx.doi.org/10.1007/s10543-013-0454-0
:param A: Matrix in the TT-format
:type A: matrix
:param y0: Initial condition in the TT-format,
:type y0: tensor
:param tau: Timestep
:type tau: float
:param scheme: The integration scheme, possible values: 'symm' -- second order, 'first' -- first order
:type scheme: str
:param space: Maximal dimension of the Krylov space for the local EXPOKIT solver.
:type space: int
:param use_normest: Use matrix norm estimation instead of the true 1-norm in KSL procedure. 0 -use true norm, 1 - Higham norm estimator, 2 - fixed norm=1.0 (for testing purposes only)
:type use_normest: int, default: 1
:rtype: tensor
:Example:
>>> import tt
>>> import tt.ksl
>>> import numpy as np
>>> d = 8
>>> a = tt.qlaplace_dd([d, d, d])
>>> y0, ev = tt.eigb.eigb(a, tt.rand(2 , 24, 2), 1e-6, verb=0)
Solving a block eigenvalue problem
Looking for 1 eigenvalues with accuracy 1E-06
swp: 1 er = 1.1408 rmax:2
swp: 2 er = 190.01 rmax:2
swp: 3 er = 2.72582E-08 rmax:2
Total number of matvecs: 0
>>> y1 = tt.ksl.ksl(a, y0, 1e-2)
Solving a real-valued dynamical problem with tau=1E-02
>>> print tt.dot(y1, y0) / (y1.norm() * y0.norm()) - 1 #Eigenvectors should not change
0.0
"""
y0 = y0.round(1e-14) # This will fix ranks
# to be no more than maximal reasonable.
# Fortran part doesn't handle excessive ranks
ry = y0.r.copy()
if scheme is 'symm':
tp = 2
else:
tp = 1
usenrm = int(use_normest)
# Check for dtype
y = tt.vector()
if np.iscomplex(A.tt.core).any() or np.iscomplex(y0.core).any():
dyn_tt.dyn_tt.ztt_ksl(
y0.d,
A.n,
A.m,
A.tt.r,
A.tt.core + 0j,
y0.core + 0j,
ry,
tau,
rmax,
0,
10,
verb,
tp,
space,
usenrm
)
y.core = dyn_tt.dyn_tt.zresult_core.copy()
else:
A.tt.core = np.real(A.tt.core)
y0.core = np.real(y0.core)
dyn_tt.dyn_tt.tt_ksl(
y0.d,
A.n,
A.m,
A.tt.r,
A.tt.core,
y0.core,
ry,
tau,
rmax,
0,
10,
verb,
tp,
space,
usenrm
)
y.core = dyn_tt.dyn_tt.dresult_core.copy()
dyn_tt.dyn_tt.deallocate_result()
y.d = y0.d
y.n = A.n.copy()
y.r = ry
y.get_ps()
return 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 ::
\\frac{dy}{dt} = V y, \\quad y(0) = y_0
and outputs approximation for :math:`y(\\tau)`
:References:
1. Christian Lubich, Ivan Oseledets, and Bart Vandereycken.
Time integration of tensor trains. arXiv preprint 1407.2042, 2014.
http://arxiv.org/abs/1407.2042
2. Christian Lubich and Ivan V. Oseledets. A projector-splitting integrator
for dynamical low-rank approximation. BIT, 54(1):171-188, 2014.
http://dx.doi.org/10.1007/s10543-013-0454-0
:param A: Matrix in the TT-format
:type A: matrix
:param y0: Initial condition in the TT-format,
:type y0: tensor
:param tau: Timestep
:type tau: float
:param scheme: The integration scheme, possible values: 'symm' -- second order, 'first' -- first order
:type scheme: str
:param space: Maximal dimension of the Krylov space for the local EXPOKIT solver.
:type space: int
:rtype: tensor
:Example:
>>> import tt
>>> import tt.ksl
>>> import numpy as np
>>> d = 8
>>> a = tt.qlaplace_dd([d, d, d])
>>> y0, ev = tt.eigb.eigb(a, tt.rand(2 , 24, 2), 1e-6, verb=0)
Solving a block eigenvalue problem
Looking for 1 eigenvalues with accuracy 1E-06
swp: 1 er = 1.1408 rmax:2
swp: 2 er = 190.01 rmax:2
swp: 3 er = 2.72582E-08 rmax:2
Total number of matvecs: 0
>>> y1 = tt.ksl.ksl(a, y0, 1e-2)
Solving a real-valued dynamical problem with tau=1E-02
>>> print tt.dot(y1, y0) / (y1.norm() * y0.norm()) - 1 #Eigenvectors should not change
0.0
"""
y0 = y0.round(1e-14) # This will fix ranks
# to be no more than maximal reasonable.
# Fortran part doesn't handle excessive ranks
ry = y0.r.copy()
if scheme is 'symm':
tp = 2
else:
tp = 1
# Check for dtype
y = tt.vector()
if np.iscomplex(A.core).any() or np.iscomplex(y0.core).any():
dyn_tt.dyn_diag_tt.ztt_diag_ksl(
y0.d,
A.n,
A.r,
A.core + 0j,
y0.core + 0j,
ry,
tau,
rmax,
0,
10,
verb,
tp,
space)
y.core = dyn_tt.dyn_diag_tt.zresult_core.copy()
else:
A.core = np.real(A.core)
y0.core = np.real(y0.core)
dyn_tt.dyn_diag_tt.dtt_diag_ksl(
y0.d,
A.n,
A.r,
A.core,
y0.core,
ry,
tau,
rmax,
0,
10,
verb,
tp,
space)
y.core = dyn_tt.dyn_diag_tt.dresult_core.copy()
dyn_tt.dyn_diag_tt.deallocate_result()
y.d = y0.d
y.n = A.n.copy()
y.r = ry
y.get_ps()
return y
|
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:`\\begin{bmatrix}\\Re M & -\\Im M \\\\ \\Im M & \\Re M \\end{bmatrix}`. This function
is useful for solving complex linear system :math:`\\mathcal{A}X = B` with real solver by
transforming it into
.. math::
\\begin{bmatrix}\\Re\\mathcal{A} & -\\Im\\mathcal{A} \\\\
\\Im\\mathcal{A} & \\Re\\mathcal{A} \\end{bmatrix}
\\begin{bmatrix}\\Re X \\\\ \\Im X\\end{bmatrix} =
\\begin{bmatrix}\\Re B \\\\ \\Im B\\end{bmatrix}.
"""
return matrix(a=self.tt.__complex_op('M'), n=_np.concatenate(
(self.n, [2])), m=_np.concatenate((self.m, [2])))
|
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.arange(2 * d)
prm = prm.reshape((d, 2), order='F')
prm = prm.transpose()
prm = prm.flatten('F')
# Get the inverse permutation
iprm = [0] * (2 * d)
for i in xrange(2 * d):
iprm[prm[i]] = i
a = a.transpose(iprm).reshape(N, M, order='F')
a = a.reshape(N, M)
return a
|
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, dtype=_np.int32)
r = _np.zeros(d+1, dtype=_np.int32)
cr = _np.array([])
for i in xrange(d):
cr = _np.concatenate((cr, a[i].flatten(order)))
r[i] = a[i].shape[0]
r[i+1] = a[i].shape[2]
n[i] = a[i].shape[1]
res.d = d
res.n = n
res.r = r
res.core = cr
res.get_ps()
return res
|
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] + n[d - 1] * r[d]
if d is 2:
er = sz * 1.0 / b
else:
a = _np.sum(n[1:d - 1])
er = (_np.sqrt(b * b + 4 * a * sz) - b) / (2 * a)
return er
|
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 = b ** 2 - 4 * a * c
r = 0.5 * (-b + _np.sqrt(D)) / a
return r
|
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 function.
:Reference:
S. V. Dolgov, B. N. Khoromskij, I. V. Oseledets, and D. V. Savostyanov.
Computation of extreme eigenvalues in higher dimensions using block tensor train format. Computer Phys. Comm.,
185(4):1207-1216, 2014. http://dx.doi.org/10.1016/j.cpc.2013.12.017
:param A: Matrix in the TT-format
:type A: matrix
:param y0: Initial guess in the block TT-format, r(d+1) is the number of eigenvalues sought
:type y0: tensor
:param eps: Accuracy required
:type eps: float
:param rmax: Maximal rank
:type rmax: int
:param kickrank: Addition rank, the larger the more robus the method,
:type kickrank: int
:rtype: A tuple (ev, tensor), where ev is a list of eigenvalues, tensor is an approximation to eigenvectors.
:Example:
>>> import tt
>>> import tt.eigb
>>> d = 8; f = 3
>>> r = [8] * (d * f + 1); r[d * f] = 8; r[0] = 1
>>> x = tt.rand(n, d * f, r)
>>> a = tt.qlaplace_dd([8, 8, 8])
>>> sol, ev = tt.eigb.eigb(a, x, 1e-6, verb=0)
Solving a block eigenvalue problem
Looking for 8 eigenvalues with accuracy 1E-06
swp: 1 er = 35.93 rmax:19
swp: 2 er = 4.51015E-04 rmax:18
swp: 3 er = 1.87584E-12 rmax:17
Total number of matvecs: 0
>>> print ev
[ 0.00044828 0.00089654 0.00089654 0.00089654 0.0013448 0.0013448
0.0013448 0.00164356]
"""
ry = y0.r.copy()
lam = tt_eigb.tt_block_eig.tt_eigb(y0.d, A.n, A.m, A.tt.r, A.tt.core, y0.core, ry, eps,
rmax, ry[y0.d], 0, nswp, max_full_size, verb)
y = tensor()
y.d = y0.d
y.n = A.n.copy()
y.r = ry
y.core = tt_eigb.tt_block_eig.result_core.copy()
tt_eigb.tt_block_eig.deallocate_result()
y.get_ps()
return y, lam
|
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 formatting is being done for the
bot's last reply (e.g. in a ``%Previous`` command).
:return str: The formatted message.
"""
# Make sure the string is Unicode for Python 2.
if sys.version_info[0] < 3 and isinstance(msg, str):
msg = msg.decode()
# Lowercase it.
msg = msg.lower()
# Run substitutions on it.
msg = self.substitute(msg, "sub")
# In UTF-8 mode, only strip metacharacters and HTML brackets
# (to protect from obvious XSS attacks).
if self.utf8:
msg = re.sub(RE.utf8_meta, '', msg)
msg = re.sub(self.master.unicode_punctuation, '', msg)
# For the bot's reply, also strip common punctuation.
if botreply:
msg = re.sub(RE.utf8_punct, '', msg)
else:
# For everything else, strip all non-alphanumerics.
msg = utils.strip_nasties(msg)
msg = msg.strip() # Strip leading and trailing white space
msg = RE.ws.sub(" ",msg) # Replace the multiple whitespaces by single whitespace
return msg
|
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 expand.
:param int depth: The recursion depth counter.
:return set: The final set of array entries.
"""
if depth > self.master._depth:
raise Exception("deep recursion detected")
if not array_name in self.master._array:
raise Exception("array '%s' not defined" % (array_name))
ret = list(self.master._array[array_name])
for array in self.master._array[array_name]:
if array.startswith('@'):
ret.remove(array)
expanded = self.do_expand_array(array[1:], depth+1)
ret.extend(expanded)
return set(ret)
|
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 in self.master._array else []
try:
ret = self.do_expand_array(array_name)
except Exception as e:
self.warn("Error expanding array '%s': %s" % (array_name, str(e)))
return ret
|
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 self.master._sorted:
raise RepliesNotSortedError("You must call sort_replies() once you are done loading RiveScript documents")
if kind not in self.master._sorted["lists"]:
raise RepliesNotSortedError("You must call sort_replies() once you are done loading RiveScript documents")
# Get the substitution map.
subs = None
if kind == 'sub':
subs = self.master._sub
else:
subs = self.master._person
# Make placeholders each time we substitute something.
ph = []
i = 0
for pattern in self.master._sorted["lists"][kind]:
result = subs[pattern]
# Make a placeholder.
ph.append(result)
placeholder = "\x00%d\x00" % i
i += 1
cache = self.master._regexc[kind][pattern]
msg = re.sub(cache["sub1"], placeholder, msg)
msg = re.sub(cache["sub2"], placeholder + r'\1', msg)
msg = re.sub(cache["sub3"], r'\1' + placeholder + r'\2', msg)
msg = re.sub(cache["sub4"], r'\1' + placeholder, msg)
placeholders = re.findall(RE.placeholder, msg)
for match in placeholders:
i = int(match)
result = ph[i]
msg = msg.replace('\x00' + match + '\x00', result)
# Strip & return.
return msg.strip()
|
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 = "def RSOBJ(rs, args):\n"
for line in code:
source = source + "\t" + line + "\n"
source += "self._objects[name] = RSOBJ\n"
try:
exec(source)
# self._objects[name] = RSOBJ
except Exception as e:
print("Failed to load code from object", name)
print("The error given was: ", e)
|
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 words sent as the object's arguments.
:return str: The output of the object macro.
"""
# Call the dynamic method.
if name not in self._objects:
return '[ERR: Object Not Found]'
func = self._objects[name]
reply = ''
try:
reply = func(rs, fields)
if reply is None:
reply = ''
except Exception as e:
raise PythonObjectError("Error executing Python object: " + str(e))
return text_type(reply)
|
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 triggers for 'previous' replies?
depth (int): Recursion step counter.
inheritance (int): The inheritance level counter, for topics that
inherit other topics.
inherited (bool): Whether the current topic is inherited by others.
Returns:
[]str: List of all triggers found.
"""
# Break if we're in too deep.
if depth > rs._depth:
rs._warn("Deep recursion while scanning topic inheritance")
# Keep in mind here that there is a difference between 'includes' and
# 'inherits' -- topics that inherit other topics are able to OVERRIDE
# triggers that appear in the inherited topic. This means that if the top
# topic has a trigger of simply '*', then NO triggers are capable of
# matching in ANY inherited topic, because even though * has the lowest
# priority, it has an automatic priority over all inherited topics.
#
# The getTopicTriggers method takes this into account. All topics that
# inherit other topics will have their triggers prefixed with a fictional
# {inherits} tag, which would start at {inherits=0} and increment if this
# topic has other inheriting topics. So we can use this tag to make sure
# topics that inherit things will have their triggers always be on top of
# the stack, from inherits=0 to inherits=n.
# Important info about the depth vs inheritance params to this function:
# depth increments by 1 each time this function recursively calls itrs.
# inheritance increments by 1 only when this topic inherits another
# topic.
#
# This way, '> topic alpha includes beta inherits gamma' will have this
# effect:
# alpha and beta's triggers are combined together into one matching
# pool, and then those triggers have higher matching priority than
# gamma's.
#
# The inherited option is True if this is a recursive call, from a topic
# that inherits other topics. This forces the {inherits} tag to be added
# to the triggers. This only applies when the top topic 'includes'
# another topic.
rs._say("\tCollecting trigger list for topic " + topic + "(depth="
+ str(depth) + "; inheritance=" + str(inheritance) + "; "
+ "inherited=" + str(inherited) + ")")
# topic: the name of the topic
# depth: starts at 0 and ++'s with each recursion
# Topic doesn't exist?
if not topic in rs._topics:
rs._warn("Inherited or included topic {} doesn't exist or has no triggers".format(
topic
))
return []
# Collect an array of triggers to return.
triggers = []
# Get those that exist in this topic directly.
inThisTopic = []
if not thats:
# The non-that structure is {topic}->[array of triggers]
if topic in rs._topics:
for trigger in rs._topics[topic]:
inThisTopic.append([ trigger["trigger"], trigger ])
else:
# The 'that' structure is: {topic}->{cur trig}->{prev trig}->{trig info}
if topic in rs._thats.keys():
for curtrig in rs._thats[topic].keys():
for previous, pointer in rs._thats[topic][curtrig].items():
inThisTopic.append([ pointer["trigger"], pointer ])
# Does this topic include others?
if topic in rs._includes:
# Check every included topic.
for includes in rs._includes[topic]:
rs._say("\t\tTopic " + topic + " includes " + includes)
triggers.extend(get_topic_triggers(rs, includes, thats, (depth + 1), inheritance, True))
# Does this topic inherit others?
if topic in rs._lineage:
# Check every inherited topic.
for inherits in rs._lineage[topic]:
rs._say("\t\tTopic " + topic + " inherits " + inherits)
triggers.extend(get_topic_triggers(rs, inherits, thats, (depth + 1), (inheritance + 1), False))
# Collect the triggers for *this* topic. If this topic inherits any
# other topics, it means that this topic's triggers have higher
# priority than those in any inherited topics. Enforce this with an
# {inherits} tag.
if topic in rs._lineage or inherited:
for trigger in inThisTopic:
rs._say("\t\tPrefixing trigger with {inherits=" + str(inheritance) + "}" + trigger[0])
triggers.append(["{inherits=" + str(inheritance) + "}" + trigger[0], trigger[1]])
else:
triggers.extend(inThisTopic)
return triggers
|
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."""
words = []
if all:
words = re.split(RE.ws, trigger)
else:
words = re.split(RE.wilds_and_optionals, trigger)
wc = 0 # Word count
for word in words:
if len(word) > 0:
wc += 1
return wc
|
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, message)
# Send the response.
resp = twilio.twiml.Response()
resp.message(reply)
return str(resp)
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.