INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
uses the MapRule 'm' to run through the 'dict'
and extract data based on the rule | def process_rule(self, m, dct, tpe):
"""
uses the MapRule 'm' to run through the 'dict'
and extract data based on the rule
"""
print('TODO - ' + tpe + ' + applying rule ' + str(m).replace('\n', '') ) |
uses type to format the raw information to a dictionary
usable by the mapper | def format_raw_data(self, tpe, raw_data):
"""
uses type to format the raw information to a dictionary
usable by the mapper
"""
if tpe == 'text':
formatted_raw_data = self.parse_text_to_dict(raw_data)
elif tpe == 'file':
formatted_raw_data ... |
takes a string and parses via NLP, ready for mapping | def parse_text_to_dict(self, txt):
"""
takes a string and parses via NLP, ready for mapping
"""
op = {}
print('TODO - import NLP, split into verbs / nouns')
op['nouns'] = txt
op['verbs'] = txt
return op |
process the file according to the mapping rules.
The cols list must match the columns in the filename | def parse_file_to_dict(self, fname):
"""
process the file according to the mapping rules.
The cols list must match the columns in the filename
"""
print('TODO - parse_file_to_dict' + fname)
for m in self.maps:
if m.tpe == 'file':
if m.key[0:3] ... |
creates a map file (in the standard CSV format) based on
columns of a dataset.
1. read column names, lookup names in list
2. read column content, get highest match of distinct values
from ontology lists (eg, Years, countries, cities, ages) | def generate_map_from_dataset(self, l_dataset):
"""
creates a map file (in the standard CSV format) based on
columns of a dataset.
1. read column names, lookup names in list
2. read column content, get highest match of distinct values
from ontology lists (eg, Years... |
reads the data_filename into a matrix and calls the main
function '' to generate a .rule file based on the data in the map
For all datafiles mapped, there exists a .rule file to define it | def create_map_from_file(self, data_filename):
"""
reads the data_filename into a matrix and calls the main
function '' to generate a .rule file based on the data in the map
For all datafiles mapped, there exists a .rule file to define it
"""
o... |
load the rules from file | def load_rules(self):
"""
load the rules from file
"""
self.col_maps = []
#print("reading mapping table")
with open(self.col_file, 'r') as f:
for line in f:
rule = MapColumn(line)
#rule = line
self.col_maps.appe... |
splits the CSV line of the current format and puts into
local class variables - mainly for testing, though this is
not the best method long term. (TODO - fix this) | def _parse_csv_col_rules(self):
"""
splits the CSV line of the current format and puts into
local class variables - mainly for testing, though this is
not the best method long term. (TODO - fix this)
"""
self.cols = self.csv_line.split(',')
self.table = self.extr... |
loops until exit command given | def run(self):
"""
loops until exit command given
"""
while self.status != 'EXIT':
print(self.process_input(self.get_input()))
print('Bye') |
takes a question and returns the best answer based on known skills | def process_input(self, question):
"""
takes a question and returns the best answer based on known skills
"""
ans = ''
if self.status == 'EXIT':
print('bye')
sys.exit()
if '?' in question:
ans = self.info.find_answer(question)
... |
This takes the question 'qu' and parses info and raw input
to try and find an answer.
It should use the skills, and where parameters are needed it
should guess them if not in there - for example weather should
default to local location unless a [country|city] is part of question | def find_answer(self, qu):
"""
This takes the question 'qu' and parses info and raw input
to try and find an answer.
It should use the skills, and where parameters are needed it
should guess them if not in there - for example weather should
default to local location unle... |
shows a data file in CSV format - all files live in CORE folder | def show_data_file(fname):
""" shows a data file in CSV format - all files live in CORE folder """
txt = '<H2>' + fname + '</H2>'
print (fname)
#try:
txt += web.read_csv_to_html_table(fname, 'Y') # it is ok to use a table for actual table data
#except:
# txt += '<H2>ERROR - cant read file</... |
Wrapper for subprocess.Popen to work across various Python versions, when using the with syntax. | def managed_process(process):
"""Wrapper for subprocess.Popen to work across various Python versions, when using the with syntax."""
try:
yield process
finally:
for stream in [process.stdout, process.stdin, process.stderr]:
if stream:
stream.close()
proces... |
Updating OS environment variables and current script path and filename. | def update_environment_variables(self, filename):
"""Updating OS environment variables and current script path and filename."""
self.env.update(os.environ.copy())
self.env.update({'PIPELINE_BASH_FILE': filename}) |
Get path for temporary scripts.
Returns:
str: path for temporary scripts or None if not set | def get_temporary_scripts_path(self):
"""
Get path for temporary scripts.
Returns:
str: path for temporary scripts or None if not set
"""
result = None
if len(self.config.temporary_scripts_path) > 0:
if os.path.isdir(self.config.temporary_scripts_... |
Create a temporary, executable bash file.
It also does render given script (string) with the model and
the provided environment variables and optional also an item
when using the B{with} field.
Args:
script (str): either pather and filename or Bash code.
Returns:
... | def create_file_for(self, script):
"""
Create a temporary, executable bash file.
It also does render given script (string) with the model and
the provided environment variables and optional also an item
when using the B{with} field.
Args:
script (str): eithe... |
Rendering Bash options. | def render_bash_options(self):
"""Rendering Bash options."""
options = ''
if self.config.debug:
options += "set -x\n"
if self.config.strict:
options += "set -euo pipefail\n"
return options |
Running the Bash code. | def process_script(self, filename):
"""Running the Bash code."""
try:
with managed_process(subprocess.Popen(shlex.split("bash %s" % filename),
stdout=self.stdout, stderr=self.stderr,
shell=sel... |
Processing one file. | def process_file(self, filename):
"""Processing one file."""
if self.config.dry_run:
if not self.config.internal:
self.logger.info("Dry run mode for script %s", filename)
with open(filename) as handle:
for line in handle:
yield ... |
Running the Bash code. | def process(self):
"""Running the Bash code."""
temp_filename = self.create_file_for(self.config.script)
if len(self.config.title) > 0:
self.logger.info(render(self.config.title, model=self.config.model, env=self.env,
item=self.config.item, variab... |
Returns an PIL Image converted to the RGB color space. If the image has
an alpha channel (transparency), it will be overlaid on a black background.
:param image: the PIL image to convert
:returns: The input image if it was already in RGB mode, or a new RGB image
if converted.
:raises Im... | def _to_pil_rgb_image(image):
"""Returns an PIL Image converted to the RGB color space. If the image has
an alpha channel (transparency), it will be overlaid on a black background.
:param image: the PIL image to convert
:returns: The input image if it was already in RGB mode, or a new RGB image
... |
Generates an optimized JPEG from a PIL image. If the image has an alpha
channel (transparency), it will be overlaid on a black background.
:param image: the PIL image
:param quality: the output JPEG quality (default 95)
:returns: Optimized JPEG bytes
:rtype: bytes
:raises ImportError: PIL / P... | def process_pil_image(image, quality=guetzli.DEFAULT_JPEG_QUALITY):
"""Generates an optimized JPEG from a PIL image. If the image has an alpha
channel (transparency), it will be overlaid on a black background.
:param image: the PIL image
:param quality: the output JPEG quality (default 95)
:return... |
Return a file descriptor from a file object. If
given an integer will simply return that integer back. | def _fileobj_to_fd(fileobj):
""" Return a file descriptor from a file object. If
given an integer will simply return that integer back. """
if isinstance(fileobj, _INTEGER_TYPES):
fd = fileobj
else:
for _integer_type in _INTEGER_TYPES:
try:
fd = _integer_type(... |
This function serves as a first call for DefaultSelector to
detect if the select module is being monkey-patched incorrectly
by eventlet, greenlet, and preserve proper behavior. | def DefaultSelector():
""" This function serves as a first call for DefaultSelector to
detect if the select module is being monkey-patched incorrectly
by eventlet, greenlet, and preserve proper behavior. """
global _DEFAULT_SELECTOR
if _DEFAULT_SELECTOR is None:
if platform.python_implementa... |
Unregister a file object from being monitored. | def unregister(self, fileobj):
""" Unregister a file object from being monitored. """
try:
key = self._fd_to_key.pop(self._fileobj_lookup(fileobj))
except KeyError:
raise KeyError("{0!r} is not registered".format(fileobj))
# Getting the fileno of a closed socket ... |
adds a channel, but must have authenication | def add_channel(self, channel, pwd_hash):
"""
adds a channel, but must have authenication
"""
if channel.pwd_hash == pwd_hash:
self.channels.append(channel)
lg.record_process('comms.py', 'Added channel ' + channel.name)
return True
else:
... |
adds a channel, but must have authenication | def delete_channel(self, channel, pwd_hash):
"""
adds a channel, but must have authenication
"""
if channel.pwd_hash == pwd_hash:
self.channels.remove(channel)
lg.record_process('comms.py', 'Removed channel ' + channel.name)
return True
else:
... |
does some basic validation | def prepare(self):
"""
does some basic validation
"""
try:
assert(type(self.sender) is Channel)
assert(type(self.receiver) is Channel)
return True
except:
return False |
this handles the message transmission | def send(self):
"""
this handles the message transmission
"""
#print('sending message to ' + self.receiver)
if self.prepare():
## TODO - send message via library
print('sending message')
lg.record_process('comms.py', 'Sending message ' + self.t... |
main function - outputs in following format BEFORE consolidation (which is TODO)
# filename, word, linenumbers
# refAction.csv, ActionTypeName, 1
# refAction.csv, PhysicalType, 1
# goals.csv, Cleanliness, 11 | def index():
"""
main function - outputs in following format BEFORE consolidation (which is TODO)
# filename, word, linenumbers
# refAction.csv, ActionTypeName, 1
# refAction.csv, PhysicalType, 1
# goals.csv, Cleanliness, 11
"""
lg = mod_log.Log(mod_cf... |
this creates an index of a text file specifically for use in AIKIF
separates the ontology descriptions highest followed by values and lastly
a final pass to get all delimited word parts. | def buildIndex(ipFile, ndxFile, append='Y', silent='N', useShortFileName='Y'):
"""
this creates an index of a text file specifically for use in AIKIF
separates the ontology descriptions highest followed by values and lastly
a final pass to get all delimited word parts.
"""
if silent == 'N':
... |
Format the output row with stats | def format_op_row(ipFile, totLines, totWords, uniqueWords):
"""
Format the output row with stats
"""
txt = os.path.basename(ipFile).ljust(36) + ' '
txt += str(totLines).rjust(7) + ' '
txt += str(totWords).rjust(7) + ' '
txt += str(len(uniqueWords)).rjust(7) + ' '
return txt |
Build the header | def format_op_hdr():
"""
Build the header
"""
txt = 'Base Filename'.ljust(36) + ' '
txt += 'Lines'.rjust(7) + ' '
txt += 'Words'.rjust(7) + ' '
txt += 'Unique'.ljust(8) + ''
return txt |
Save the list of unique words to the master list | def AppendIndexDictionaryToFile(uniqueWords, ndxFile, ipFile, useShortFileName='Y'):
"""
Save the list of unique words to the master list
"""
if useShortFileName == 'Y':
f = os.path.basename(ipFile)
else:
f = ipFile
with open(ndxFile, "a", encoding='utf-8', errors='replace') as... |
print the index as a dict | def DisplayIndexAsDictionary(word_occurrences):
"""
print the index as a dict
"""
word_keys = word_occurrences.keys()
for num, word in enumerate(word_keys):
line_nums = word_occurrences[word]
print(word + " ")
if num > 3:
break |
for testing, simply shows a list details | def show(title, lst, full=-1):
"""
for testing, simply shows a list details
"""
txt = title + ' (' + str(len(lst)) + ') items :\n '
num = 0
for i in lst:
if full == -1 or num < full:
if type(i) is str:
txt = txt + i + ',\n '
else:
t... |
extract a unique list of words and have line numbers that word appears | def getWordList(ipFile, delim):
"""
extract a unique list of words and have line numbers that word appears
"""
indexedWords = {}
totWords = 0
totLines = 0
with codecs.open(ipFile, "r",encoding='utf-8', errors='replace') as f:
for line in f:
totLines = totLines + 1
... |
make a single index file with 1 record per word which shows the word, file and linenums
# storms, knowledge.csv - 3
# string, rawData.csv - 1
# structure, EVENT_SYSTEM-PC-FILE.CSV - 18, OBJECT_SYSTEM-PC-FILE.CSV - 4, sample-filelist-for-AIKIF.csv - 18 18
# subgoal, goals.csv - 3 4 12 13 ... | def consolidate(ipFile, opFile):
"""
make a single index file with 1 record per word which shows the word, file and linenums
# storms, knowledge.csv - 3
# string, rawData.csv - 1
# structure, EVENT_SYSTEM-PC-FILE.CSV - 18, OBJECT_SYSTEM-PC-FILE.CSV - 4, sample-filelist-for-AIKIF.csv - 18... |
split by multiple delimiters | def multi_split(txt, delims):
"""
split by multiple delimiters
"""
res = [txt]
for delimChar in delims:
txt, res = res, []
for word in txt:
if len(word) > 1:
res += word.split(delimChar)
return res |
Preparing and creating script. | def creator(entry, config):
"""Preparing and creating script."""
script = render(config.script, model=config.model, env=config.env, item=config.item)
temp = tempfile.NamedTemporaryFile(prefix="script-", suffix=".py", mode='w+t', delete=False)
temp.writelines(script)
temp.close()... |
converts and unknown type to string for display purposes. | def force_to_string(unknown):
"""
converts and unknown type to string for display purposes.
"""
result = ''
if type(unknown) is str:
result = unknown
if type(unknown) is int:
result = str(unknown)
if type(unknown) is float:
result = str(unknown)
if type(unkno... |
For a log session you can add as many watch points
which are used in the aggregation and extraction of
key things that happen.
Each watch point has a rating (up to you and can range
from success to total failure and an importance for
finer control of display | def add_watch_point(self, string, rating, importance=5):
"""
For a log session you can add as many watch points
which are used in the aggregation and extraction of
key things that happen.
Each watch point has a rating (up to you and can range
from success to total failu... |
get a unique id (shortish string) to allow simple aggregation
of log records from multiple sources. This id is used for the
life of the running program to allow extraction from all logs.
WARING - this can give duplicate sessions when 2 apps hit it
at the same time. | def get_session_id(self):
"""
get a unique id (shortish string) to allow simple aggregation
of log records from multiple sources. This id is used for the
life of the running program to allow extraction from all logs.
WARING - this can give duplicate sessions when 2 apps hit it
... |
calculates a rough guess of runtime based on product of parameters | def estimate_complexity(self, x,y,z,n):
"""
calculates a rough guess of runtime based on product of parameters
"""
num_calculations = x * y * z * n
run_time = num_calculations / 100000 # a 2014 PC does about 100k calcs in a second (guess based on prior logs)
return sel... |
converts seconds to a string in terms of
seconds -> years to show complexity of algorithm | def show_time_as_short_string(self, seconds):
"""
converts seconds to a string in terms of
seconds -> years to show complexity of algorithm
"""
if seconds < 60:
return str(seconds) + ' seconds'
elif seconds < 3600:
return str(round(seconds/60, 1)... |
logs an entry to fname along with standard date and user details | def _log(self, fname, txt, prg=''):
"""
logs an entry to fname along with standard date and user details
"""
if os.sep not in fname:
fname = self.log_folder + os.sep + fname
delim = ','
q = '"'
dte = TodayAsString()
usr = GetUserName()
... |
function to collect raw data from the web and hard drive
Examples - new source file for ontologies, email contacts list, folder for xmas photos | def record_source(self, src, prg=''):
"""
function to collect raw data from the web and hard drive
Examples - new source file for ontologies, email contacts list, folder for xmas photos
"""
self._log(self.logFileSource , force_to_string(src), prg) |
log a process or program - log a physical program (.py, .bat, .exe) | def record_process(self, process, prg=''):
"""
log a process or program - log a physical program (.py, .bat, .exe)
"""
self._log(self.logFileProcess, force_to_string(process), prg) |
record the command passed - this is usually the name of the program
being run or task being run | def record_command(self, cmd, prg=''):
"""
record the command passed - this is usually the name of the program
being run or task being run
"""
self._log(self.logFileCommand , force_to_string(cmd), prg) |
record the output of the command. Records the result, can have
multiple results, so will need to work out a consistent way to aggregate this | def record_result(self, res, prg=''):
"""
record the output of the command. Records the result, can have
multiple results, so will need to work out a consistent way to aggregate this
"""
self._log(self.logFileResult , force_to_string(res), prg) |
parse the log files and extract entries from all
logfiles to one file per program (program is the
2nd to last entry each logfile) | def filter_by_program(self, prg, opFile):
"""
parse the log files and extract entries from all
logfiles to one file per program (program is the
2nd to last entry each logfile)
"""
log_1 = open(self.process_file, 'r')
log_2 = open(self.command_file, 'r')
... |
read a logfile and return entries for a program | def extract_logs(self, fname, prg):
"""
read a logfile and return entries for a program
"""
op = []
with open(fname, 'r') as f:
for line in f:
if prg in line:
op.append(line)
return op |
takes the logfiles and produces an event summary matrix
date command result process source
20140421 9 40 178 9
20140423 0 0 6 0
20140424 19 1 47 19
20140425 24 0 117 24
... | def summarise_events(self):
"""
takes the logfiles and produces an event summary matrix
date command result process source
20140421 9 40 178 9
20140423 0 0 6 0
20140424 19 1 47 19
... |
reads a logfile and returns a dictionary by date
showing the count of log entries | def _count_by_date(self, fname, all_dates):
"""
reads a logfile and returns a dictionary by date
showing the count of log entries
"""
if not os.path.isfile(fname):
return {}
d_log_sum = {}
with open(fname, "r") as raw_log:
for line in raw_l... |
provides a mapping from the CSV file to the
aikif data structures. | def map_data(self):
"""
provides a mapping from the CSV file to the
aikif data structures.
"""
with open(self.src_file, "r") as f:
for line in f:
cols = line.split(',')
print(cols) |
read the dependent peptides table and extract localiztion information
:param filename: path to the 'allPeptides.txt' table.
:returns dep, localization: the dependent peptide table, localization information. | def read_dependent_peptides(filename):
""" read the dependent peptides table and extract localiztion information
:param filename: path to the 'allPeptides.txt' table.
:returns dep, localization: the dependent peptide table, localization information.
"""
df = (pd.read_perseus(filename, usecols=_cols)... |
rename the columns in the dependent peptides table from
the raw file to the corresponding {experiment}_{fraction}.
:param dep: dependent peptides table.
:param exp: experimental design table. | def _set_column_names(dep, exp):
""" rename the columns in the dependent peptides table from
the raw file to the corresponding {experiment}_{fraction}.
:param dep: dependent peptides table.
:param exp: experimental design table.
"""
colnames = exp['Experiment'].astype(str) + '_' + exp['Fraction'... |
count occurences in a list of lists
>>> count([['a','b'],['a']])
defaultdict(int, {'a' : 2, 'b' : 1}) | def count(args):
""" count occurences in a list of lists
>>> count([['a','b'],['a']])
defaultdict(int, {'a' : 2, 'b' : 1})
"""
counts = defaultdict(int)
for arg in args:
for item in arg:
counts[item] = counts[item] + 1
return counts |
count the most likely localization for each depentent peptide.
:param df: allPeptides.txt table. | def _count_localizations(df):
""" count the most likely localization for each depentent peptide.
:param df: allPeptides.txt table.
"""
grp = df.groupby(_index_columns)
counts = grp['DP AA'].apply(lambda x: count(x.str.split(';').values))
counts.index = counts.index.set_names('DP AA', level=4)
... |
returns the most frequent localization for any dependent peptide.
In case of ties, preference is given to n-terminal modification which are
biologically more likely to occur
:param df: allPeptides.txt table. | def _frequent_localizations(df):
""" returns the most frequent localization for any dependent peptide.
In case of ties, preference is given to n-terminal modification which are
biologically more likely to occur
:param df: allPeptides.txt table.
"""
max_count = int(df['DP AA count'].max())
ma... |
transform a allPeptides.txt and experimentalDesign.txt table
into the dependentPeptides.txt table written in outfile.
:param paramfile: Perseus parameters.xml including at least two FileParam
entries names 'allPeptides.txt' and 'experimentalDesign.txt'.
:param outfile: Path to the output file. | def run_dependent_peptides_from_parameters(paramfile, outfile):
""" transform a allPeptides.txt and experimentalDesign.txt table
into the dependentPeptides.txt table written in outfile.
:param paramfile: Perseus parameters.xml including at least two FileParam
entries names 'allPeptides.txt' and 'experim... |
transform a allPeptides.txt and experimentalDesign.txt table
into the dependentPeptides.txt table written in outfile.
:param allPeptides_file: MaxQuant 'allPeptides.txt' output table.
:param rawFilesTable_file: MaxQuant 'Raw files'-tab table.
:param outfile: Path to the output file. | def run_dependent_peptides(allPeptides_file, rawFilesTable_file, outfile):
""" transform a allPeptides.txt and experimentalDesign.txt table
into the dependentPeptides.txt table written in outfile.
:param allPeptides_file: MaxQuant 'allPeptides.txt' output table.
:param rawFilesTable_file: MaxQuant 'Raw ... |
Returns the string of a variable name. | def variablename(var):
"""
Returns the string of a variable name.
"""
s=[tpl[0] for tpl in itertools.ifilter(lambda x: var is x[1], globals().items())]
s=s[0].upper()
return s |
Performs a blast query online.
As in https://ncbi.github.io/blast-cloud/
:param query: Search query. Allowed values: Accession, GI, or FASTA.
:param database: BLAST database. Allowed values: nt, nr, refseq_rna, refseq_protein, swissprot, pdbaa, pdbnt
:param program: BLAST program. Allowed values: bla... | def BLASTquery(query,database,program,filter=None,\
format_type=None, expect=None,\
nucl_reward=None, nucl_penalty=None,\
gapcosts=None, matrix=None,\
hitlist_size=None, descriptions=None,\
alignments=None,\
ncbi_gi=None, threshol... |
Checks the status of a query.
:param rid: BLAST search request identifier. Allowed values: The Request ID (RID) returned when the search was submitted
:param baseURL: server url. Default=http://blast.ncbi.nlm.nih.gov
:returns status: status for the query.
:returns therearehist: yes or no for existing ... | def BLASTcheck(rid,baseURL="http://blast.ncbi.nlm.nih.gov"):
"""
Checks the status of a query.
:param rid: BLAST search request identifier. Allowed values: The Request ID (RID) returned when the search was submitted
:param baseURL: server url. Default=http://blast.ncbi.nlm.nih.gov
:returns status:... |
Retrieves results for an RID.
:param rid: BLAST search request identifier. Allowed values: The Request ID (RID) returned when the search was submitted
:param format_type: Report type. Allowed values: HTML, Text, XML, XML2, JSON2, or Tabular. Tabular is the default.
:param hitlist_size: Number of databases ... | def BLASTresults(rid, format_type="Tabular", \
hitlist_size= None, alignments=None, \
ncbi_gi = None, format_object=None,\
baseURL="http://blast.ncbi.nlm.nih.gov"):
"""
Retrieves results for an RID.
:param rid: BLAST search request identifier. Allowed valu... |
Generating HTML report.
Args:
store (Store): report data.
Returns:
str: rendered HTML template. | def generate_html(store):
"""
Generating HTML report.
Args:
store (Store): report data.
Returns:
str: rendered HTML template.
"""
spline = {
'version': VERSION,
'url': 'https://github.com/Nachtfeuer/pipeline',
'generated': datetime.now().strftime("%A, %d... |
Generate file in defined format representing the report of pipeline(s).
Args:
store (Store): report data.
report_format (str): currently "html" is supported only.
path (str): path where to write the report to. Missing sub folders will be created. | def generate(store, report_format, path):
"""
Generate file in defined format representing the report of pipeline(s).
Args:
store (Store): report data.
report_format (str): currently "html" is supported only.
path (str): path where to write the report to. Missing sub folders will be... |
Handle begin of a list. | def __begin_of_list(self, ast_token):
"""Handle begin of a list."""
self.list_level += 1
if self.list_level == 1:
self.final_ast_tokens.append(ast_token) |
Handle end of a list. | def __end_of_list(self, ast_token):
"""Handle end of a list."""
self.list_level -= 1
if self.list_level == 0:
if self.list_entry is not None:
self.final_ast_tokens.append(self.list_entry)
self.list_entry = None
self.final_ast_tokens.append(... |
Handle tokens inside the list or outside the list. | def __default(self, ast_token):
"""Handle tokens inside the list or outside the list."""
if self.list_level == 1:
if self.list_entry is None:
self.list_entry = ast_token
elif not isinstance(ast_token, type(self.list_entry)):
self.final_ast_tokens.a... |
Main function of compression. | def compress(self):
"""Main function of compression."""
for ast_token in self.ast_tokens:
if type(ast_token) in self.dispatcher: # pylint: disable=unidiomatic-typecheck
self.dispatcher[type(ast_token)](ast_token)
else:
self.dispatcher['default'](a... |
Get AST tokens for Python condition.
Returns:
list: list of AST tokens | def get_tokens(condition):
"""
Get AST tokens for Python condition.
Returns:
list: list of AST tokens
"""
try:
ast_tokens = list(ast.walk(ast.parse(condition.strip())))
except SyntaxError as exception:
Logger.get_logger(__name__).error... |
Verify that each token in order does match the expected types.
The list provided by `get_tokens` does have three more elements
at the beginning of the list which should be always the same
for a condition (Module and Expr). Those are automatically
added first to the final list of expecte... | def match_tokens(ast_tokens, ast_types):
"""
Verify that each token in order does match the expected types.
The list provided by `get_tokens` does have three more elements
at the beginning of the list which should be always the same
for a condition (Module and Expr). Those are a... |
Verify condition (format).
>>> Condition.is_valid('{{ foo }} == 42')
True
>>> Condition.is_valid('"{{ foo }}" == 42')
False
>>> Condition.is_valid(' not "{{ foo }}" == "42" ')
True
>>> Condition.is_valid(' not {{ foo }} == 42 ')
True
>>> Condi... | def is_valid(condition):
"""
Verify condition (format).
>>> Condition.is_valid('{{ foo }} == 42')
True
>>> Condition.is_valid('"{{ foo }}" == 42')
False
>>> Condition.is_valid(' not "{{ foo }}" == "42" ')
True
>>> Condition.is_valid(' not {{ fo... |
Find rule for given condition.
Args:
condition (str): Python condition as string.
Returns:
str, list, function: found rule name, list of AST tokens for condition
and verification function. | def find_rule(condition):
"""
Find rule for given condition.
Args:
condition (str): Python condition as string.
Returns:
str, list, function: found rule name, list of AST tokens for condition
and verification function.
""... |
Evaluate simple condition.
>>> Condition.evaluate(' 2 == 2 ')
True
>>> Condition.evaluate(' not 2 == 2 ')
False
>>> Condition.evaluate(' not "abc" == "xyz" ')
True
>>> Condition.evaluate('2 in [2, 4, 6, 8, 10]')
True
>>> Condition.ev... | def evaluate(condition):
"""
Evaluate simple condition.
>>> Condition.evaluate(' 2 == 2 ')
True
>>> Condition.evaluate(' not 2 == 2 ')
False
>>> Condition.evaluate(' not "abc" == "xyz" ')
True
>>> Condition.evaluate('2 in [2, 4, 6, 8... |
starts the web interface and possibly other processes | def start_aikif():
"""
starts the web interface and possibly other processes
"""
if sys.platform[0:3] == 'win':
os.system("start go_web_aikif.bat")
else:
os.system("../aikif/web_app/web_aikif.py")
import webbrowser
import time
time.sleep(1)
webbrowser... |
Get creator function by name.
Args:
name (str): name of the creator function.
Returns:
function: creater function. | def get_creator_by_name(name):
"""
Get creator function by name.
Args:
name (str): name of the creator function.
Returns:
function: creater function.
"""
return {'docker(container)': Container.creator,
'shell': Bash.creator, 'docker(image)': Image.creator,
... |
Running on shell via multiprocessing. | def worker(data):
"""Running on shell via multiprocessing."""
creator = get_creator_by_name(data['creator'])
shell = creator(data['entry'],
ShellConfig(script=data['entry']['script'],
title=data['entry']['title'] if 'title' in data['entry'] else '',
... |
Copying and merging environment variables.
Args:
include_os (bool): when true then include the environment variables (default: False)
Returns:
dict: environment variables as defined in the pipeline
(optional including system environment variables). | def get_merged_env(self, include_os=False):
"""
Copying and merging environment variables.
Args:
include_os (bool): when true then include the environment variables (default: False)
Returns:
dict: environment variables as defined in the pipeline
... |
Prepare one shell or docker task. | def prepare_shell_data(self, shells, key, entry):
"""Prepare one shell or docker task."""
if self.can_process_shell(entry):
if key in ['python']:
entry['type'] = key
if 'with' in entry and isinstance(entry['with'], str):
rendered_with = ast.litera... |
Processing a group of tasks. | def process(self, document):
"""Processing a group of tasks."""
self.logger.info("Processing group of tasks (parallel=%s)", self.get_parallel_mode())
self.pipeline.data.env_list[2] = {}
output, shells = [], []
result = Adapter({'success': True, 'output': []})
for task_en... |
Processing a list of shells. | def process_shells(self, shells):
"""Processing a list of shells."""
result = {'success': True, 'output': []}
if self.parallel and len(shells) > 1:
result = self.process_shells_parallel(shells)
elif len(shells) > 0:
result = self.process_shells_ordered(shells)
... |
:return: True when shell can be executed. | def can_process_shell(self, entry):
""":return: True when shell can be executed."""
count = 0
condition = render(entry['when'], variables=self.pipeline.variables,
model=self.pipeline.model, env=self.get_merged_env(include_os=True))
if Condition.evaluate("" if ... |
Adding all files from given path to the object.
Args:
path (str): valid, existing directory | def add_path(self, path, path_filter=None):
"""
Adding all files from given path to the object.
Args:
path (str): valid, existing directory
"""
for root, _, files in os.walk(path):
for filename in files:
full_path_and_filename = os.path.jo... |
Convert JSON into a in memory file storage.
Args:
data (str): valid JSON with path and filenames and
the base64 encoding of the file content.
Returns:
InMemoryFiles: in memory file storage | def from_json(data):
"""
Convert JSON into a in memory file storage.
Args:
data (str): valid JSON with path and filenames and
the base64 encoding of the file content.
Returns:
InMemoryFiles: in memory file storage
"""
memf... |
Run cleanup hook when configured. | def run_cleanup(self, env, exit_code):
"""Run cleanup hook when configured."""
output = []
if self.pipeline.data.hooks and len(self.pipeline.data.hooks.cleanup) > 0:
env.update({'PIPELINE_RESULT': 'FAILURE'})
env.update({'PIPELINE_SHELL_EXIT_CODE': str(exit_code)})
... |
script to setup folder structures for AIKIF
and prepare data tables. | def main():
"""
script to setup folder structures for AIKIF
and prepare data tables.
"""
print('\n\n /------- AIKIF Installation --------\\')
print(' | s. show current setup |')
print(' | f. setup folder structures |')
print(' | c. create sample data |')
... |
delete all files in folder 'fldr' | def delete_files_in_folder(fldr):
"""
delete all files in folder 'fldr'
"""
fl = glob.glob(fldr + os.sep + '*.*')
for f in fl:
delete_file(f, True) |
file_tools.copy_all_files_and_subfolders(src, dest, backup_path, ['*.*'])
gets list of all subfolders and copies each file to
its own folder in 'dest' folder
paths, xtn, excluded, output_file_name = 'my_files.csv') | def copy_all_files_and_subfolders(src, dest, base_path_ignore, xtn_list):
"""
file_tools.copy_all_files_and_subfolders(src, dest, backup_path, ['*.*'])
gets list of all subfolders and copies each file to
its own folder in 'dest' folder
paths, xtn, excluded, output_file_name = 'my_files.csv')
"""
ensure_dir(dest... |
extracts the real content from an RDF info object | def get_string_from_rdf(src):
""" extracts the real content from an RDF info object """
res = src.split("/") #[:-1]
return "".join([l.replace('"', '""') for l in res[len(res) - 1]]) |
Flatten nested sequences into one. | def flatten(*sequence):
"""Flatten nested sequences into one."""
result = []
for entry in sequence:
if isinstance(entry, list):
result += Select.flatten(*entry)
elif isinstance(entry, tuple):
result += Select.flatten(*entry)
els... |
Saving stored files at a given path (relative paths are added).
Args:
path (str): root path where to save the files. | def save(self, path):
"""
Saving stored files at a given path (relative paths are added).
Args:
path (str): root path where to save the files.
"""
for relative_path_and_filename, content in self.files.items():
full_path_and_filename = os.path.join(path, r... |
Do the query. | def build(self):
"""Do the query."""
result = []
for entry in self.sequence:
ignore = False
for filter_function in self.filter_functions:
if not filter_function(entry):
ignore = True
break
if not ignore:
... |
reads an RDF file into a graph | def load_graph_from_rdf(fname):
""" reads an RDF file into a graph """
print("reading RDF from " + fname + "....")
store = Graph()
store.parse(fname, format="n3")
print("Loaded " + str(len(store)) + " tuples")
return store |
make a short version of an RDF file | def create_sample_file(ip, op, num_lines):
""" make a short version of an RDF file """
with open(ip, "rb") as f:
with open(op, "wb") as fout:
for _ in range(num_lines):
fout.write(f.readline() ) |
copies all the files from src to dest folder | def copy_files_to_folder(src, dest, xtn='*.txt'):
"""
copies all the files from src to dest folder
"""
try:
all_files = glob.glob(os.path.join(src,xtn))
for f in all_files:
copy_file(f, dest)
except Exception as ex:
print('ERROR copy_files_to_folder - ' + str(ex)) |
This is the main body of the process that does the work.
Summary:
- load the raw data
- read in rules list
- create log events for AIKIF according to rules [map]
- create new facts / reports based on rules [report]
OUTPUT =
AIKIF mapping : Date_of_transaction => event
... | def main():
"""
This is the main body of the process that does the work.
Summary:
- load the raw data
- read in rules list
- create log events for AIKIF according to rules [map]
- create new facts / reports based on rules [report]
OUTPUT =
AIKIF mapping : Date_of_... |
export a graph to CSV for simpler viewing | def export(g, csv_fname):
""" export a graph to CSV for simpler viewing """
with open(csv_fname, "w") as f:
num_tuples = 0
f.write('"num","subject","predicate","object"\n')
for subj, pred, obj in g:
num_tuples += 1
f.write('"' + str(num_tuples) + '",')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.