INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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
... |
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 |
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 14 goal_types. csv ... | 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... |
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 20140426 16 0 83 16 20140427 1 0 6 1 20140429 0 0 0 4 | 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. | 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. | 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. | 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. | 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 ). | 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. | 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. | 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 ). | 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. | 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. | 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. | 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. | 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 parallel. | def process_shells_parallel(self, shells):
"""Processing a list of shells parallel."""
output = []
success = True
with closing(multiprocessing.Pool(multiprocessing.cpu_count())) as pool:
for result in [Adapter(entry) for entry in pool.map(worker, [shell for shell in shells])]... |
Processing a list of shells one after the other. | def process_shells_ordered(self, shells):
"""Processing a list of shells one after the other."""
output = []
for shell in shells:
entry = shell['entry']
config = ShellConfig(script=entry['script'], title=entry['title'] if 'title' in entry else '',
... |
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 ... |
Processing a shell entry. | def process_shell(self, creator, entry, config):
"""Processing a shell entry."""
self.logger.info("Processing Bash code: start")
output = []
shell = creator(entry, config)
for line in shell.process():
output.append(line)
self.logger.info(" | %s", line)
... |
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)})
... |
Saving output for configured variable name. | def __handle_variable(self, shell_entry, output):
"""
Saving output for configured variable name.
Args:
shell_entry(dict): shell based configuration (shell, docker container or Python).
output: list of strings representing output of last shell
"""
if 'var... |
This is the main body of the process that does the work. | 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_... |
Creates the environment Code in Base class = self. log. record_process ( enviroment. py Creating environment - + self. name ) | def create(self, num_sites):
"""
Creates the environment
Code in Base class = self.log.record_process('enviroment.py', 'Creating environment - ' + self.name)
"""
super(Internet, self).create(num_sites)
#print('building websites')
for _ in range(0,num_sites):
... |
Removes parameters whose values are set to None. | def _clean_params(self, params):
"""Removes parameters whose values are set to None.
"""
clean_params = {}
for key, value in params.iteritems():
if value is not None:
clean_params[key] = value
return clean_params |
Returns the distance between the centroids of two catchments in kilometers. | def distance_to(self, other_catchment):
"""
Returns the distance between the centroids of two catchments in kilometers.
:param other_catchment: Catchment to calculate distance to
:type other_catchment: :class:`.Catchment`
:return: Distance between the catchments in km.
:... |
Estimate the urbext2000 parameter for a given year assuming a nation - wide urbanisation curve. | def urbext(self, year):
"""
Estimate the `urbext2000` parameter for a given year assuming a nation-wide urbanisation curve.
Methodology source: eqn 5.5, report FD1919/TR
:param year: Year to provide estimate for
:type year: float
:return: Urban extent parameter
... |
Return a list of continuous data periods by removing the data gaps from the overall record. | def continuous_periods(self):
"""
Return a list of continuous data periods by removing the data gaps from the overall record.
"""
result = []
# For the first period
start_date = self.start_date
for gap in self.pot_data_gaps:
end_date = gap.start_date ... |
Adding all files from given path to the object. | 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... |
Saving stored files at a given path ( relative paths are added ). | 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... |
Convert JSON into a 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... |
delete a single file | def delete_file(f, ignore_errors=False):
"""
delete a single file
"""
try:
os.remove(f)
except Exception as ex:
if ignore_errors:
return
print('ERROR deleting file ' + str(ex)) |
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) |
copy single file | def copy_file(src, dest):
"""
copy single file
"""
try:
shutil.copy2(src , dest)
except Exception as ex:
print('ERROR copying file' + str(ex)) |
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)) |
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... |
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 |')
... |
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 |
display sample data from a graph | def show_graph_summary(g):
""" display sample data from a graph """
sample_data = []
print("list(g[RDFS.Class]) = " + str(len(list(g[RDFS.Class]))))
# Get Subject Lists
num_subj = 0
for subj in g.subjects(RDF.type):
num_subj += 1
if num_subj < 5:
sample_data.append("s... |
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) + '",')
... |
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]]) |
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() ) |
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... |
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 the zip file determines compression and unzips recursively until source files are extracted | def extract_all(zipfile, dest_folder):
"""
reads the zip file, determines compression
and unzips recursively until source files
are extracted
"""
z = ZipFile(zipfile)
print(z)
z.extract(dest_folder) |
add a file to the archive | def create_zip_from_file(zip_file, fname):
"""
add a file to the archive
"""
with zipfile.ZipFile(zip_file, 'w') as myzip:
myzip.write(fname) |
add all the files from the folder fldr to the archive | def create_zip_from_folder(zip_file, fldr, mode="r"):
"""
add all the files from the folder fldr
to the archive
"""
#print('zip from folder - adding folder : ', fldr)
zipf = zipfile.ZipFile(zip_file, 'w')
for root, dirs, files in os.walk(fldr):
for file in files:
fullname... |
unzip the file contents to the dest_folder ( create if it doesn t exist ) and then return the list of files extracted | def extract(self, dest_fldr, password=''):
"""
unzip the file contents to the dest_folder
(create if it doesn't exist)
and then return the list of files extracted
"""
#print('extracting to ' + dest_fldr)
if self.type == 'ZIP':
self._extract_zip(dest_fl... |
scans a directory for files like *. GZ or *. ZIP and returns the filename of the first one found ( should only be one of each file here | def get_file_named(self, fldr, xtn):
"""
scans a directory for files like *.GZ or *.ZIP and returns
the filename of the first one found (should only be one of
each file here
"""
res = [] # list of Sample objects
for root, _, files in os.walk(fldr):
... |
Acquire the: attr: lock | def acquire(self, blocking=True, timeout=-1):
"""Acquire the :attr:`lock`
Args:
blocking (bool): See :meth:`threading.Lock.acquire`
timeout (float): See :meth:`threading.Lock.acquire`
Returns:
bool: :obj:`True` if the lock was acquired, otherwise :obj:`False... |
Acquire the: attr: lock asynchronously | async def acquire_async(self):
"""Acquire the :attr:`lock` asynchronously
"""
r = self.acquire(blocking=False)
while not r:
await asyncio.sleep(.01)
r = self.acquire(blocking=False) |
Called on event emission and notifies the: meth: wait method | def trigger(self, *args, **kwargs):
"""Called on event emission and notifies the :meth:`wait` method
Called by :class:`AioEventWaiters` when the
:class:`~pydispatch.dispatch.Event` instance is dispatched.
Positional and keyword arguments are stored as instance attributes for
us... |
Add a: class: AioEventWaiter to the: attr: waiters container | async def add_waiter(self):
"""Add a :class:`AioEventWaiter` to the :attr:`waiters` container
The event loop to use for :attr:`AioEventWaiter.loop` is found in the
current context using :func:`asyncio.get_event_loop`
Returns:
waiter: The created :class:`AioEventWaiter` inst... |
Add a coroutine function | def add_method(self, loop, callback):
"""Add a coroutine function
Args:
loop: The :class:`event loop <asyncio.BaseEventLoop>` instance
on which to schedule callbacks
callback: The :term:`coroutine function` to add
"""
f, obj = get_method_vars(call... |
Iterate over stored coroutine functions | def iter_methods(self):
"""Iterate over stored coroutine functions
Yields:
Stored :term:`coroutine function` objects
.. seealso:: :meth:`pydispatch.utils.WeakMethodContainer.iter_instances`
"""
for wrkey, obj in self.iter_instances():
f, obj_id = wrkey
... |
Schedule and await a coroutine on the specified loop | def submit_coroutine(self, coro, loop):
"""Schedule and await a coroutine on the specified loop
The coroutine is wrapped and scheduled using
:func:`asyncio.run_coroutine_threadsafe`. While the coroutine is
"awaited", the result is not available as method returns immediately.
Ar... |
launch a file - used for starting html pages | def launch(self):
""" launch a file - used for starting html pages """
#os.system(self.fullname) # gives permission denied seeing it needs to be chmod +x
import subprocess
try:
retcode = subprocess.call(self.fullname, shell=True)
if retcode < 0:
pr... |
delete a file don t really care if it doesn t exist | def delete(self):
""" delete a file, don't really care if it doesn't exist """
if self.fullname != "":
try:
os.remove(self.fullname)
except IOError:
print("Cant delete ",self.fullname) |
you wont believe what this method does | def count_lines_in_file(self, fname=''):
""" you wont believe what this method does """
i = 0
if fname == '':
fname = self.fullname
try:
#with open(fname, encoding="utf8") as f:
with codecs.open(fname, "r",encoding='utf8', errors='ignore') as f:
... |
counts non blank lines | def count_lines_of_code(self, fname=''):
""" counts non blank lines """
if fname == '':
fname = self.fullname
loc = 0
try:
with open(fname) as f:
for l in f:
if l.strip() != '':
loc += 1
r... |
retrieve a sample of the file | def get_file_sample(self, numLines=10):
""" retrieve a sample of the file """
res = ''
try:
with open(self.fullname, 'r') as f:
for line_num, line in enumerate(f):
res += str(line_num).zfill(5) + ' ' + line
if line_num >= numLi... |
adds a line of text to a file | def append_text(self, txt):
""" adds a line of text to a file """
with open(self.fullname, "a") as myfile:
myfile.write(txt) |
load a file to a string | def load_file_to_string(self):
""" load a file to a string """
try:
with open(self.fullname, 'r') as f:
txt = f.read()
return txt
except IOError:
return '' |
load a file to a list | def load_file_to_list(self):
""" load a file to a list """
lst = []
try:
with open(self.fullname, 'r') as f:
for line in f:
lst.append(line)
return lst
except IOError:
return lst |
get a HTML formatted view of all Python programs in all subfolders of AIKIF including imports and lists of functions and classes | def get_program_list():
"""
get a HTML formatted view of all Python programs
in all subfolders of AIKIF, including imports and
lists of functions and classes
"""
colList = ['FileName','FileSize','Functions', 'Imports']
txt = '<TABLE width=90% border=0>'
txt += format_file_table_header(c... |
extracts a displayable subfolder name from full filename | def get_subfolder(txt):
"""
extracts a displayable subfolder name from full filename
"""
root_folder = os.sep + 'aikif' + os.sep
ndx = txt.find(root_folder, 1)
return txt[ndx:].replace('__init__.py', '') |
get a list of functions from a Python program | def get_functions(fname):
""" get a list of functions from a Python program """
txt = ''
with open(fname, 'r') as f:
for line in f:
if line.strip()[0:4] == 'def ':
txt += '<PRE>' + strip_text_after_string(strip_text_after_string(line, '#')[4:], ':') + '</PRE>\n'
... |
used to strip any poorly documented comments at the end of function defs | def strip_text_after_string(txt, junk):
""" used to strip any poorly documented comments at the end of function defs """
if junk in txt:
return txt[:txt.find(junk)]
else:
return txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.