func_code_string stringlengths 52 1.94M | func_documentation_string stringlengths 1 47.2k |
|---|---|
def do_execute(self):
result = None
data = self.input.payload
pltdataset.line_plot(
data,
atts=self.resolve_option("attributes"),
percent=float(self.resolve_option("percent")),
seed=int(self.resolve_option("seed")),
title=self.... | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str |
def fix_config(self, options):
options = super(ClassifierErrors, self).fix_config(options)
opt = "absolute"
if opt not in options:
options[opt] = True
if opt not in self.help:
self.help[opt] = "Whether to use absolute errors as size or relative ones (bool... | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict |
def check_input(self, token):
if not isinstance(token.payload, Evaluation):
raise Exception(self.full_name + ": Input token is not an Evaluation object!") | Performs checks on the input token. Raises an exception if unsupported.
:param token: the token to check
:type token: Token |
def do_execute(self):
result = None
evl = self.input.payload
pltclassifier.plot_classifier_errors(
evl.predictions,
absolute=bool(self.resolve_option("absolute")),
max_relative_size=int(self.resolve_option("max_relative_size")),
absolute_s... | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str |
def fix_config(self, options):
options = super(ROC, self).fix_config(options)
opt = "class_index"
if opt not in options:
options[opt] = [0]
if opt not in self.help:
self.help[opt] = "The list of 0-based class-label indices to display (list)."
opt ... | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict |
def fix_config(self, options):
options = super(PRC, self).fix_config(options)
opt = "class_index"
if opt not in options:
options[opt] = [0]
if opt not in self.help:
self.help[opt] = "The list of 0-based class-label indices to display (list)."
opt ... | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict |
def do_execute(self):
result = None
evl = self.input.payload
pltclassifier.plot_prc(
evl,
class_index=self.resolve_option("class_index"),
title=self.resolve_option("title"),
key_loc=self.resolve_option("key_loc"),
outfile=self.... | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str |
def do_execute(self):
result = None
data = self.input.payload
if isinstance(self._input.payload, Instance):
inst = self.input.payload
data = inst.dataset
elif isinstance(self.input.payload, Instances):
data = self.input.payload
ins... | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str |
def configure_splitevaluator(self):
if self.classification:
speval = javabridge.make_instance("weka/experiment/ClassifierSplitEvaluator", "()V")
else:
speval = javabridge.make_instance("weka/experiment/RegressionSplitEvaluator", "()V")
classifier = javabridge.cal... | Configures and returns the SplitEvaluator and Classifier instance as tuple.
:return: evaluator and classifier
:rtype: tuple |
def setup(self):
# 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, "set... | Initializes the experiment. |
def run(self):
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") | Executes the experiment. |
def load(cls, filename):
jobject = javabridge.static_call(
"weka/experiment/Experiment", "read", "(Ljava/lang/String;)Lweka/experiment/Experiment;",
filename)
return Experiment(jobject=jobject) | Loads the experiment from disk.
:param filename: the filename of the experiment to load
:type filename: str
:return: the experiment
:rtype: Experiment |
def configure_resultproducer(self):
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)
spe... | Configures and returns the ResultProducer and PropertyPath as tuple.
:return: producer and property path
:rtype: tuple |
def set_row_name(self, index, name):
javabridge.call(self.jobject, "setRowName", "(ILjava/lang/String;)V", 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 |
def set_col_name(self, index, name):
javabridge.call(self.jobject, "setColName", "(ILjava/lang/String;)V", 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 |
def get_mean(self, col, row):
return javabridge.call(self.jobject, "getMean", "(II)D", col, row) | Returns the mean at this location (if valid location).
:param col: the 0-based column index
:type col: int
:param row: the 0-based row index
:type row: int
:return: the mean
:rtype: float |
def set_mean(self, col, row, mean):
javabridge.call(self.jobject, "setMean", "(IID)V", col, row, mean) | Sets the mean at this location (if valid location).
:param col: the 0-based column index
:type col: int
:param row: the 0-based row index
:type row: int
:param mean: the mean to set
:type mean: float |
def get_stdev(self, col, row):
return javabridge.call(self.jobject, "getStdDev", "(II)D", col, row) | Returns the standard deviation at this location (if valid location).
:param col: the 0-based column index
:type col: int
:param row: the 0-based row index
:type row: int
:return: the standard deviation
:rtype: float |
def set_stdev(self, col, row, stdev):
javabridge.call(self.jobject, "setStdDev", "(IID)V", col, row, stdev) | Sets the standard deviation at this location (if valid location).
:param col: the 0-based column index
:type col: int
:param row: the 0-based row index
:type row: int
:param stdev: the standard deviation to set
:type stdev: float |
def validate(self):
required = ['token', 'content']
valid_data = {
'exp_record': (['type', 'format'], 'record',
'Exporting record but content is not record'),
'imp_record': (['type', 'overwriteBehavior', 'data', 'format'],
'record', 'Impor... | Checks that at least required params exist |
def execute(self, **kwargs):
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 | 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'|'... |
def get_content(self, r):
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
... | Abstraction for grabbing content from a returned response |
def raise_for_status(self, r):
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.conte... | 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) er... |
def __basepl(self, content, rec_type='flat', format='json'):
d = {'token': self.token, 'content': content, 'format': format}
if content not in ['metadata', 'file']:
d['type'] = rec_type
return d | Return a dictionary which can be used as is or added to for
payloads |
def is_longitudinal(self):
return len(self.events) > 0 and \
len(self.arm_nums) > 0 and \
len(self.arm_names) > 0 | Returns
-------
boolean :
longitudinal status of this project |
def filter_metadata(self, key):
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 | 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 |
def export_fem(self, arms=None, format='json', df_kwargs=None):
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']
... | 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''`` wi... |
def export_metadata(self, fields=None, forms=None, format='json',
df_kwargs=None):
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]... | 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 o... |
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):
ret_format = format
... | 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
... |
def __meta_metadata(self, field, key):
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 the value for key for the field in the metadata |
def backfill_fields(self, fields, forms):
if forms and not fields:
new_fields = [self.def_field]
elif fields and self.def_field not in fields:
new_fields = list(fields)
if self.def_field not in fields:
new_fields.append(self.def_field)
... | Properly backfill fields to explicitly request specific
keys. The issue is that >6.X servers *only* return requested fields
so to improve backwards compatiblity for PyCap clients, add specific fields
when required.
Parameters
----------
fields: list
requested... |
def filter(self, query, output_fields=None):
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_k... | 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
---... |
def names_labels(self, do_print=False):
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 | Simple helper function to get all field names and labels |
def import_records(self, to_import, overwrite='normal', format='json',
return_format='json', return_content='count',
date_format='YMD', force_auto_number=False):
pl = self.__basepl('record')
if hasattr(to_import, 'to_csv'):
# We'll assume it's a df
buf = ... | 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:
... |
def export_file(self, record, field, event=None, return_format='json'):
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_fo... | 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.
... |
def import_file(self, record, field, fname, fobj, event=None,
return_format='json'):
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'] ... | 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 o... |
def delete_file(self, record, field, return_format='json', event=None):
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... | 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 mess... |
def _check_file_field(self, 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:
... | Check that field exists and is a file field |
def export_users(self, format='json'):
pl = self.__basepl(content='user', format=format)
return self._call_api(pl, 'exp_user')[0] | 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
* ``'expira... |
def export_survey_participant_list(self, instrument, event=None, format='json'):
pl = self.__basepl(content='participantList', format=format)
pl['instrument'] = instrument
if event:
pl['event'] = event
return self._call_api(pl, 'exp_survey_participant_list') | 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... |
def create_new_username(ip, devicetype=None, timeout=_DEFAULT_TIMEOUT):
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:
_ = in... | 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 ... |
async def run(self):
logging.info('Starting message router...')
coroutines = set()
while True:
coro = self._poll_channel()
coroutines.add(coro)
_, coroutines = await asyncio.wait(coroutines, timeout=0.1) | Entrypoint to route messages between plugins. |
async def shutdown(sig, loop):
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 = a... | Gracefully cancel current tasks when app receives a shutdown signal. |
def _deep_merge_dict(a, b):
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 | Additively merge right side dict into left side dict. |
def load_plugins(config, plugin_kwargs):
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... | 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 objec... |
def connection_made(self, transport):
self.transport = transport
self.transport.sendto(self.message)
self.transport.close() | Create connection, use to send message and close.
Args:
transport (asyncio.DatagramTransport): Transport used for sending. |
async def send(self, metric):
message = json.dumps(metric).encode('utf-8')
await self.loop.create_datagram_endpoint(
lambda: UDPClientProtocol(message),
remote_addr=(self.ip, self.port)) | Transform metric to JSON bytestring and send to server.
Args:
metric (dict): Complete metric to send as JSON. |
async def check_record(self, record, timeout=60):
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 resolva... | 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 th... |
async def _check_resolver_ans(
self, dns_answer_list, record_name,
record_data_list, record_ttl, record_type_code):
type_filtered_list = [
ans for ans in dns_answer_list if ans.qtype == record_type_code
]
# check to see that type_filtered_lst has
... | 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.
... |
def read(*filenames, **kwargs):
encoding = kwargs.get('encoding', 'utf-8')
sep = kwargs.get('sep', '\n')
buf = []
for fl in filenames:
with codecs.open(os.path.join(HERE, fl), 'rb', encoding) as f:
buf.append(f.read())
return sep.join(buf) | Build an absolute path from ``*filenames``, and return contents of
resulting file. Defaults to UTF-8 encoding. |
def log(self, metric):
message = self.LOGFMT.format(**metric)
if metric['context']:
message += ' context: {context}'.format(context=metric['context'])
self._logger.log(self.level, message) | Format and output metric.
Args:
metric (dict): Complete metric. |
def encipher(self,string,keep_punct=False):
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 | 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 s... |
def encipher(self,string):
string = self.remove_punctuation(string)#,filter='[^'+self.key+']')
ret = ''
for c in range(0,len(string)):
ret += self.encipher_char(string[c])
return ret | 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 lengt... |
def decipher(self,string):
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 | 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 ... |
def decipher(self,string):
step2 = ColTrans(self.keyword).decipher(string)
step1 = PolybiusSquare(self.key,size=6,chars='ADFGVX').decipher(step2)
return step1 | 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.... |
def encipher(self,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 | 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'),
... |
def ic(ctext):
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 | takes ciphertext, calculates index of coincidence. |
def ngram_count(text,N=1,keep_punct=False):
if not keep_punct: text = re.sub('[^A-Z]','',text.upper())
count = {}
for i in range(len(text)-N+1):
c = text[i:i+N]
if c in count: count[c] += 1
else: count[c] = 1.0
return count | if N=1, return a dict containing each letter along with how many times the letter occurred.
if N=2, returns a dict containing counts of each bigram (pair of letters)
etc.
There is an option to remove all spaces and punctuation prior to processing |
def ngram_freq(text,N=1,log=False,floor=0.01):
freq = ngram_count(text,N)
L = 1.0*(len(text)-N+1)
for c in freq.keys():
if log: freq[c] = math.log10(freq[c]/L)
else: freq[c] = freq[c]/L
if log: freq['floor'] = math.log10(floor/L)
else: freq['floor'] = floor/L
return freq | returns the n-gram frequencies of all n-grams encountered in text.
Option to return log probabilities or standard probabilities.
Note that only n-grams occurring in 'text' will have probabilities.
For the probability of not-occurring n-grams, use freq['floor'].
This is set to floor/len(t... |
def restore_punctuation(original,modified):
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 ... | If punctuation was accidently removed, use this function to restore it.
requires the orignial string with punctuation. |
def keyword_to_key(word,alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
ret = ''
word = (word + alphabet).upper()
for i in word:
if i in ret: continue
ret += i
return ret | convert a key word to a key by appending on the other letters of the alphabet.
e.g. MONARCHY -> MONARCHYBDEFGIJKLPQSTUVWXZ |
def encipher(self, 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])
... | 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(plaintex... |
def decipher(self, 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 | 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 = Play... |
def encipher(self,string):
string = self.remove_punctuation(string,filter='[^'+self.key+']')
ctext = ""
for c in string:
ctext += ''.join([str(i) for i in L2IND[c]])
return ctext | 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 p... |
def decipher(self,string):
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 | 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 cipher... |
def encipher(self,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
retur... | 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='mfnbdcr... |
def decipher(self,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 ... | 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 = Fo... |
def encipher(self,string,keep_punct=False):
r
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 | 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... |
def encipher(self,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 += 'Z... | 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. |
def encipher(self,message):
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
... | 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 ... |
def encipher(self,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:
... | 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. |
def decipher(self,string):
string = string.upper()
mapping = dict(zip(self.key,self.table))
ptext = ""
for i in string:
ptext += mapping[i]
return self.demorse(ptext) | 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. |
def encipher(self,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 | 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 enciphere... |
def decipher(self,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)
... | 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 strin... |
def encipher(self,string,keep_punct=False):
if not keep_punct: string = self.remove_punctuation(string)
return ''.join(self.buildfence(string, self.key)) | 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 i... |
def decipher(self,string,keep_punct=False):
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) | 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 i... |
def decipher(self,string,keep_punct=False):
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 | 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 Fa... |
def encipher(self,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... | 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. |
def encipher(self,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)]
... | 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 encipher... |
def decipher(self,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):
... | 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 stri... |
def decipher(self,string,keep_punct=False):
# 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.remo... | 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. ... |
def matvec(a, b, compression=False):
acrs = _vector.vector.to_list(a.tt)
bcrs = _vector.vector.to_list(b)
ccrs = []
d = b.d
def get_core(i):
acr = _np.reshape(
acrs[i],
(a.tt.r[i],
a.n[i],
a.m[i],
a.tt.r[
i ... | Matrix-vector product in TT format. |
def kron(a, b):
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') | Kronecker product of two TT-matrices or two TT-vectors |
def dot(a, b):
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') | Dot product of two TT-matrices or two TT-vectors |
def mkron(a, *args):
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([], dt... | Kronecker product of all the arguments |
def zkron(ttA, ttB):
Al = _matrix.matrix.to_list(ttA)
Bl = _matrix.matrix.to_list(ttB)
Hl = [_np.kron(B, A) for (A, B) in zip(Al, Bl)]
return _matrix.matrix.from_list(Hl) | Do kronecker product between cores of two matrices ttA and ttB.
Look about kronecker at: https://en.wikipedia.org/wiki/Kronecker_product
For details about operation refer: https://arxiv.org/abs/1802.02839
:param ttA: first TT-matrix;
:param ttB: second TT-matrix;
:return: TT-matrix in z-order |
def zkronv(ttA, ttB):
Al = _vector.vector.to_list(ttA)
Bl = _vector.vector.to_list(ttB)
Hl = [_np.kron(B, A) for (A, B) in zip(Al, Bl)]
return _vector.vector.from_list(Hl) | Do kronecker product between vectors ttA and ttB.
Look about kronecker at: https://en.wikipedia.org/wiki/Kronecker_product
For details about operation refer: https://arxiv.org/abs/1802.02839
:param ttA: first TT-vector;
:param ttB: second TT-vector;
:return: operation result in z-order |
def zmeshgrid(d):
lin = xfun(2, d)
one = ones(2, d)
xx = zkronv(lin, one)
yy = zkronv(one, lin)
return xx, yy | Returns a meshgrid like np.meshgrid but in z-order
:param d: you'll get 4**d nodes in meshgrid
:return: xx, yy in z-order |
def zaffine(c0, c1, c2, d):
xx, yy = zmeshgrid(d)
Hx, Hy = _vector.vector.to_list(xx), _vector.vector.to_list(yy)
Hs = _cp.deepcopy(Hx)
Hs[0][:, :, 0] = c1 * Hx[0][:, :, 0] + c2 * Hy[0][:, :, 0]
Hs[-1][1, :, :] = c1 * Hx[-1][1, :, :] + (c0 + c2 * Hy[-1][1, :, :])
d = len(Hs)
for k in ra... | Generate linear function c0 + c1 ex + c2 ey in z ordering with d cores in QTT
:param c0:
:param c1:
:param c2:
:param d:
:return: |
def concatenate(*args):
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])
r... | 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(... |
def sum(a, axis=-1):
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, ... | Sum TT-vector over specified axes |
def ones(n, d=None):
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)
retu... | Creates a TT-vector of all ones |
def rand(n, d=None, r=2, samplefunc=_np.random.randn):
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.i... | 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. |
def eye(n, d=None):
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)
... | Creates an identity TT-matrix |
def Toeplitz(x, d=None, D=None, kind='F'):
# checking for arguments consistency
def check_kinds(D, kind):
if D % len(kind) == 0:
kind.extend(kind * (D // len(kind) - 1))
if len(kind) != D:
raise ValueError(
"Must give proper amount of _matrix kinds (o... | Creates multilevel Toeplitz TT-matrix with ``D`` levels.
Possible _matrix types:
* 'F' - full Toeplitz _matrix, size(x) = 2^{d+1}
* 'C' - circulant _matrix, size(x) = 2^d
* 'L' - lower triangular Toeplitz _matrix, size(x) = 2^d
* 'U' - upper triangul... |
def qlaplace_dd(d):
res = _matrix.matrix()
d0 = d[::-1]
D = len(d0)
I = _np.eye(2)
J = _np.array([[0, 1], [0, 0]])
cr = []
if D is 1:
for k in xrange(1, d0[0] + 1):
if k is 1:
cur_core = _np.zeros((1, 2, 2, 3))
cur_core[:, :, :, 0] = 2... | Creates a QTT representation of the Laplace operator |
def xfun(n, d=None):
if isinstance(n, six.integer_types):
n = [n]
if d is None:
n0 = _np.asanyarray(n, dtype=_np.int32)
else:
n0 = _np.array(n * d, dtype=_np.int32)
d = n0.size
if d == 1:
return _vector.vector.from_list(
[_np.reshape(_np.arange(n0[0])... | Create a QTT-representation of 0:prod(n) _vector
call examples:
tt.xfun(2, 5) # create 2 x 2 x 2 x 2 x 2 TT-vector
tt.xfun(3) # create [0, 1, 2] one-dimensional TT-vector
tt.xfun([3, 5, 7], 2) # create 3 x 5 x 7 x 3 x 5 x 7 TT-vector |
def linspace(n, d=None, a=0.0, b=1.0, right=True, left=True):
if isinstance(n, six.integer_types):
n = [n]
if d is None:
n0 = _np.asanyarray(n, dtype=_np.int32)
else:
n0 = _np.array(n * d, dtype=_np.int32)
d = n0.size
t = xfun(n0)
e = ones(n0)
N = _np.prod(n0) #... | Create a QTT-representation of a uniform grid on an interval [a, b] |
def sin(d, alpha=1.0, phase=0.0):
cr = []
cur_core = _np.zeros([1, 2, 2], dtype=_np.float)
cur_core[0, 0, :] = [_math.cos(phase), _math.sin(phase)]
cur_core[0, 1, :] = [_math.cos(alpha + phase), _math.sin(alpha + phase)]
cr.append(cur_core)
for i in xrange(1, d - 1):
cur_core = _np.... | Create TT-vector for :math:`\\sin(\\alpha n + \\varphi)`. |
def cos(d, alpha=1.0, phase=0.0):
return sin(d, alpha, phase + _math.pi * 0.5) | Create TT-vector for :math:`\\cos(\\alpha n + \\varphi)`. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.