INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
use shell to bring the application with caption to front | def app_activate(caption):
"""
use shell to bring the application with caption to front
"""
try:
shell = win32com.client.Dispatch("WScript.Shell")
shell.AppActivate(caption)
except Exception as ex:
print('error calling win32com.client.Dispatch (AppActivate)') |
sends the text or keys to the active application using shell Note that the imp module shows deprecation warning. Examples: shell. SendKeys ( ^a ) # CTRL + A shell. SendKeys ( { DELETE } ) # Delete key shell. SendKeys ( hello this is a lot of text with a// ) | def send_keys(key_string):
"""
sends the text or keys to the active application using shell
Note, that the imp module shows deprecation warning.
Examples:
shell.SendKeys("^a") # CTRL+A
shell.SendKeys("{DELETE}") # Delete key
shell.SendKeys("hello this is a lot of text with a //"... |
Return a list of catchments sorted by distance to subject_catchment ** and filtered to only include catchments suitable for QMED analyses **. | def nearest_qmed_catchments(self, subject_catchment, limit=None, dist_limit=500):
"""
Return a list of catchments sorted by distance to `subject_catchment` **and filtered to only include catchments
suitable for QMED analyses**.
:param subject_catchment: catchment object to measure dista... |
Return a list of catchments sorted by hydrological similarity defined by similarity_distance_function | def most_similar_catchments(self, subject_catchment, similarity_dist_function, records_limit=500,
include_subject_catchment='auto'):
"""
Return a list of catchments sorted by hydrological similarity defined by `similarity_distance_function`
:param subject_catchme... |
Reads and parses a sam file. | def readSAM(SAMfile,header=False):
"""
Reads and parses a sam file.
:param SAMfile: /path/to/file.sam
:param header: logical, if True, reads the header information
:returns: a pandas dataframe with the respective SAM columns: 'QNAME','FLAG','RNAME','POS','MAPQ','CIGAR','RNEXT','PNEXT','TLEN','SEQ'... |
Writes a pandas dataframe with the respective SAM columns: QNAME FLAG RNAME POS MAPQ CIGAR RNEXT PNEXT TLEN SEQ QUAL into a sam file | def writeSAM(sam,SAMfile,header=None):
"""
Writes a pandas dataframe with the respective SAM columns: 'QNAME','FLAG','RNAME','POS','MAPQ','CIGAR','RNEXT','PNEXT','TLEN','SEQ','QUAL' into a sam file
:param sam: pandas dataframe to be writen
:param SAMfile: /path/to/file.sam
:returns: nothing
""... |
Explains a SAM flag. | def SAMflags(x):
"""
Explains a SAM flag.
:param x: flag
:returns: complete SAM flag explanaition
"""
flags=[]
if x & 1:
l="1: Read paired"
else:
l="0: Read unpaired"
flags.append(l)
if x & 2 :
l="1: Read mapped in proper pair"
else:
l="0: ... |
returns a string representation of the bias details | def get_bias_details(self):
"""
returns a string representation of the bias details
"""
res = 'Bias File Details\n'
for b in self.bias_details:
if len(b) > 2:
res += b[0].ljust(35)
res += b[1].ljust(35)
res += b[2].ljust... |
returns a weighting from 0 to 1 based on the sources. Due to fractions multiplying resulting in very small numbers adding 0. 5 to bias calculations which means actual range is 0. 5 - > 1. 5 ( still testing ) Note - range should be from 0 - > 1 | def _calculate_bias(self):
"""
returns a weighting from 0 to 1 based on the sources.
Due to fractions multiplying resulting in very small
numbers, adding 0.5 to bias calculations which means
actual range is 0.5 -> 1.5 (still testing)
Note - range should be from ... |
read the bias file based on the short_filename and return as a dictionary | def _read_bias_rating(self, short_filename):
"""
read the bias file based on the short_filename
and return as a dictionary
"""
res = {}
full_name = os.path.join(root_fldr, 'aikif', 'data', 'ref', short_filename)
lg.record_process('bias.py','reading ' + full_name)
... |
returns the home folder and program root depending on OS | def get_root_folder():
"""
returns the home folder and program root depending on OS
"""
locations = {
'linux':{'hme':'/home/duncan/', 'core_folder':'/home/duncan/dev/src/python/AIKIF'},
'win32':{'hme':'T:\\user\\', 'core_folder':'T:\\user\\dev\\src\\python\\AIKIF'},
'cygwin':{'hme':os.... |
read a simple text file from a private location to get username and password | def read_credentials(fname):
"""
read a simple text file from a private location to get
username and password
"""
with open(fname, 'r') as f:
username = f.readline().strip('\n')
password = f.readline().strip('\n')
return username, password |
module intended to be imported in most AIKIF utils to manage folder paths user settings etc. Modify the parameters at the top of this file to suit | def show_config():
"""
module intended to be imported in most AIKIF utils
to manage folder paths, user settings, etc.
Modify the parameters at the top of this file to suit
"""
res = ''
res += '\n---------- Folder Locations ---------\n'
for k,v in fldrs.items():
res += str(k) + ' ... |
return the matrix as a list of lists raw graph = { 1: [ 2 3 4 ] 2: [ 6 7 ] } 6 nodes: [ 1 2 3 4 6 7 ] 5 links: [[ 1 2 ] [ 1 3 ] [ 1 4 ] [ 2 6 ] [ 2 7 ]] [ 0 1 1 1 0 0 ] [ 1 0 0 0 1 1 ] [ 1 0 0 0 0 0 ] [ 1 0 0 0 0 0 ] [ 0 1 0 0 0 0 ] [ 0 1 0 0 0 0 ] | def get_adjacency_matrix(self, show_in_console=False):
""" return the matrix as a list of lists
raw graph = {'1': ['2', '3', '4'], '2': ['6', '7']}
6 nodes: ['1', '2', '3', '4', '6', '7']
5 links: [['1', '2'], ['1', '3'], ['1', '4'], ['2', '6'], ['2', '7']]
[0, 1, 1, 1, 0, 0]
... |
Selectes motifs from a meme file based on the number of sites. | def filterMotifs(memeFile,outFile, minSites):
"""
Selectes motifs from a meme file based on the number of sites.
:param memeFile: MEME file to be read
:param outFile: MEME file to be written
:param minSites: minimum number of sites each motif needs to have to be valid
:returns: nothing
"""... |
reads the file and cleans into standard text ready for parsing | def _read_file(self):
"""
reads the file and cleans into standard text ready for parsing
"""
self.raw = []
with open(self.fname, 'r') as f:
for line in f:
#print(line)
if line.startswith('#'):
pass # comment
... |
Restore the default configuration and remove the user s config file. | def reset(self):
"""
Restore the default configuration and remove the user's config file.
"""
# Delete user config file
try:
os.remove(self._user_config_file)
except FileNotFoundError:
pass
# Empty and refill the config object
for... |
Write data to user config file. | def save(self):
"""
Write data to user config file.
"""
with open(self._user_config_file, 'w', encoding='utf-8') as f:
self.write(f) |
Return UTC datetime from timestamp in config file. | def get_datetime(self, section, option, fallback):
"""
Return UTC datetime from timestamp in config file.
:param section: Config section
:param option: Config option
:param fallback: Fallback/default value
:return: Datetime in UTC
:rtype: :class:`datetime.datetim... |
Return UTC datetime from timestamp in config file. | def set_datetime(self, section, option, value):
"""
Return UTC datetime from timestamp in config file.
:param section: Config section
:param option: Config option
:param value: Datetime value to set
:type value: :class:`datetime.datetime`
"""
self[section... |
General Machine Learning Formulas Intermezzo - computing Logarithms log2 ( x ) = y < = > 2^y = x | def ml_entropy(lst):
"""
General Machine Learning Formulas
Intermezzo - computing Logarithms
log2(x) = y <=> 2^y = x
Definition of Entropy
k
E = - SUM ( p[i] log2(p[i])
i=1
where
k = possible values enumerated 1,2,...,k
p[i] = c[i] / n is... |
Read the magic file | def _magic_data(filename=os.path.join(here, 'magic_data.json')):
""" Read the magic file"""
with open(filename) as f:
data = json.load(f)
headers = [_create_puremagic(x) for x in data['headers']]
footers = [_create_puremagic(x) for x in data['footers']]
return headers, footers |
The length of the largest magic string + its offset | def _max_lengths():
""" The length of the largest magic string + its offset"""
max_header_length = max([len(x.byte_match) + x.offset
for x in magic_header_array])
max_footer_length = max([len(x.byte_match) + abs(x.offset)
for x in magic_footer_array]... |
Rough confidence based on string length and file extension | def _confidence(matches, ext=None):
""" Rough confidence based on string length and file extension"""
results = []
for match in matches:
con = (0.8 if len(match.extension) > 9 else
float("0.{0}".format(len(match.extension))))
if ext == match.extension:
con = 0.9
... |
Attempt to identify data by its magic numbers | def _identify_all(header, footer, ext=None):
""" Attempt to identify 'data' by its magic numbers"""
# Capture the length of the data
# That way we do not try to identify bytes that don't exist
matches = list()
for magic_row in magic_header_array:
start = magic_row.offset
end = magic... |
Discover what type of file it is based on the incoming string | def _magic(header, footer, mime, ext=None):
""" Discover what type of file it is based on the incoming string """
if not header:
raise ValueError("Input was empty")
info = _identify_all(header, footer, ext)[0]
if mime:
return info.mime_type
return info.extension if not \
isin... |
Grab the start and end of the file | def _file_details(filename):
""" Grab the start and end of the file"""
max_head, max_foot = _max_lengths()
with open(filename, "rb") as fin:
head = fin.read(max_head)
try:
fin.seek(-max_foot, os.SEEK_END)
except IOError:
fin.seek(0)
foot = fin.read()
... |
Scan a filename for it s extension. | def ext_from_filename(filename):
""" Scan a filename for it's extension.
:param filename: string of the filename
:return: the extension off the end (empty string if it can't find one)
"""
try:
base, ext = filename.lower().rsplit(".", 1)
except ValueError:
return ''
ext = ".{... |
Opens file attempts to identify content based off magic number and will return the file extension. If mime is True it will return the mime type instead. | def from_file(filename, mime=False):
""" Opens file, attempts to identify content based
off magic number and will return the file extension.
If mime is True it will return the mime type instead.
:param filename: path to file
:param mime: Return mime, not extension
:return: guessed extension or ... |
Reads in string attempts to identify content based off magic number and will return the file extension. If mime is True it will return the mime type instead. If filename is provided it will be used in the computation. | def from_string(string, mime=False, filename=None):
""" Reads in string, attempts to identify content based
off magic number and will return the file extension.
If mime is True it will return the mime type instead.
If filename is provided it will be used in the computation.
:param string: string re... |
Returns tuple of ( num_of_matches array_of_matches ) arranged highest confidence match first. | def magic_file(filename):
""" Returns tuple of (num_of_matches, array_of_matches)
arranged highest confidence match first.
:param filename: path to file
:return: list of possible matches, highest confidence first
"""
head, foot = _file_details(filename)
if not head:
raise ValueError... |
Returns tuple of ( num_of_matches array_of_matches ) arranged highest confidence match first If filename is provided it will be used in the computation. | def magic_string(string, filename=None):
""" Returns tuple of (num_of_matches, array_of_matches)
arranged highest confidence match first
If filename is provided it will be used in the computation.
:param string: string representation to check
:param filename: original filename
:return: list of ... |
Reads a GTF file and labels the respective columns in agreement with GTF file standards: seqname source feature start end score strand frame attribute. | def readGTF(infile):
"""
Reads a GTF file and labels the respective columns in agreement with GTF file standards:
'seqname','source','feature','start','end','score','strand','frame','attribute'.
:param infile: path/to/file.gtf
:returns: a Pandas dataframe of the respective GTF
"""
df=pd.re... |
Returns a field of choice from the attribute column of the GTF | def retrieve_GTF_field(field,gtf):
"""
Returns a field of choice from the attribute column of the GTF
:param field: field to be retrieved
:returns: a Pandas dataframe with one columns containing the field of choice
"""
inGTF=gtf.copy()
def splits(x):
l=x.split(";")
l=[ s.sp... |
List the type of attributes in a the attribute section of a GTF file | def attributesGTF(inGTF):
"""
List the type of attributes in a the attribute section of a GTF file
:param inGTF: GTF dataframe to be analysed
:returns: a list of attributes present in the attribute section
"""
df=pd.DataFrame(inGTF['attribute'].str.split(";").tolist())
desc=[]
for i in... |
Reads an extracts all attributes in the attributes section of a GTF and constructs a new dataframe wiht one collumn per attribute instead of the attributes column | def parseGTF(inGTF):
"""
Reads an extracts all attributes in the attributes section of a GTF and constructs a new dataframe wiht one collumn per attribute instead of the attributes column
:param inGTF: GTF dataframe to be parsed
:returns: a dataframe of the orignal input GTF with attributes parsed.
... |
Write a GTF dataframe into a file | def writeGTF(inGTF,file_path):
"""
Write a GTF dataframe into a file
:param inGTF: GTF dataframe to be written. It should either have 9 columns with the last one being the "attributes" section or more than 9 columns where all columns after the 8th will be colapsed into one.
:param file_path: path/to/th... |
Transform a GTF dataframe into a bed dataframe | def GTFtoBED(inGTF,name):
"""
Transform a GTF dataframe into a bed dataframe
:param inGTF: GTF dataframe for transformation
:param name: field of the GTF data frame to be use for the bed 'name' positon
returns: a bed dataframe with the corresponding bed fiels: 'chrom','chromStart','chromEnd','name... |
Gets all positions of all bases in an exon | def MAPGenoToTrans(parsedGTF,feature):
"""
Gets all positions of all bases in an exon
:param df: a Pandas dataframe with 'start','end', and 'strand' information for each entry.
df must contain 'seqname','feature','start','end','strand','frame','gene_id',
'transcript_id','exo... |
Maps a genome position to transcript positon | def GetTransPosition(df,field,dic,refCol="transcript_id"):
"""
Maps a genome position to transcript positon"
:param df: a Pandas dataframe
:param field: the head of the column containing the genomic position
:param dic: a dictionary containing for each transcript the respective bases eg. {ENST23923... |
download a file from a public website with no logon required output = open ( filename wb ) output. write ( request. urlopen ( url ). read () ) output. close () | def download_file_no_logon(url, filename):
"""
download a file from a public website with no logon required
output = open(filename,'wb')
output.write(request.urlopen(url).read())
output.close()
"""
import urllib.request
#url = "http://www.google.com/"
request = urllib.reques... |
having problems with urllib on a specific site so trying requests | def get_protected_page(url, user, pwd, filename):
"""
having problems with urllib on a specific site so trying requests
"""
import requests
r = requests.get(url, auth=(user, pwd))
print(r.status_code)
if r.status_code == 200:
print('success')
with open(filename, 'wb') as fd:
... |
Currently not working... # https:// docs. python. org/ 3/ library/ urllib. request. html#examples # Create an OpenerDirector with support for Basic HTTP Authentication... | def download_file(p_realm, p_url, p_op_file, p_username, p_password):
"""
Currently not working...
# https://docs.python.org/3/library/urllib.request.html#examples
# Create an OpenerDirector with support for Basic HTTP Authentication...
"""
auth_handler = urllib.request.HTTPBasicAuthHandler()
... |
Currently fails behind proxy... # https:// docs. python. org/ 3/ library/ urllib. request. html#examples | def download_file_proxy(p_url, p_op_file, p_username, p_password, proxies):
"""
Currently fails behind proxy...
# https://docs.python.org/3/library/urllib.request.html#examples
"""
chunk_size=4096
import requests
r = requests.get(p_url, auth=(p_username, p_password), proxies=proxies)
#pr... |
parse the rawFilesTable. txt file into a pandas dataframe | def read_rawFilesTable(filename):
"""parse the 'rawFilesTable.txt' file into a pandas dataframe"""
exp = pd.read_table(filename)
expected_columns = {'File', 'Exists', 'Size', 'Data format', 'Parameter group', 'Experiment', 'Fraction'}
found_columns = set(exp.columns)
if len(expected_columns - found_... |
Add an instance method or function | def add_method(self, m, **kwargs):
"""Add an instance method or function
Args:
m: The instance method or function to store
"""
if isinstance(m, types.FunctionType):
self['function', id(m)] = m
else:
f, obj = get_method_vars(m)
wrke... |
Remove an instance method or function if it exists | def del_method(self, m):
"""Remove an instance method or function if it exists
Args:
m: The instance method or function to remove
"""
if isinstance(m, types.FunctionType) and not iscoroutinefunction(m):
wrkey = ('function', id(m))
else:
f, obj... |
Remove any stored instance methods that belong to an object | def del_instance(self, obj):
"""Remove any stored instance methods that belong to an object
Args:
obj: The instance object to remove
"""
to_remove = set()
for wrkey, _obj in self.iter_instances():
if obj is _obj:
to_remove.add(wrkey)
... |
Iterate over the stored objects | def iter_instances(self):
"""Iterate over the stored objects
Yields:
wrkey: The two-tuple key used to store the object
obj: The instance or function object
"""
for wrkey in set(self.keys()):
obj = self.get(wrkey)
if obj is None:
... |
Iterate over stored functions and instance methods | def iter_methods(self):
"""Iterate over stored functions and instance methods
Yields:
Instance methods or function objects
"""
for wrkey, obj in self.iter_instances():
f, obj_id = wrkey
if f == 'function':
yield self[wrkey]
... |
reads the subject file to a list to confirm config is setup | def load_data_subject_areas(subject_file):
"""
reads the subject file to a list, to confirm config is setup
"""
lst = []
if os.path.exists(subject_file):
with open(subject_file, 'r') as f:
for line in f:
lst.append(line.strip())
else:
print('MISSING DA... |
reads the ontology yaml file and does basic verifcation | def check_ontology(fname):
"""
reads the ontology yaml file and does basic verifcation
"""
with open(fname, 'r') as stream:
y = yaml.safe_load(stream)
import pprint
pprint.pprint(y) |
top level function used for new data processing which attempts to find a level in a heirarchy and return the key and filename usage res = FindOntology ( file ) # returns SYSTEM - PC - FILE | def find_ontology(self, txt):
"""
top level function used for new data processing which attempts
to find a level in a heirarchy and return the key and filename
usage res = FindOntology('file') # returns 'SYSTEM-PC-FILE'
"""
totFound = 0
searchString = txt.upper()... |
top level function used to simply return the ONE ACTUAL string used for data types | def find_type(self, txt):
"""
top level function used to simply return the
ONE ACTUAL string used for data types
"""
searchString = txt.upper()
match = 'Unknown'
for i in self.lst_type:
if searchString in i:
match = i
return ma... |
returns the file based on dataType and subjectArea | def get_full_filename(self, dataType, subjectArea):
"""
returns the file based on dataType and subjectArea
"""
return dataPath + os.sep + 'core' + os.sep + dataType + '_' + subjectArea + '.CSV' |
Parses a database URL in this format: [ database type ]:// [ username ]: [ password ] @ [ host ]: [ port ]/ [ database name ] | def parse(url):
"""
Parses a database URL in this format:
[database type]://[username]:[password]@[host]:[port]/[database name]
or, for cloud SQL:
[database type]://[username]:[password]@[project_id]:[instance_name]/[database name]
"""
config = {}
url = urlparse.urlparse(url)
# Re... |
Get a logger by name. | def get_logger(name):
"""Get a logger by name."""
if name is None:
return NoLogger()
logger = logging.getLogger(name)
if Logger.use_external_configuration:
logger.propagate = False
return logger |
read the list of thoughts from a text file | def load_plan(self, fname):
""" read the list of thoughts from a text file """
with open(fname, "r") as f:
for line in f:
if line != '':
tpe, txt = self.parse_plan_from_string(line)
#print('tpe= "' + tpe + '"', txt)
... |
adds a constraint for the plan | def add_constraint(self, name, tpe, val):
"""
adds a constraint for the plan
"""
self.constraint.append([name, tpe, val]) |
calculates basic stats on the MapRule elements of the maps to give a quick overview. | def get_maps_stats(self):
"""
calculates basic stats on the MapRule elements of the maps
to give a quick overview.
"""
tpes = {}
for m in self.maps:
if m.tpe in tpes:
tpes[m.tpe] += 1
else:
tpes[m.tpe] = 1
re... |
load the rules from file | def load_rules(self):
"""
load the rules from file
"""
self.maps = []
with open(self.map_file, 'r') as f:
for line in f:
if line.strip(' ')[0:1] != '#':
rule = MapRule(line)
#print('rule = ', rule)
... |
save the rules to file after web updates or program changes | def save_rules(self, op_file):
"""
save the rules to file after web updates or program changes
"""
with open(op_file, 'w') as f:
for m in self.maps:
f.write(m.format_for_file_output()) |
takes the filename to be read and uses the maps setup on class instantiation to process the file. This is a top level function and uses self. maps which should be the column descriptions ( in order ). | def process_raw_file(self, raw_file_name, field_names):
"""
takes the filename to be read and uses the maps setup
on class instantiation to process the file.
This is a top level function and uses self.maps which
should be the column descriptions (in order).
"""
... |
function to decide how to process the raw data ( which can be any format ). Note - not 100% sure how this will be implemented should we pass the filename ( currently takes a line ) | def identify_data(self, tpe, raw_data):
"""
function to decide how to process
the raw data (which can be any format).
Note - not 100% sure how this will be implemented
should we pass the filename (currently takes a line)
"""
num_applicable_rules = 0
forma... |
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. | 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. | 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. | 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. | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.