INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Check the project file for the REPLACE_FOLDER card. If it exists, append it's value to create the batch directory path.
This is the directory output is written to when run in batch mode. | def _getBatchDirectory(self, projectRootDirectory):
"""
Check the project file for the REPLACE_FOLDER card. If it exists, append it's value to create the batch directory path.
This is the directory output is written to when run in batch mode.
"""
# Set output directory to main di... |
GSSHAPY Project Read Files from File Method | def _readXput(self, fileCards, directory, session, spatial=False, spatialReferenceID=4236, replaceParamFile=None):
"""
GSSHAPY Project Read Files from File Method
"""
## NOTE: This function is dependent on the project file being read first
# Read Input/Output Files
for ca... |
GSSHA Project Read Map Files from File Method | def _readXputMaps(self, mapCards, directory, session, spatial=False, spatialReferenceID=4236, replaceParamFile=None):
"""
GSSHA Project Read Map Files from File Method
"""
if self.mapType in self.MAP_TYPES_SUPPORTED:
for card in self.projectCards:
if (card.nam... |
Method to handle the special case of WMS Dataset Files. WMS Dataset Files
cannot be read in independently as other types of file can. They rely on
the Mask Map file for some parameters. | def _readWMSDatasets(self, datasetCards, directory, session, spatial=False, spatialReferenceID=4236):
"""
Method to handle the special case of WMS Dataset Files. WMS Dataset Files
cannot be read in independently as other types of file can. They rely on
the Mask Map file for some paramete... |
Check for the parameter replacement file cards
(REPLACE_PARAMS and REPLACE_VALS) and read the files into
database if they exist.
Returns:
replaceParamFile or None if it doesn't exist | def _readReplacementFiles(self, directory, session, spatial, spatialReferenceID):
"""
Check for the parameter replacement file cards
(REPLACE_PARAMS and REPLACE_VALS) and read the files into
database if they exist.
Returns:
replaceParamFile or None if it doesn't exis... |
When batch mode is run in GSSHA, the files of the same type are
prepended with an integer to avoid filename conflicts.
This will attempt to read files in this format and
throw warnings if the files aren't found. | def _readBatchOutputForFile(self, directory, fileIO, filename, session, spatial, spatialReferenceID,
replaceParamFile=None, maskMap=None):
"""
When batch mode is run in GSSHA, the files of the same type are
prepended with an integer to avoid filename conflicts.
... |
Invoke File Read Method on Other Files | def _invokeRead(self, fileIO, directory, filename, session, spatial=False,
spatialReferenceID=4236, replaceParamFile=None, **kwargs):
"""
Invoke File Read Method on Other Files
"""
path = os.path.join(directory, filename)
if os.path.isfile(path):
... |
GSSHA Project Write Files to File Method | def _writeXput(self, session, directory, fileCards,
name=None, replaceParamFile=None):
"""
GSSHA Project Write Files to File Method
"""
for card in self.projectCards:
if (card.name in fileCards) and self._noneOrNumValue(card.value) \
and... |
GSSHAPY Project Write Map Files to File Method | def _writeXputMaps(self, session, directory, mapCards,
name=None, replaceParamFile=None):
"""
GSSHAPY Project Write Map Files to File Method
"""
if self.mapType in self.MAP_TYPES_SUPPORTED:
for card in self.projectCards:
if (card.name in... |
GSSHAPY Project Write WMS Datasets to File Method | def _writeWMSDatasets(self, session, directory, wmsDatasetCards, name=None):
"""
GSSHAPY Project Write WMS Datasets to File Method
"""
if self.mapType in self.MAP_TYPES_SUPPORTED:
for card in self.projectCards:
if (card.name in wmsDatasetCards) and self._noneO... |
Write the replacement files | def _writeReplacementFiles(self, session, directory, name):
"""
Write the replacement files
"""
if self.replaceParamFile:
self.replaceParamFile.write(session=session, directory=directory,
name=name)
if self.replaceValFile:
... |
Invoke File Write Method on Other Files | def _invokeWrite(self, fileIO, session, directory, filename, replaceParamFile):
"""
Invoke File Write Method on Other Files
"""
# Default value for instance
instance = None
try:
# Handle case where fileIO interfaces with single file
# Retrieve Fil... |
Write project card to string.
Args:
originalPrefix (str): Original name to give to files that follow the project naming convention
(e.g: prefix.gag).
newPrefix (str, optional): If new prefix is desired, pass in this parameter. Defaults to None.
Returns:
... | def write(self, originalPrefix, newPrefix=None):
"""
Write project card to string.
Args:
originalPrefix (str): Original name to give to files that follow the project naming convention
(e.g: prefix.gag).
newPrefix (str, optional): If new prefix is desired,... |
Returns the number of seconds it has been since the start until the latest entry. | def elapsed(self):
"""Returns the number of seconds it has been since the start until the latest entry."""
if not self.started or self._start_time is None:
return 0.0
return self._timing_data[-1][0] - self._start_time |
Returns an unstable rate based on the last two entries in the timing data. Less intensive to compute. | def rate_unstable(self):
"""Returns an unstable rate based on the last two entries in the timing data. Less intensive to compute."""
if not self.started or self.stalled:
return 0.0
x1, y1 = self._timing_data[-2]
x2, y2 = self._timing_data[-1]
return (y2 - y1) / (x2 - ... |
Returns the overall average rate based on the start time. | def rate_overall(self):
"""Returns the overall average rate based on the start time."""
elapsed = self.elapsed
return self.rate if not elapsed else self.numerator / self.elapsed |
Sets the new numerator (number of items done).
Positional arguments:
numerator -- the new numerator to add to the timing data.
Keyword arguments:
calculate -- calculate the ETA and rate by default. | def set_numerator(self, numerator, calculate=True):
"""Sets the new numerator (number of items done).
Positional arguments:
numerator -- the new numerator to add to the timing data.
Keyword arguments:
calculate -- calculate the ETA and rate by default.
"""
# Val... |
Perform the ETA and rate calculation.
Two linear lines are used to calculate the ETA: the linear regression (line through a scatter-plot), and the
fitted line (a line that runs through the latest data point in _timing_data but parallel to the linear
regression line).
As the percentage ... | def _calculate(self):
"""Perform the ETA and rate calculation.
Two linear lines are used to calculate the ETA: the linear regression (line through a scatter-plot), and the
fitted line (a line that runs through the latest data point in _timing_data but parallel to the linear
regression l... |
Templatetagish wrapper for Translator.trans()
:param parser:
:param token:
:param is_transchoice:
:return: | def tranz(parser, token, is_transchoice=False):
"""
Templatetagish wrapper for Translator.trans()
:param parser:
:param token:
:param is_transchoice:
:return:
"""
tokens = token.split_contents()
id = tokens[1]
number = domain = locale = None
parameters = {}
if len(tokens... |
Templatetagish wrapper for Translator.transchoice() | def tranz_context(parser, token):
"""
Templatetagish wrapper for Translator.transchoice()
"""
tokens = token.split_contents()
parameters = {}
for idx, token in enumerate(tokens[1:], start=1):
if "=" in token:
if token[0:token.index('=')] not in ("domain", "prefix", "locale")... |
Read HMET WES from File Method | def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
"""
Read HMET WES from File Method
"""
# Set file extension property
self.fileExtension = extension
# Open file and parse into HmetRecords
with op... |
Write HMET WES to File Method | def _write(self, session, openFile, replaceParamFile):
"""
Write HMET WES to File Method
"""
## TODO: Ensure Other HMET Formats are supported
hmetRecords = self.hmetRecords
for record in hmetRecords:
openFile.write('%s\t%s\t%s\t%s\t%.3f\t%s\t%s\t%s\t%s\t%.2f\... |
ProjectFileEvent Read from File Method | def _read(self, directory, filename, session, path, name, extension,
spatial=None, spatialReferenceID=None, replaceParamFile=None):
"""
ProjectFileEvent Read from File Method
"""
yml_events = []
with open(path) as fo:
yml_events = yaml.load(fo)
... |
ProjectFileEvent Write to File Method | def _write(self, session, openFile, replaceParamFile=None):
"""
ProjectFileEvent Write to File Method
"""
openFile.write(
text(
yaml.dump([evt.as_yml() for evt in
self.events.order_by(ProjectFileEvent.name,
... |
ProjectFileEvent Write to File Method | def next_id(self, subfolder):
"""
ProjectFileEvent Write to File Method
"""
evt_sim_folders = self.events.filter(
ProjectFileEvent.subfolder
.like("{0}_%".format(subfolder))
)
max_id = 0
num_search = ... |
Add an event | def add_event(self, name, subfolder, session):
"""
Add an event
"""
if self._similar_event_exists(subfolder):
subfolder += "_{0}".format(self.next_id(subfolder))
new_event = ProjectFileEvent(name=name, subfolder=subfolder)
session.add(new_event)
self.e... |
Add an event | def generate_event(self, session):
"""
Add an event
"""
event_name = "event_{0}".format(self.next_id("event"))
return self.add_event(name=event_name, subfolder=event_name,
session=session) |
Return yml compatible version of self | def as_yml(self):
"""
Return yml compatible version of self
"""
return YmlFileEvent(name=str(self.name),
subfolder=str(self.subfolder)) |
Prepare request to node's API route
:param Node node: the RAML node object | def prepare_request(node):
"""
Prepare request to node's API route
:param Node node: the RAML node object
"""
if node.resource.method not in AVAILABLE_METHODS:
raise UnsupportedHTTPMethodError(node.resource.method)
def request(data=None, json=None, **kwargs):
"""
... |
Used to convert the :dmap: option to auto directives. | def _dsp2dot_option(arg):
"""Used to convert the :dmap: option to auto directives."""
# noinspection PyUnusedLocal
def map_args(*args, **kwargs):
from schedula.utils.base import Base
a = inspect.signature(Base.plot).bind(None, *args, **kwargs).arguments
a.popitem(last=False)
... |
get xarray dataset file handle to LSM files | def xd(self):
"""get xarray dataset file handle to LSM files"""
if self._xd is None:
path_to_lsm_files = path.join(self.lsm_input_folder_path,
self.lsm_search_card)
self._xd = super(NWMtoGSSHA, self).xd
self._xd.lsm.coords_pro... |
This function loads data from LSM and converts to GSSHA format | def _load_converted_gssha_data_from_lsm(self, gssha_var, lsm_var, load_type):
"""
This function loads data from LSM and converts to GSSHA format
"""
super(NWMtoGSSHA, self).\
_load_converted_gssha_data_from_lsm(gssha_var, lsm_var, load_type)
self.data.lsm.coords_proje... |
Return the path to a transcoder (ffmpeg or avconv) with MP3 support. | def get_transcoder():
"""Return the path to a transcoder (ffmpeg or avconv) with MP3 support."""
transcoders = ['ffmpeg', 'avconv']
transcoder_details = {}
for transcoder in transcoders:
command_path = shutil.which(transcoder)
if command_path is None:
transcoder_details[transcoder] = 'Not installed.'
co... |
Defines the data to be plotted.
:param data:
All data.
:type data: dict
:param x_name:
x-axes name.
:type x_name: str
:param y_names:
y-axes names to be plotted.
:type y_names: str
:return:
Data to be plotted.
:rtype: list | def define_plot_data(data, x_name, *y_names):
"""
Defines the data to be plotted.
:param data:
All data.
:type data: dict
:param x_name:
x-axes name.
:type x_name: str
:param y_names:
y-axes names to be plotted.
:type y_names: str
:return:
Data to ... |
Plotting lines.
:param it:
Data to plot where key value is the name of the series.
:type it: list[dict]
:return:
The plot.
:rtype: plotly.plotly.iplot | def plot_lines(it):
"""
Plotting lines.
:param it:
Data to plot where key value is the name of the series.
:type it: list[dict]
:return:
The plot.
:rtype: plotly.plotly.iplot
"""
data = [go.Scatter(mode='lines', **d) for d in it]
return py.iplot(data, filename='scat... |
Do a read on a channel. | def _ssh_channel_read(ssh_channel_int, count, is_stderr):
"""Do a read on a channel."""
buffer_ = create_string_buffer(count)
while 1:
received_bytes = c_ssh_channel_read(ssh_channel_int,
cast(buffer_, c_void_p),
... |
This function generates dictionary
from values parameter.
For example this:
example = {
'streetway': ('street', {'language': 'en'}),
'first_name': ('first', {'language': 'en'})
}
chance.dictionary(example)
will output something like this:
{'streetway': 'Jabhuru Point', 'first... | def dictionary(values):
"""
This function generates dictionary
from values parameter.
For example this:
example = {
'streetway': ('street', {'language': 'en'}),
'first_name': ('first', {'language': 'en'})
}
chance.dictionary(example)
will output something like this:
{... |
Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
102 bytes, etc).
Based on django.template.defaultfilters.filesizeformat | def filesizeformat(bytes, decimals=1):
"""
Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
102 bytes, etc).
Based on django.template.defaultfilters.filesizeformat
"""
try:
bytes = float(bytes)
except (TypeError, ValueError, UnicodeDecodeError):
raise... |
Parse EVENT chunks | def eventChunk(key, lines):
"""
Parse EVENT chunks
"""
## NOTE: RADAR file format not supported currently.
## TODO: Add Support for RADAR file format type values
# Contants
KEYWORDS = ('EVENT',
'NRPDS',
'NRGAG',
'COORD',
'GAGES... |
From: http://stackoverflow.com/questions/20801034/how-to-measure-download-speed-and-progress-using-requests | def main():
"""From: http://stackoverflow.com/questions/20801034/how-to-measure-download-speed-and-progress-using-requests"""
# Prepare.
if os.name == 'nt':
locale.setlocale(locale.LC_ALL, 'english-us')
else:
locale.resetlocale()
response = requests.get(OPTIONS['<url>'], stream=True)... |
Base method for making a Losant API request | def request(self, method, path, params=None, headers=None, body=None):
""" Base method for making a Losant API request """
if not headers:
headers = {}
if not params:
params = {}
headers["Accept"] = "application/json"
headers["Accept-Version"] = "^1.15.0"... |
Flatten out nested arrays and dicts in query params into correct format | def flatten_params(self, data, base_key=None):
""" Flatten out nested arrays and dicts in query params into correct format """
result = {}
if data is None:
return result
map_data = None
if not isinstance(data, collections.Mapping):
map_data = []
... |
Reads the excel file.
:param input_fpath:
Input file path.
:type input_fpath: str
:return:
Raw Data.
:rtype: dict | def read_excel(input_fpath):
"""
Reads the excel file.
:param input_fpath:
Input file path.
:type input_fpath: str
:return:
Raw Data.
:rtype: dict
"""
return {k: v.values for k, v in pd.read_excel(input_fpath).items()} |
Save model outputs in an Excel file.
:param outputs:
Model outputs.
:type outputs: dict
:param output_fpath:
Output file path.
:type output_fpath: str | def save_outputs(outputs, output_fpath):
"""
Save model outputs in an Excel file.
:param outputs:
Model outputs.
:type outputs: dict
:param output_fpath:
Output file path.
:type output_fpath: str
"""
df = pd.DataFrame(outputs)
with pd.ExcelWriter(output_fpath) as wr... |
Precipitation Read from File Method | def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
"""
Precipitation Read from File Method
"""
# Set file extension property
self.fileExtension = extension
# Dictionary of keywords/cards and parse function... |
Precipitation File Write to File Method | def _write(self, session, openFile, replaceParamFile):
"""
Precipitation File Write to File Method
"""
# Retrieve the events associated with this PrecipFile
events = self.precipEvents
# Write each event to file
for event in events:
openFile.write('EVE... |
Create GSSHAPY PrecipEvent, PrecipValue, and PrecipGage Objects Method | def _createGsshaPyObjects(self, eventChunk):
"""
Create GSSHAPY PrecipEvent, PrecipValue, and PrecipGage Objects Method
"""
## TODO: Add Support for RADAR file format type values
# Create GSSHAPY PrecipEvent
event = PrecipEvent(description=eventChunk['description'],
... |
Look up spatial reference system using the projection file.
Args:
directory (str):
filename (str):
Return:
int: Spatial Reference ID | def lookupSpatialReferenceID(cls, directory, filename):
"""
Look up spatial reference system using the projection file.
Args:
directory (str):
filename (str):
Return:
int: Spatial Reference ID
"""
path = os.path.join(directory, filen... |
Projection File Read from File Method | def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
"""
Projection File Read from File Method
"""
# Set file extension property
self.fileExtension = extension
# Open file and parse into a data structure
... |
Projection File Write to File Method | def _write(self, session, openFile, replaceParamFile):
"""
Projection File Write to File Method
"""
# Write lines
openFile.write(text(self.projection)) |
Log events to the console.
Args:
status (bool, Optional, Default=True)
whether logging to console should be turned on(True) or off(False)
level (string, Optional, Default=None) :
level of logging; whichever level is chosen all higher levels will be logged.
See: ... | def log_to_console(status=True, level=None):
"""Log events to the console.
Args:
status (bool, Optional, Default=True)
whether logging to console should be turned on(True) or off(False)
level (string, Optional, Default=None) :
level of logging; whichever level is chosen... |
Log events to a file.
Args:
status (bool, Optional, Default=True)
whether logging to file should be turned on(True) or off(False)
filename (string, Optional, Default=None) :
path of file to log to
level (string, Optional, Default=None) :
level of logging;... | def log_to_file(status=True, filename=default_log_file, level=None):
"""Log events to a file.
Args:
status (bool, Optional, Default=True)
whether logging to file should be turned on(True) or off(False)
filename (string, Optional, Default=None) :
path of file to log to
... |
Sets a new numerator and generates the ETA. Must be greater than or equal to previous numerator. | def numerator(self, value):
"""Sets a new numerator and generates the ETA. Must be greater than or equal to previous numerator."""
# If ETA is every iteration, don't do anything fancy.
if self.eta_every <= 1:
self._eta.numerator = value
self._eta_string = self._generate_e... |
Returns the rate of the progress as a float. Selects the unstable rate if eta_every > 1 for performance. | def rate(self):
"""Returns the rate of the progress as a float. Selects the unstable rate if eta_every > 1 for performance."""
return float(self._eta.rate_unstable if self.eta_every > 1 else self._eta.rate) |
Generates an elevation grid for the GSSHA simulation
from an elevation raster
Example::
from gsshapy.orm import ProjectFile, ElevationGridFile
from gsshapy.lib import db_tools as dbt
gssha_directory = '/gsshapy/tests/grid_standard/gssha_project'
elevat... | def generateFromRaster(self,
elevation_raster,
shapefile_path=None,
out_elevation_grid=None,
resample_method=gdalconst.GRA_Average,
load_raster_to_db=True):
"""
Generate... |
Storm Pipe Network File Read from File Method | def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
"""
Storm Pipe Network File Read from File Method
"""
# Set file extension property
self.fileExtension = extension
# Dictionary of keywords/cards and pars... |
Storm Pipe Network File Write to File Method | def _write(self, session, openFile, replaceParamFile):
"""
Storm Pipe Network File Write to File Method
"""
# Retrieve Connection objects and write to file
connections = self.connections
self._writeConnections(connections=connections,
fileOb... |
Create GSSHAPY Connection Objects Method | def _createConnection(self, connections):
"""
Create GSSHAPY Connection Objects Method
"""
for c in connections:
# Create GSSHAPY Connection object
connection = Connection(slinkNumber=c['slinkNumber'],
upSjuncNumber=c['upSjunc'... |
Create GSSHAPY SuperLink, Pipe, and SuperNode Objects Method | def _createSlink(self, slinks):
"""
Create GSSHAPY SuperLink, Pipe, and SuperNode Objects Method
"""
for slink in slinks:
# Create GSSHAPY SuperLink object
superLink = SuperLink(slinkNumber=slink['slinkNumber'],
numPipes=slink['n... |
Create GSSHAPY SuperJunction Objects Method | def _createSjunc(self, sjuncs):
"""
Create GSSHAPY SuperJunction Objects Method
"""
for sjunc in sjuncs:
# Create GSSHAPY SuperJunction object
superJunction = SuperJunction(sjuncNumber=sjunc['sjuncNumber'],
groundSurfaceE... |
Write Connections to File Method | def _writeConnections(self, connections, fileObject):
"""
Write Connections to File Method
"""
for connection in connections:
fileObject.write('CONNECT %s %s %s\n' % (
connection.slinkNumber,
connection.upSjuncNumber,
connect... |
Write SuperJunctions to File Method | def _writeSuperJunctions(self, superJunctions, fileObject):
"""
Write SuperJunctions to File Method
"""
for sjunc in superJunctions:
fileObject.write('SJUNC %s %.2f %.2f %.6f %s %s %s %.6f %.6f\n' % (
sjunc.sjuncNumber,
sjunc.groundSur... |
Write SuperLinks to File Method | def _writeSuperLinks(self, superLinks, fileObject):
"""
Write SuperLinks to File Method
"""
for slink in superLinks:
fileObject.write('SLINK %s %s\n' % (
slink.slinkNumber,
slink.numPipes))
for node in slink.superNodes:
... |
Converts seconds remaining into a human readable timestamp (e.g. hh:mm:ss, h:mm:ss, mm:ss, or ss).
Positional arguments:
seconds -- integer/float indicating seconds remaining.
Keyword arguments:
always_show_hours -- don't hide the 0 hours.
always_show_minutes -- don't hide the 0 minutes.
hours... | def eta_hms(seconds, always_show_hours=False, always_show_minutes=False, hours_leading_zero=False):
"""Converts seconds remaining into a human readable timestamp (e.g. hh:mm:ss, h:mm:ss, mm:ss, or ss).
Positional arguments:
seconds -- integer/float indicating seconds remaining.
Keyword arguments:
... |
Converts seconds remaining into human readable strings (e.g. '1s' or '5h 22m 2s').
Positional arguments:
seconds -- integer/float indicating seconds remaining.
Keyword arguments:
shortest -- show the shortest possible string length by only showing the biggest unit.
leading_zero -- always show a le... | def eta_letters(seconds, shortest=False, leading_zero=False):
"""Converts seconds remaining into human readable strings (e.g. '1s' or '5h 22m 2s').
Positional arguments:
seconds -- integer/float indicating seconds remaining.
Keyword arguments:
shortest -- show the shortest possible string length b... |
ku = ultimate gain
tu = period of oscillation at ultimate gain | def ziegler_nichols(self,ku,tu,control_type='pid'):
'''
ku = ultimate gain
tu = period of oscillation at ultimate gain
'''
converter = dict(
p = lambda ku,tu: (.5*ku, 0, 0),
pi = lambda ku,tu: (.45*ku, 1.2*(.45*ku)/tu, 0),
pd = lambda k... |
Process the dataset header | def datasetHeaderChunk(key, lines):
"""
Process the dataset header
"""
KEYWORDS = ('DATASET',
'OBJTYPE',
'VECTYPE',
'BEGSCL',
'BEGVEC',
'OBJID',
'ND',
'NC',
'NAME')
TYPE_K... |
Process the time step chunks for scalar datasets | def datasetScalarTimeStepChunk(lines, numberColumns, numberCells):
"""
Process the time step chunks for scalar datasets
"""
END_DATASET_TAG = 'ENDDS'
# Define the result object
result = {'iStatus': None,
'timestamp': None,
'cellArray': None,
'rasterText... |
Write Dispatcher object in Python pickle format.
Pickles are a serialized byte stream of a Python object.
This format will preserve Python objects used as nodes or edges.
:param dsp:
A dispatcher that identifies the model adopted.
:type dsp: schedula.Dispatcher
:param path:
File o... | def save_dispatcher(dsp, path):
"""
Write Dispatcher object in Python pickle format.
Pickles are a serialized byte stream of a Python object.
This format will preserve Python objects used as nodes or edges.
:param dsp:
A dispatcher that identifies the model adopted.
:type dsp: schedula... |
Load Dispatcher default values in Python pickle format.
Pickles are a serialized byte stream of a Python object.
This format will preserve Python objects used as nodes or edges.
:param dsp:
A dispatcher that identifies the model adopted.
:type dsp: schedula.Dispatcher
:param path:
... | def load_default_values(dsp, path):
"""
Load Dispatcher default values in Python pickle format.
Pickles are a serialized byte stream of a Python object.
This format will preserve Python objects used as nodes or edges.
:param dsp:
A dispatcher that identifies the model adopted.
:type ds... |
Write Dispatcher default values in Python pickle format.
Pickles are a serialized byte stream of a Python object.
This format will preserve Python objects used as nodes or edges.
:param dsp:
A dispatcher that identifies the model adopted.
:type dsp: schedula.Dispatcher
:param path:
... | def save_default_values(dsp, path):
"""
Write Dispatcher default values in Python pickle format.
Pickles are a serialized byte stream of a Python object.
This format will preserve Python objects used as nodes or edges.
:param dsp:
A dispatcher that identifies the model adopted.
:type d... |
Write Dispatcher graph object in Python pickle format.
Pickles are a serialized byte stream of a Python object.
This format will preserve Python objects used as nodes or edges.
:param dsp:
A dispatcher that identifies the model adopted.
:type dsp: schedula.Dispatcher
:param path:
... | def save_map(dsp, path):
"""
Write Dispatcher graph object in Python pickle format.
Pickles are a serialized byte stream of a Python object.
This format will preserve Python objects used as nodes or edges.
:param dsp:
A dispatcher that identifies the model adopted.
:type dsp: schedula.... |
Divide a file into chunks between
key words in the list | def chunk(keywords, lines):
"""
Divide a file into chunks between
key words in the list
"""
chunks = dict()
chunk = []
# Create an empty dictionary using all the keywords
for keyword in keywords:
chunks[keyword] = []
# Populate dictionary with lists of chunks asso... |
Apply global pre-processing to values during reading throughout the project.
Args:
valueString (str): String representing the value to be preprocessed.
replaceParamsFile (gsshapy.orm.ReplaceParamFile, optional): Instance of the replace param file. Required if
replacement variables are i... | def valueReadPreprocessor(valueString, replaceParamsFile=None):
"""
Apply global pre-processing to values during reading throughout the project.
Args:
valueString (str): String representing the value to be preprocessed.
replaceParamsFile (gsshapy.orm.ReplaceParamFile, optional): Instance of... |
Look up variable name in replace param file for the negative id given and return it.
Args:
valueString (str): String representing the value to be preprocessed.
replaceParamsFile (gsshapy.orm.ReplaceParamFile, optional): Instance of the replace param file. Required if
replacement variabl... | def valueWritePreprocessor(valueString, replaceParamsFile=None):
"""
Look up variable name in replace param file for the negative id given and return it.
Args:
valueString (str): String representing the value to be preprocessed.
replaceParamsFile (gsshapy.orm.ReplaceParamFile, optional): In... |
Run all FeatureExtractors and output results to CSV. | def run(self, dataset_path):
"""Run all FeatureExtractors and output results to CSV."""
features = self._generate_features(self._feature_extractors)
features.to_csv(dataset_path) |
Run all FeatureExtractors and record results in a key-value format.
:param feature_extractors: iterable of `FeatureExtractor` objects. | def _generate_features(self, feature_extractors):
"""Run all FeatureExtractors and record results in a key-value format.
:param feature_extractors: iterable of `FeatureExtractor` objects.
"""
results = [pd.DataFrame()]
n_ext = len(feature_extractors)
for i, extractor in... |
Generic read file into database method.
Args:
directory (str): Directory containing the file to be read.
filename (str): Name of the file which will be read (e.g.: 'example.prj').
session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS ena... | def read(self, directory, filename, session, spatial=False,
spatialReferenceID=4236, replaceParamFile=None, **kwargs):
"""
Generic read file into database method.
Args:
directory (str): Directory containing the file to be read.
filename (str): Name of the fi... |
Write from database back to file.
Args:
session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database.
directory (str): Directory where the file will be written.
name (str): The name of the file that will be created (including t... | def write(self, session, directory, name, replaceParamFile=None, **kwargs):
"""
Write from database back to file.
Args:
session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database.
directory (str): Directory where the file... |
Custom commit function for file objects | def _commit(self, session, errorMessage):
"""
Custom commit function for file objects
"""
try:
session.commit()
except IntegrityError:
# Raise special error if the commit fails due to empty files
log.error('Commit to database failed. %s' % erro... |
Private file object read method. Classes that inherit from this base class must implement this method.
The ``read()`` method that each file object inherits from this base class performs the processes common to all
file read methods, after which it calls the file object's ``_read()`` (the preceding unde... | def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
"""
Private file object read method. Classes that inherit from this base class must implement this method.
The ``read()`` method that each file object inherits from this base cla... |
Return a dictionary of values derived directly from the VCS. This is the
third attempt to find information by get_versions(). | def svn_versions_from_vcs(tag_prefix, root, verbose=False):
"""Return a dictionary of values derived directly from the VCS. This is the
third attempt to find information by get_versions().
"""
if not os.path.exists(os.path.join(root, '.svn')):
if verbose:
print("no .svn in %s." % ro... |
This variation of get_versions() will be used in versioneer.py . | def get_versions(default=DEFAULT, verbose=False):
"""This variation of get_versions() will be used in versioneer.py ."""
# returns dict with two keys: 'version' and 'full'
assert versionfile_source is not None, "please set versioneer.versionfile_source"
assert tag_prefix is not None, "please set versi... |
Create the versioneer.py file. | def run(self):
"""Create the versioneer.py file."""
print(" creating %s" % versionfile_source)
with open(versionfile_source, "w") as f:
f.write(get_vcs_code())
ipy = os.path.join(os.path.dirname(versionfile_source), "__init__.py")
try:
with open(ipy, "r"... |
Parse Card Chunk Method | def cardChunk(key, chunk):
"""
Parse Card Chunk Method
"""
for line in chunk:
values = []
sline = line.strip().split()
for idx in range(1, len(sline)):
values.append(sline[idx])
return {'card': sline[0],
'values': values} |
Parse Card Chunk Method | def connectChunk(key, chunk):
"""
Parse Card Chunk Method
"""
upLinks = []
schunk = chunk[0].strip().split()
for idx in range(4, len(schunk)):
upLinks.append(schunk[idx])
result = {'link': schunk[1],
'downLink': schunk[2],
'numUpLinks': schunk[3],
... |
Parse LINK Chunk Method | def linkChunk(key, chunk):
"""
Parse LINK Chunk Method
"""
# Extract link type card
linkType = chunk[1].strip().split()[0]
# Cases
if linkType == 'DX':
# Cross section link type handler
result = xSectionLink(chunk)
elif linkType == 'STRUCTURE':
# Structure link ... |
Parse STRUCTURE LINK Method | def structureLink(lines):
"""
Parse STRUCTURE LINK Method
"""
# Constants
KEYWORDS = ('LINK',
'STRUCTURE',
'NUMSTRUCTS',
'STRUCTTYPE')
WEIR_KEYWORDS = ('STRUCTTYPE',
'CREST_LENGTH',
'CREST_LOW_ELEV',
... |
Parse Cross Section Links Method | def xSectionLink(lines):
"""
Parse Cross Section Links Method
"""
# Constants
KEYWORDS = ('LINK',
'DX',
'TRAPEZOID',
'TRAPEZOID_ERODE',
'TRAPEZOID_SUBSURFACE',
'ERODE_TRAPEZOID',
'ERODE_SUBSURFACE',
... |
Parse RESERVOIR Link Method | def reservoirLink(lines):
"""
Parse RESERVOIR Link Method
"""
# Constants
KEYWORDS = ('LINK',
'RESERVOIR',
'RES_MINWSE',
'RES_INITWSE',
'RES_MAXWSE',
'RES_NUMPTS',
'LAKE',
'MINWSE',
... |
Parse NODE Method | def nodeChunk(lines):
"""
Parse NODE Method
"""
# Constants
KEYWORDS = ('NODE',
'X_Y',
'ELEV')
result = {'node': None,
'x': None,
'y': None,
'elev': None}
chunks = pt.chunk(KEYWORDS, lines)
# Parse chunks associ... |
Parse XSEC Method | def xSectionChunk(lines):
"""
Parse XSEC Method
"""
# Constants
KEYWORDS = ('MANNINGS_N',
'BOTTOM_WIDTH',
'BANKFULL_DEPTH',
'SIDE_SLOPE',
'NPAIRS',
'NUM_INTERP',
'X1',
'ERODE',
... |
Parse Weir and Culvert Structures Method | def structureChunk(keywords, resultDict, lines):
"""
Parse Weir and Culvert Structures Method
"""
chunks = pt.chunk(keywords, lines)
# Parse chunks associated with each key
for key, chunkList in iteritems(chunks):
# Parse each chunk in the chunk list
for chunk in chunkList:
... |
Returns the completed progress bar.
Positional arguments:
width -- the width of the entire bar (including borders). | def bar(self, width, **_):
"""Returns the completed progress bar.
Positional arguments:
width -- the width of the entire bar (including borders).
"""
return self.CHAR_LEFT_BORDER + self.CHAR_EMPTY * (width - self._width_offset) + self.CHAR_RIGHT_BORDER |
Returns the completed progress bar. Every time this is called the animation moves.
Positional arguments:
width -- the width of the entire bar (including borders). | def bar(self, width, **_):
"""Returns the completed progress bar. Every time this is called the animation moves.
Positional arguments:
width -- the width of the entire bar (including borders).
"""
width -= self._width_offset
self._position += self._direction
# C... |
Returns the completed progress bar.
Positional arguments:
width -- the width of the entire bar (including borders).
Keyword arguments:
percent -- the percentage to draw. | def bar(self, width, percent=0):
"""Returns the completed progress bar.
Positional arguments:
width -- the width of the entire bar (including borders).
Keyword arguments:
percent -- the percentage to draw.
"""
width -= self._width_offset
units = int(perc... |
Returns the completed progress bar.
Positional arguments:
width -- the width of the entire bar (including borders).
Keyword arguments:
percent -- the percentage to draw. | def bar(self, width, percent=0):
"""Returns the completed progress bar.
Positional arguments:
width -- the width of the entire bar (including borders).
Keyword arguments:
percent -- the percentage to draw.
"""
width -= self._width_offset
units_float = pe... |
Mapping Table Read from File Method | def _read(self, directory, filename, session, path, name, extension,
spatial=False, spatialReferenceID=4236, replaceParamFile=None,
readIndexMaps=True):
"""
Mapping Table Read from File Method
"""
# Set file extension property
self.fileExtension = exte... |
Map Table Write to File Method | def _write(self, session, openFile, replaceParamFile=None, writeIndexMaps=True):
"""
Map Table Write to File Method
"""
# Extract directory
directory = os.path.split(openFile.name)[0]
# Derive a Unique Set of Contaminants
for mapTable in self.getOrderedMapTables(... |
Retrieve the map tables ordered by name | def getOrderedMapTables(self, session):
"""
Retrieve the map tables ordered by name
"""
return session.query(MapTable).filter(MapTable.mapTableFile == self).order_by(MapTable.name).all() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.