INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Returns the 1 - based index of the last object on this page relative to total objects found ( hits ). | def end_index(self):
"""
Returns the 1-based index of the last object on this page,
relative to total objects found (hits).
"""
return ((self.number - 1) * self.paginator.per_page +
len(self.object_list)) |
Returns a Page object for the given 1 - based page number. | def page(self, number):
"""
Returns a Page object for the given 1-based page number.
"""
number = self.validate_number(number)
# remove the extra item(s) when creating the page
page_items = self.object_list[:self.per_page]
return FinitePage(page_items, number, sel... |
Checks for one more item than last on this page. | def has_next(self):
"""
Checks for one more item than last on this page.
"""
try:
next_item = self.paginator.object_list[self.paginator.per_page]
except IndexError:
return False
return True |
extracts names from the node to get counts of miss + cann on both sides | def parse_miss_cann(node, m, c):
"""
extracts names from the node to get
counts of miss + cann on both sides
"""
if node[2]:
m1 = node[0]
m2 = m-node[0]
c1 = node[1]
c2 = c-node[1]
else:
m1=m-node[0]
m2=node[0]
c1=c-node[1]
c2=node... |
based on current situation pick who gets transported next and return the path NOTE - improvement here as there are often duplicate paths or backtracking e. g. | def pick_next_boat_trip(node, m, c, frontier):
"""
based on current situation, pick who
gets transported next, and return the path
NOTE - improvement here as there are often
duplicate paths or backtracking, e.g.
"""
next_path = []
cur_path = []
boat, mult = boat_on_left_bank(node)
... |
run the algorithm to find the path list | def solve(m,c):
"""
run the algorithm to find the path list
"""
G={ (m,c,1):[] }
frontier=[ (m,c,1) ] # 1 as boat starts on left bank
while len(frontier) > 0:
hold=list(frontier)
for node in hold:
newnode=[]
frontier.remove(node)
newnode.exte... |
takes the list of columns as a string ( via SELECT statement in DB ) and produces a lst of columns | def get_column_list_from_select(self, txt, col_delim=','):
"""
takes the list of columns as a string (via SELECT statement in DB)
and produces a lst of columns
"""
return [c.strip().strip(',') for c in txt.split(col_delim)] |
appends the CREATE TABLE index etc to self. ddl_text | def create_script_fact(self):
"""
appends the CREATE TABLE, index etc to self.ddl_text
"""
self.ddl_text += '---------------------------------------------\n'
self.ddl_text += '-- CREATE Fact Table - ' + self.fact_table + '\n'
self.ddl_text += '----------------------------... |
appends the CREATE TABLE index etc to another table | def create_script_staging_table(self, output_table, col_list):
"""
appends the CREATE TABLE, index etc to another table
"""
self.ddl_text += '---------------------------------------------\n'
self.ddl_text += '-- CREATE Staging Table - ' + output_table + '\n'
self.ddl_text... |
For each column in the piv_list append ALL from_column s using the group_list e. g. Input Table YEAR Person Q1 Q2 2010 Fred Spain 14 2010 Jane Spain 13. 995 Output Table Year Person Question Result 2010 Fred Q1 Spain 2010 Fred Q2 14 2010 Jane Q1 Spain 2010 Jane Q2 13. 995 You would use: from_column = [ YEAR Person ] pi... | def reverse_pivot_to_fact(self, staging_table, piv_column, piv_list, from_column, meas_names, meas_values, new_line):
"""
For each column in the piv_list, append ALL from_column's using the group_list
e.g.
Input Table
YEAR Person Q1 Q2
2010 Fre... |
generate SQL to insert staging table records into the core table based on column_list ( If no column list then insert sequentially ) | def populate_from_staging(self, staging_table, from_column_list, output_table):
"""
generate SQL to insert staging table records into
the core table based on column_list (If no column list
then insert sequentially)
"""
self.sql_text += 'INSERT INTO ' + output_table + ' (... |
simply updates all rows and sets COL to NEW_VAL where col = old_val e. g. update_old_to_new ( NAME The University of Adelaide University of Adelaide ) will generate UPDATE table op SET op. NAME = University of Adelaide WHERE op. NAME = The University of Adelaide ; | def update_old_to_new(self, col, old_val, new_val):
""" simply updates all rows and sets COL to NEW_VAL where col = old_val
e.g. update_old_to_new("NAME", "The University of Adelaide", "University of Adelaide")
will generate
UPDATE table op SET op.NAME = 'University of Adelaide' WHERE op... |
create SQL to join a fact table key based on join_col to a dimension The fact table is aliased as op and the join dimension is aliased as ip meaning you can pass substrings or SQL to match values. e. g. the command: aup. key_to_dimension ( GENDER_KEY substr ( op. GENDER 1 1 ) tbl_GENDER gender_code GENDER_KEY ) | def key_to_dimension(self, fact_key, fact_join_col, dimension_name, dimension_join_col, dimension_key):
"""
create SQL to join a fact table key based on "join_col" to a dimension
The fact table is aliased as "op" and the join dimension is aliased as "ip"
meaning you can pass substrings... |
selects the src_cols from src_table and groups by dim_grain then inserts into newly created table dim_name the columns as dim_cols | def extract_dimension(self, dim_name, dim_cols, dim_key, dim_stag_table, src_table, src_cols, grain_cols, where_clause):
"""
selects the src_cols from src_table and groups by dim_grain
then inserts into newly created table dim_name the columns as 'dim_cols
"""
self.ddl_t... |
Create an aggregate table grouped by col showing meas The meas is something like sum ( in ) or count ( * ) RETURNS: DROP TABLE C_AGG_PRODUCT ; CREATE TABLE C_AGG_PRODUCT AS ( SELECT PRODUCT sum ( AMOUNT ) AS result FROM C_SALES GROUP BY PRODUCT ) ; | def aggregate(self, opTable, group_by_cols, meas):
"""
Create an aggregate table grouped by col showing meas
The meas is something like "sum(in)" or "count(*)"
RETURNS:
DROP TABLE C_AGG_PRODUCT;
CREATE TABLE C_AGG_PRODUCT AS (
SELECT PRODUCT, sum(... |
for all columns check which values are not in the other table | def distinct_values(t_old, t_new):
"""
for all columns, check which values are not in
the other table
"""
res = []
res.append([' -- NOT IN check -- '])
for new_col in t_new.header:
dist_new = t_new.get_distinct_values_from_cols([new_col])
#print('NEW Distinct values for '... |
returns the web page header containing standard AIKIF top level web menu | def aikif_web_menu(cur=''):
""" returns the web page header containing standard AIKIF top level web menu """
pgeHdg = ''
pgeBlurb = ''
if cur == '':
cur = 'Home'
txt = get_header(cur) #"<div id=top_menu>"
txt += '<div id = "container">\n'
txt += ' <div id = "header">\n'
txt +=... |
This generates the research document based on the results of the various programs and includes RST imports for introduction and summary | def main():
"""
This generates the research document based on the results of
the various programs and includes RST imports for introduction
and summary
"""
print("Generating research notes...")
if os.path.exists(fname):
os.remove(fname)
append_rst('===============================... |
returns a list of records containing text | def find(self, txt):
"""
returns a list of records containing text
"""
result = []
for d in self.data:
if txt in d:
result.append(d)
return result |
Schema for data in CollectorUpdate. | def schema_complete():
"""Schema for data in CollectorUpdate."""
return Schema({
'stage': And(str, len),
'timestamp': int,
'status': And(str, lambda s: s in ['started', 'succeeded', 'failed']),
# optional matrix
Optional('matrix', default='defa... |
Schema for event items. | def schema_event_items():
"""Schema for event items."""
return {
'timestamp': And(int, lambda n: n > 0),
Optional('information', default={}): {
Optional(Regex(r'([a-z][_a-z]*)')): object
}
} |
Schema for data in CollectorStage. | def schema_complete():
"""Schema for data in CollectorStage."""
return Schema({
'stage': And(str, len),
'status': And(str, lambda s: s in ['started', 'succeeded', 'failed']),
Optional('events', default=[]): And(len, [CollectorStage.schema_event_items()])
}) |
Add event information. | def add(self, timestamp, information):
"""
Add event information.
Args:
timestamp (int): event timestamp.
information (dict): event information.
Raises:
RuntimeError: when validation of parameters has failed.
"""
try:
item... |
Calculate how long the stage took. | def duration(self):
"""
Calculate how long the stage took.
Returns:
float: (current) duration of the stage
"""
duration = 0.0
if len(self.events) > 0:
first = datetime.fromtimestamp(self.events[0]['timestamp'])
last = datetime.fromtime... |
Number of registered stages for given matrix name. | def count_stages(self, matrix_name):
"""
Number of registered stages for given matrix name.
Parameters:
matrix_name (str): name of the matrix
Returns:
int: number of reported stages for given matrix name.
"""
return len(self.data[matrix_name]) if... |
Get Stage of a concrete matrix. | def get_stage(self, matrix_name, stage_name):
"""
Get Stage of a concrete matrix.
Attributes:
matrix_name (str): name of the matrix
stage_name (str): name of the stage.
Returns:
CollectorStage: when stage has been found or None.
"""
f... |
Get duration for a concrete matrix. | def get_duration(self, matrix_name):
"""
Get duration for a concrete matrix.
Args:
matrix_name (str): name of the Matrix.
Returns:
float: duration of concrete matrix in seconds.
"""
duration = 0.0
if matrix_name in self.data:
... |
Add a collector item. | def update(self, item):
"""
Add a collector item.
Args:
item (CollectorUpdate): event data like stage, timestampe and status.
"""
if item.matrix not in self.data:
self.data[item.matrix] = []
result = Select(self.data[item.matrix]).where(
... |
Collector main loop. | def run(self):
"""Collector main loop."""
while True:
data = self.queue.get()
if data is None:
Logger.get_logger(__name__).info("Stopping collector process ...")
break
# updating the report data
self.store.update(data)
... |
view a text file ( map ) in high resolution | def display_map(fname):
"""
view a text file (map) in high resolution
"""
print("viewing ", fname)
wrld = read_map(fname)
for row in wrld:
#for col in row:
print(row)
app = gui_view_tk(None)
app.add_file(fname)
app.show_grid_from_file(fname)
app.title('Map Vi... |
reads a saved text file to list | def read_map(fname):
"""
reads a saved text file to list
"""
lst = []
with open(fname, "r") as f:
for line in f:
lst.append(line)
return lst |
reads a saved grid file and paints it on the canvas | def show_grid_from_file(self, fname):
"""
reads a saved grid file and paints it on the canvas
"""
with open(fname, "r") as f:
for y, row in enumerate(f):
for x, val in enumerate(row):
self.draw_cell(y, x, val) |
draw a cell as position row col containing val | def draw_cell(self, row, col, val):
"""
draw a cell as position row, col containing val
"""
if val == 'T':
self.paint_target(row,col)
elif val == '#':
self.paint_block(row,col)
elif val == 'X':
self.paint_hill(row,col)
elif val ... |
prints a block packing out around the y/ x location with pixels up to cell width and cell height | def put_standard_block(self, y, x, val):
"""
prints a block, packing out around the y/x location
with pixels up to cell width and cell height
"""
for j in range(0,self.cell_height):
for i in range(0,self.cell_width):
self.img.put(val, (x*self.cell_widt... |
paint an agent trail as ONE pixel to allow for multiple agent trails to be seen in the same cell | def paint_agent_trail(self, y, x, val):
"""
paint an agent trail as ONE pixel to allow for multiple agent
trails to be seen in the same cell
"""
for j in range(1,self.cell_height-1):
for i in range(1,self.cell_width-1):
self.img.put(self.agent_color(va... |
gets a colour for agent 0 - 9 | def agent_color(self, val):
"""
gets a colour for agent 0 - 9
"""
if val == '0':
colour = 'blue'
elif val == '1':
colour = 'navy'
elif val == '2':
colour = 'firebrick'
elif val == '3':
colour = 'blue'
elif v... |
create a list of people with randomly generated names and stats | def create_random_population(num=100):
"""
create a list of people with randomly generated names and stats
"""
people = []
for _ in range(num):
nme = 'blah'
tax_min = random.randint(1,40)/100
tax_max = tax_min + random.randint(1,40)/100
tradition = random.randint(1,10... |
Run cleanup script of pipeline when hook is configured. | def cleanup(self):
"""Run cleanup script of pipeline when hook is configured."""
if self.data.hooks and len(self.data.hooks.cleanup) > 0:
env = self.data.env_list[0].copy()
env.update({'PIPELINE_RESULT': 'SUCCESS', 'PIPELINE_SHELL_EXIT_CODE': '0'})
config = ShellConfi... |
Processing the whole pipeline definition. | def process(self, pipeline):
"""Processing the whole pipeline definition."""
output = []
for entry in pipeline:
key = list(entry.keys())[0]
# an environment block can be repeated
if key == "env":
self.data.env_list[0].update(entry[key])
... |
TODO docstrings | def collect_dependency_paths(package_name):
"""
TODO docstrings
"""
deps = []
try:
dist = pkg_resources.get_distribution(package_name)
except (pkg_resources.DistributionNotFound, ValueError):
message = "Distribution '{}' not found.".format(package_name)
raise RequirementN... |
TODO docstrings | def parse_requirements_file(req_file):
"""
TODO docstrings
"""
lines = []
for line in req_file.readlines():
line = line.strip()
if not line or line.startswith('#'):
continue
lines.append(line)
return lines |
TODO docstrings | def make_simlinks(dest_dir, paths_list):
"""
TODO docstrings
"""
for path in paths_list:
dest = os.path.join(dest_dir, os.path.split(path)[-1])
if os.path.exists(dest):
if os.path.islink(dest):
os.remove(dest)
else:
sys.stderr.write... |
Takes a raw user input initially from command line Later: - check user credentials - rate bias - check for malicious commands | def get_command(self, mode, txt=''):
"""
Takes a raw user input, initially from command line
Later:
- check user credentials
- rate bias
- check for malicious commands
"""
if mode == 'COMMAND':
self.prompt = '> '
elif mode ... |
Output the data to the current device ( usually screen via print statements but can be file or network/ API | def show_output(self, txt, device='Console'):
"""
Output the data to the current device (usually
screen via print statements but can be file or
network / API
"""
if device == 'Console':
print(txt)
elif device == 'File':
raise ('show_output ... |
Top level function to process the command mainly depending on mode. This should work by using the function name defined in all_commamnds | def process(self, txt, mode):
"""
Top level function to process the command, mainly
depending on mode.
This should work by using the function name defined
in all_commamnds
"""
result = ''
if mode == 'ADD': # already in add mode, so add data
if... |
Enter add mode - all text entered now will be processed as adding information until cancelled | def cmd_add(self, txt):
"""
Enter add mode - all text entered now will be
processed as adding information until cancelled
"""
self.show_output('Adding ', txt)
self.raw.add(txt)
print(self.raw)
return 'Added ' + txt |
search and query the AIKIF | def cmd_query(self, txt):
"""
search and query the AIKIF
"""
self.show_output('Searching for ', txt)
res = self.raw.find(txt)
for d in res:
self.show_output(d)
return str(len(res)) + ' results for ' + txt |
shapefilename: considera nomenclatura de shapefile do IBGE para determinar se é UF ou Municípios. ex. 55UF2500GC_SIR. shp para UF e 55MU2500GC_SIR. shp para Municípios srid: 4674 ( Projeção SIRGAS 2000 ) | def convert_shapefile(shapefilename, srid=4674):
"""
shapefilename: considera nomenclatura de shapefile do IBGE para determinar se é UF
ou Municípios.
ex. 55UF2500GC_SIR.shp para UF e 55MU2500GC_SIR.shp para Municípios
srid: 4674 (Projeção SIRGAS 2000)
"""
# /ho... |
Verifies that all required functions been injected. | def verify_integrity(self):
"""Verifies that all required functions been injected."""
if not self.__integrity_check:
if not self.__appid:
raise Exception('U2F_APPID was not defined! Please define it in configuration file.')
if self.__facets_enabled and not len(se... |
Enrollment function | def enroll(self):
"""Enrollment function"""
self.verify_integrity()
if session.get('u2f_enroll_authorized', False):
if request.method == 'GET':
return jsonify(self.get_enroll()), 200
elif request.method == 'POST':
response = self.verify_e... |
Signature function | def sign(self):
"""Signature function"""
self.verify_integrity()
if session.get('u2f_sign_required', False):
if request.method == 'GET':
response = self.get_signature_challenge()
if response['status'] == 'ok':
return jsoni... |
Manages users enrolled u2f devices | def devices(self):
"""Manages users enrolled u2f devices"""
self.verify_integrity()
if session.get('u2f_device_management_authorized', False):
if request.method == 'GET':
return jsonify(self.get_devices()), 200
elif request.method == 'DELETE':
... |
Provides facets support. REQUIRES VALID HTTPS! | def facets(self):
"""Provides facets support. REQUIRES VALID HTTPS!"""
self.verify_integrity()
if self.__facets_enabled:
data = json.dumps({
'trustedFacets' : [{
'version': { 'major': 1, 'minor' : 0 },
'ids': self.__facets_list... |
Returns new enroll seed | def get_enroll(self):
"""Returns new enroll seed"""
devices = [DeviceRegistration.wrap(device) for device in self.__get_u2f_devices()]
enroll = start_register(self.__appid, devices)
enroll['status'] = 'ok'
session['_u2f_enroll_'] = enroll.json
return enroll |
Verifies and saves U2F enroll | def verify_enroll(self, response):
"""Verifies and saves U2F enroll"""
seed = session.pop('_u2f_enroll_')
try:
new_device, cert = complete_register(seed, response, self.__facets_list)
except Exception as e:
if self.__call_fail_enroll:
self.__call_... |
Returns new signature challenge | def get_signature_challenge(self):
"""Returns new signature challenge"""
devices = [DeviceRegistration.wrap(device) for device in self.__get_u2f_devices()]
if devices == []:
return {
'status' : 'failed',
'error' : 'No devices been associated with t... |
Verifies signature | def verify_signature(self, signature):
"""Verifies signature"""
devices = [DeviceRegistration.wrap(device) for device in self.__get_u2f_devices()]
challenge = session.pop('_u2f_challenge_')
try:
counter, touch = verify_authenticate(devices, challenge, signature, self.__fa... |
Removes device specified by id | def remove_device(self, request):
"""Removes device specified by id"""
devices = self.__get_u2f_devices()
for i in range(len(devices)):
if devices[i]['keyHandle'] == request['id']:
del devices[i]
self.__save_u2f_devices(devices)
... |
Verifies that counter value is greater than previous signature | def verify_counter(self, signature, counter):
""" Verifies that counter value is greater than previous signature"""
devices = self.__get_u2f_devices()
for device in devices:
# Searching for specific keyhandle
if device['keyHandle'] == signature['keyHandle']:
... |
Validate data against the schema. | def validate(data):
"""
Validate data against the schema.
Args:
data(dict): data structure to validate.
Returns:
dict: data as provided and defaults where defined in schema.
"""
try:
return Schema(Validator.SCHEMA).validate(data)
... |
Include the defined yaml file. | def include(self, node):
"""Include the defined yaml file."""
result = None
if isinstance(node, ScalarNode):
result = Loader.include_file(self.construct_scalar(node))
else:
raise RuntimeError("Not supported !include on type %s" % type(node))
return result |
Load another yaml file ( no recursion ). | def include_file(filename):
"""Load another yaml file (no recursion)."""
if os.path.isfile(filename):
with open(filename) as handle:
return safe_load(handle)
raise RuntimeError("Include file %s doesn't exist!" % filename) |
Load yaml file with specific include loader. | def load(filename):
""""Load yaml file with specific include loader."""
if os.path.isfile(filename):
with open(filename) as handle:
return yaml_load(handle, Loader=Loader) # nosec
raise RuntimeError("File %s doesn't exist!" % filename) |
This is an example of project documentation using AIKIF It documents the project itself including requirements design test goals | def main():
"""
This is an example of project documentation using AIKIF
It documents the project itself, including requirements,
design, test, goals,
"""
print('Initialising AIKIF Project...')
name = 'AIKIF'
type = 'Software'
desc = """
Artificial Intelligence Knowledge I... |
transposes rows and columns | def pivot(self):
"""
transposes rows and columns
"""
self.op_data = [list(i) for i in zip(*self.ip_data)] |
convert list to key value pairs This should also create unique id s to allow for any dataset to be transposed and then later manipulated r1c1 r1c2 r1c3 r2c1 r2c2 r2c3 should be converted to ID COLNUM VAL r1c1 | def key_value_pairs(self):
"""
convert list to key value pairs
This should also create unique id's to allow for any
dataset to be transposed, and then later manipulated
r1c1,r1c2,r1c3
r2c1,r2c2,r2c3
should be converted to
ID COLNUM VAL... |
This takes a table of data conaining a person identifier ( Name or ID ) and returns a table showing all links based on a common column Ip table Links by Location Links by Job NAME Location Job John Perth Plumber Location Perth John Fred Job Farmer Mary Jane Mary Burra Farmer Location Perth John Cindy Jane Darwin Farmer... | def data_to_links(self, id_col_num, link_col_num, include_links_self='Y'):
"""
This takes a table of data conaining a person identifier (Name or ID)
and returns a table showing all links based on a common column
Ip table Links by Location Links by Job
NAME Lo... |
This is the reverse of data_to_links and takes a links table and generates a data table as follows Input Table Output Table Cat_Name CAT_val Person_a person_b NAME Location Location Perth John Fred John Perth Location Perth John Cindy Cindy Perth Location Perth Fred Cindy Fred Perth | def links_to_data(self, col_name_col_num, col_val_col_num, id_a_col_num, id_b_col_num):
"""
This is the reverse of data_to_links and takes a links table and
generates a data table as follows
Input Table Output Table
Cat_Name,CAT_val,Person_a,person_b NAM... |
try each strategy with different amounts | def find_best_plan(self):
"""
try each strategy with different amounts
"""
for plan in self.plans:
for strat in self.strategy:
self.run_plan(plan, strat) |
loads previously exported CSV file to redis database | def load_data(fname):
""" loads previously exported CSV file to redis database """
print('Loading ' + fname + ' to redis')
r = redis.StrictRedis(host = '127.0.0.1', port = 6379, db = 0);
with open(fname, 'r') as f:
for line_num, row in enumerate(f):
if row.strip('') != '':
... |
takes a row from an n3 file and returns the triple NOTE - currently parses a CSV line already split via cyc_extract. py | def parse_n3(row, src='csv'):
"""
takes a row from an n3 file and returns the triple
NOTE - currently parses a CSV line already split via
cyc_extract.py
"""
if row.strip() == '':
return '',''
l_root = 'opencyc'
key = ''
val = ''
if src == 'csv':
cols = row.split... |
takes a large data file and produces a HTML summary as html | def summarise_file_as_html(fname):
"""
takes a large data file and produces a HTML summary as html
"""
txt = '<H1>' + fname + '</H1>'
num_lines = 0
print('Reading OpenCyc file - ', fname)
with open(ip_folder + os.sep + fname, 'r') as f:
txt += '<PRE>'
for line in f:
... |
Example to show AIKIF logging of results. Generates a sequence of random grids and runs the Game of Life saving results | def main():
"""
Example to show AIKIF logging of results.
Generates a sequence of random grids and runs the
Game of Life, saving results
"""
iterations = 9 # how many simulations to run
years = 3 # how many times to run each simulation
width = 22 # grid height
... |
run a single game of life for years and log start and end living cells to aikif | def run_game_of_life(years, width, height, time_delay, silent="N"):
"""
run a single game of life for 'years' and log start and
end living cells to aikif
"""
lfe = mod_grid.GameOfLife(width, height, ['.', 'x'], 1)
set_random_starting_grid(lfe)
lg.record_source(lfe, 'game_of_life_console.py'... |
generate a random grid for game of life using a set of patterns ( just to make it interesting ) | def set_random_starting_grid(lfe):
"""
generate a random grid for game of life using a
set of patterns (just to make it interesting)
"""
cls_patterns = mod_grid.GameOfLifePatterns(25)
print(cls_patterns)
exit(0)
patterns = cls_patterns.get_patterns()
for pattern in patterns:
... |
allows display of a game of life on a console via resetting cursor position to a set point - looks ok for testing but not production quality. | def print_there(x, y, text):
""""
allows display of a game of life on a console via
resetting cursor position to a set point - looks 'ok'
for testing but not production quality.
"""
sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text))
sys.stdout.flush() |
takes a blob of text and finds delimiter OR guesses the column positions to parse into a table. input: txt = blob of text lines separated by \ n output: res = table of text | def parse_text_to_table(txt):
"""
takes a blob of text and finds delimiter OR guesses
the column positions to parse into a table.
input: txt = blob of text, lines separated by \n
output: res = table of text
"""
res = [] # resulting table
delim = identify_delim(txt)
print('txt to pars... |
assume no delimiter in this file so guess the best fixed column widths to split by | def identify_col_pos(txt):
"""
assume no delimiter in this file, so guess the best
fixed column widths to split by
"""
res = []
#res.append(0)
lines = txt.split('\n')
prev_ch = ''
for col_pos, ch in enumerate(lines[0]):
if _is_white_space(ch) is False and _is_white_space(prev_ch) is True:
res.a... |
read a CSV file to list without worrying about odd characters | def load_tbl_from_csv(fname):
"""
read a CSV file to list without worrying about odd characters
"""
import csv
rows_to_load = []
with open(fname, 'r', encoding='cp1252', errors='ignore') as csvfile:
csvreader = csv.reader(csvfile, delimiter = ',' )
reader = csv.reader(csvfile)
rows_to_load ... |
reads the characters in txt and returns a dictionary of all letters | def _get_dict_char_count(txt):
"""
reads the characters in txt and returns a dictionary
of all letters
"""
dct = {}
for letter in txt:
if letter in dct:
dct[letter] += 1
else:
dct[letter] = 1
return dct |
identifies delimiters and returns a count by ROW in the text file as well as the delimiter value ( if any ) The delim is determined if the count of delims is consistant in all rows. | def identify_delim(txt):
"""
identifies delimiters and returns a count by ROW
in the text file as well as the delimiter value (if any)
The delim is determined if the count of delims is consistant
in all rows.
"""
possible_delims = _get_dict_char_count(txt) # {'C': 3, 'a': 4, 'b': 5, 'c': 6, ',': 6, 'A': ... |
takes a string and truncates to standard form for data matching. Based on the spec at OpenRefine https:// github. com/ OpenRefine/ OpenRefine/ wiki/ Clustering - In - Depth#fingerprint - remove leading and trailing whitespace - change all characters to their lowercase representation - remove all punctuation and control... | def fingerprint(txt):
"""
takes a string and truncates to standard form for data matching.
Based on the spec at OpenRefine
https://github.com/OpenRefine/OpenRefine/wiki/Clustering-In-Depth#fingerprint
- remove leading and trailing whitespace
- change all characters to their lowercase representation
- remo... |
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({'PIPELINE_BASH_FILE_ORIGINAL': filename})
filename = os.path.join('/root/scripts', os.path.basename(filename))
self.env.update({'PIPELINE_BASH_... |
Creator function for creating an instance of a Bash. | def creator(entry, config):
"""Creator function for creating an instance of a Bash."""
template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')
with open(template_file) as handle:
template = handle.read()
# all fields are re-rendered vi... |
Creator function for creating an instance of a Docker image script. | def creator(entry, config):
"""Creator function for creating an instance of a Docker image script."""
# writing Dockerfile
dockerfile = render(config.script, model=config.model, env=config.env,
variables=config.variables, item=config.item)
filename = "dockerfi... |
Creates the environment in your subclassed create function include the line below super (). build ( arg1 arg2 arg2... ) | def create(self, num):
"""
Creates the environment
in your subclassed create function include the line below
super().build(arg1, arg2, arg2, ...)
"""
self.log.record_process('enviroment.py', 'Creating ' + str(num) + ' environments - ' + self.name) |
Simplify redirect of stdout. | def stdout_redirector():
"""
Simplify redirect of stdout.
Taken from here: https://eli.thegreenplace.net/2015/redirecting-all-kinds-of-stdout-in-python/
"""
old_stdout = sys.stdout
sys.stdout = Stream()
try:
yield sys.stdout
finally:
sys.stdout.close()
sys.stdout... |
Generating a temporary file with content. | def write_temporary_file(content, prefix='', suffix=''):
"""
Generating a temporary file with content.
Args:
content (str): file content (usually a script, Dockerfile, playbook or config file)
prefix (str): the filename starts with this prefix (default: no prefix)
suffix (str): the ... |
Prints filename of a new migration | def print_new(ctx, name, migration_type):
"""Prints filename of a new migration"""
click.echo(ctx.obj.repository.generate_migration_name(name, migration_type)) |
logs the agent details to logfile unique_name_file ( list_agents. txtlist_agents_names. txt ) = list of all instances of all agents | def _log_agent_name(self, unique_name_file):
"""
logs the agent details to logfile
unique_name_file (list_agents.txtlist_agents_names.txt) = list of all instances of all agents
"""
agt_list = os.path.join(root_fldr, 'data', unique_name_file)
if os.path.exists(agt_list):
... |
Starts an agent with standard logging | def start(self):
"""
Starts an agent with standard logging
"""
self.running = True
self.status = 'RUNNING'
self.mylog.record_process('agent', self.name + ' - starting') |
set coords of agent in an arbitrary world | def set_coords(self, x=0, y=0, z=0, t=0):
"""
set coords of agent in an arbitrary world
"""
self.coords = {}
self.coords['x'] = x
self.coords['y'] = y
self.coords['z'] = z
self.coords['t'] = t |
Load catchment object from a. CD3 or. xml file. | def from_file(file_path, incl_pot=True):
"""
Load catchment object from a ``.CD3`` or ``.xml`` file.
If there is also a corresponding ``.AM`` file (annual maximum flow data) or
a ``.PT`` file (peaks over threshold data) in the same folder as the CD3 file, these datasets will also be loaded.
:param... |
Load catchment object into the database. | def to_db(catchment, session, method='create', autocommit=False):
"""
Load catchment object into the database.
A catchment/station number (:attr:`catchment.id`) must be provided. If :attr:`method` is set to `update`, any
existing catchment in the database with the same catchment number will be updated.... |
Import an entire folder ( incl. sub - folders ) into the database | def folder_to_db(path, session, method='create', autocommit=False, incl_pot=True):
"""
Import an entire folder (incl. sub-folders) into the database
:param path: Folder location
:type path: str
:param session: database session to use, typically `floodestimation.db.Session()`
:type session: :cla... |
Retrieves all gauged catchments ( incl. catchment descriptors and annual maximum flow data ) from the National River Flow Archive and saves it to a ( sqlite ) database. | def nrfa_to_db(session, method='create', autocommit=False, incl_pot=True):
"""
Retrieves all gauged catchments (incl. catchment descriptors and annual maximum flow data) from the National River
Flow Archive and saves it to a (sqlite) database.
:param session: database session to use, typically `floodes... |
Add catchments from a user folder to the database. | def userdata_to_db(session, method='update', autocommit=False):
"""
Add catchments from a user folder to the database.
The user folder is specified in the ``config.ini`` file like this::
[import]
folder = path/to/import/folder
If this configuration key does not exist this will be sile... |
finds the window by caption and returns handle ( int ) | def get_window_by_caption(caption):
"""
finds the window by caption and returns handle (int)
"""
try:
hwnd = win32gui.FindWindow(None, caption)
return hwnd
except Exception as ex:
print('error calling win32gui.FindWindow ' + str(ex))
return -1 |
sends the text txt to the window handle hwnd using SendMessage | def send_text(hwnd, txt):
"""
sends the text 'txt' to the window handle hwnd using SendMessage
"""
try:
for c in txt:
if c == '\n':
win32api.SendMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
win32api.SendMessage(hwnd, win32con.WM_KEYUP, win... |
start an app | def launch_app(app_path, params=[], time_before_kill_app=15):
"""
start an app
"""
import subprocess
try:
res = subprocess.call([app_path, params], timeout=time_before_kill_app, shell=True)
print('res = ', res)
if res == 0:
return True
else:
re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.