idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
4,700 | def _commit ( self , session , errorMessage ) : try : session . commit ( ) except IntegrityError : # Raise special error if the commit fails due to empty files log . error ( 'Commit to database failed. %s' % errorMessage ) except : # Raise other errors as normal raise | Custom commit function for file objects | 62 | 6 |
4,701 | def run ( self ) : 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" ) as f : old = f . read ( ) except EnvironmentError : old = "" if INIT_PY_SNIPPET not in old : print ( " appending to %s" % ipy ) with open ( ipy , "a" ) as f : f . write ( INIT_PY_SNIPPET ) else : print ( " %s unmodified" % ipy ) # Make sure both the top-level "versioneer.py" and versionfile_source # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so # they'll be copied into source distributions. Pip won't be able to # install the package without this. manifest_in = os . path . join ( get_root ( ) , "MANIFEST.in" ) simple_includes = set ( ) try : with open ( manifest_in , "r" ) as f : for line in f : if line . startswith ( "include " ) : for include in line . split ( ) [ 1 : ] : simple_includes . add ( include ) except EnvironmentError : pass # That doesn't cover everything MANIFEST.in can do # (http://docs.python.org/2/distutils/sourcedist.html#commands), so # it might give some false negatives. Appending redundant 'include' # lines is safe, though. if "versioneer.py" not in simple_includes : print ( " appending 'versioneer.py' to MANIFEST.in" ) with open ( manifest_in , "a" ) as f : f . write ( "include versioneer.py\n" ) else : print ( " 'versioneer.py' already in MANIFEST.in" ) if versionfile_source not in simple_includes : print ( " appending versionfile_source ('%s') to MANIFEST.in" % versionfile_source ) with open ( manifest_in , "a" ) as f : f . write ( "include %s\n" % versionfile_source ) else : print ( " versionfile_source already in MANIFEST.in" ) # Make VCS-specific changes. For git, this means creating/changing # .gitattributes to mark _version.py for export-time keyword # substitution. do_vcs_install_f = getattr ( sys . modules [ __name__ ] , VCS + '_do_vcs_install' ) do_vcs_install_f ( manifest_in , versionfile_source , ipy ) | Create the versioneer . py file . | 647 | 8 |
4,702 | def linkChunk ( key , chunk ) : # 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 type handler result = structureLink ( chunk ) elif linkType in ( 'RESERVOIR' , 'LAKE' ) : # Reservoir link type handler result = reservoirLink ( chunk ) return result | Parse LINK Chunk Method | 113 | 6 |
4,703 | def structureLink ( lines ) : # Constants KEYWORDS = ( 'LINK' , 'STRUCTURE' , 'NUMSTRUCTS' , 'STRUCTTYPE' ) WEIR_KEYWORDS = ( 'STRUCTTYPE' , 'CREST_LENGTH' , 'CREST_LOW_ELEV' , 'DISCHARGE_COEFF_FORWARD' , 'DISCHARGE_COEFF_REVERSE' , 'CREST_LOW_LOC' , 'STEEP_SLOPE' , 'SHALLOW_SLOPE' ) CULVERT_KEYWORDS = ( 'STRUCTTYPE' , 'UPINVERT' , 'DOWNINVERT' , 'INLET_DISCH_COEFF' , 'REV_FLOW_DISCH_COEFF' , 'SLOPE' , 'LENGTH' , 'ROUGH_COEFF' , 'DIAMETER' , 'WIDTH' , 'HEIGHT' ) WEIRS = ( 'WEIR' , 'SAG_WEIR' ) CULVERTS = ( 'ROUND_CULVERT' , 'RECT_CULVERT' ) CURVES = ( 'RATING_CURVE' , 'SCHEDULED_RELEASE' , 'RULE_CURVE' ) result = { 'type' : 'STRUCTURE' , 'header' : { 'link' : None , 'numstructs' : None } , 'structures' : [ ] } 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 : # Cases if key == 'STRUCTTYPE' : # Structure handler structType = chunk [ 0 ] . strip ( ) . split ( ) [ 1 ] # Cases if structType in WEIRS : weirResult = { 'structtype' : None , 'crest_length' : None , 'crest_low_elev' : None , 'discharge_coeff_forward' : None , 'discharge_coeff_reverse' : None , 'crest_low_loc' : None , 'steep_slope' : None , 'shallow_slope' : None } # Weir type structures handler result [ 'structures' ] . append ( structureChunk ( WEIR_KEYWORDS , weirResult , chunk ) ) elif structType in CULVERTS : culvertResult = { 'structtype' : None , 'upinvert' : None , 'downinvert' : None , 'inlet_disch_coeff' : None , 'rev_flow_disch_coeff' : None , 'slope' : None , 'length' : None , 'rough_coeff' : None , 'diameter' : None , 'width' : None , 'height' : None } # Culvert type structures handler result [ 'structures' ] . append ( structureChunk ( CULVERT_KEYWORDS , culvertResult , chunk ) ) elif structType in CURVES : # Curve type handler pass elif key != 'STRUCTURE' : # All other variables header result [ 'header' ] [ key . lower ( ) ] = chunk [ 0 ] . strip ( ) . split ( ) [ 1 ] return result | Parse STRUCTURE LINK Method | 734 | 7 |
4,704 | def reservoirLink ( lines ) : # Constants KEYWORDS = ( 'LINK' , 'RESERVOIR' , 'RES_MINWSE' , 'RES_INITWSE' , 'RES_MAXWSE' , 'RES_NUMPTS' , 'LAKE' , 'MINWSE' , 'INITWSE' , 'MAXWSE' , 'NUMPTS' ) result = { 'header' : { 'link' : None , 'res_minwse' : None , 'res_initwse' : None , 'res_maxwse' : None , 'res_numpts' : None , 'minwse' : None , 'initwse' : None , 'maxwse' : None , 'numpts' : None } , 'type' : None , 'points' : [ ] } pair = { 'i' : None , 'j' : None } # Rechunk the chunk 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 : schunk = chunk [ 0 ] . strip ( ) . split ( ) # Cases if key in ( 'NUMPTS' , 'RES_NUMPTS' ) : # Points handler result [ 'header' ] [ key . lower ( ) ] = schunk [ 1 ] # Parse points for idx in range ( 1 , len ( chunk ) ) : schunk = chunk [ idx ] . strip ( ) . split ( ) for count , ordinate in enumerate ( schunk ) : # Divide ordinates into ij pairs if ( count % 2 ) == 0 : pair [ 'i' ] = ordinate else : pair [ 'j' ] = ordinate result [ 'points' ] . append ( pair ) pair = { 'i' : None , 'j' : None } elif key in ( 'LAKE' , 'RESERVOIR' ) : # Type handler result [ 'type' ] = schunk [ 0 ] else : # Header variables handler result [ 'header' ] [ key . lower ( ) ] = schunk [ 1 ] return result | Parse RESERVOIR Link Method | 486 | 8 |
4,705 | def nodeChunk ( lines ) : # Constants KEYWORDS = ( 'NODE' , 'X_Y' , 'ELEV' ) result = { 'node' : None , 'x' : None , 'y' : None , 'elev' : None } 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 : schunk = chunk [ 0 ] . strip ( ) . split ( ) if key == 'X_Y' : result [ 'x' ] = schunk [ 1 ] result [ 'y' ] = schunk [ 2 ] else : result [ key . lower ( ) ] = schunk [ 1 ] return result | Parse NODE Method | 174 | 5 |
4,706 | def xSectionChunk ( lines ) : # Constants KEYWORDS = ( 'MANNINGS_N' , 'BOTTOM_WIDTH' , 'BANKFULL_DEPTH' , 'SIDE_SLOPE' , 'NPAIRS' , 'NUM_INTERP' , 'X1' , 'ERODE' , 'MAX_EROSION' , 'SUBSURFACE' , 'M_RIVER' , 'K_RIVER' ) result = { 'mannings_n' : None , 'bottom_width' : None , 'bankfull_depth' : None , 'side_slope' : None , 'npairs' : None , 'num_interp' : None , 'erode' : False , 'subsurface' : False , 'max_erosion' : None , 'm_river' : None , 'k_river' : None , 'breakpoints' : [ ] } 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 : # Strip and split the line (only one item in each list) schunk = chunk [ 0 ] . strip ( ) . split ( ) # Cases if key == 'X1' : # Extract breakpoint XY pairs x = schunk [ 1 ] y = schunk [ 2 ] result [ 'breakpoints' ] . append ( { 'x' : x , 'y' : y } ) if key in ( 'SUBSURFACE' , 'ERODE' ) : # Set booleans result [ key . lower ( ) ] = True else : # Extract value result [ key . lower ( ) ] = schunk [ 1 ] return result | Parse XSEC Method | 390 | 5 |
4,707 | def structureChunk ( keywords , resultDict , lines ) : 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 : # Strip and split the line (only one item in each list) schunk = chunk [ 0 ] . strip ( ) . split ( ) # Extract values and assign to appropriate key in resultDict resultDict [ key . lower ( ) ] = schunk [ 1 ] return resultDict | Parse Weir and Culvert Structures Method | 120 | 9 |
4,708 | def bar ( self , width , * * _ ) : width -= self . _width_offset self . _position += self . _direction # Change direction. if self . _position <= 0 and self . _direction < 0 : self . _position = 0 self . _direction = 1 elif self . _position > width : self . _position = width - 1 self . _direction = - 1 final_bar = ( self . CHAR_LEFT_BORDER + self . CHAR_EMPTY * self . _position + self . CHAR_ANIMATED + self . CHAR_EMPTY * ( width - self . _position ) + self . CHAR_RIGHT_BORDER ) return final_bar | Returns the completed progress bar . Every time this is called the animation moves . | 151 | 15 |
4,709 | def _read ( self , directory , filename , session , path , name , extension , spatial = False , spatialReferenceID = 4236 , replaceParamFile = None , readIndexMaps = True ) : # Set file extension property self . fileExtension = extension # Dictionary of keywords/cards and parse function names KEYWORDS = { 'INDEX_MAP' : mtc . indexMapChunk , 'ROUGHNESS' : mtc . mapTableChunk , 'INTERCEPTION' : mtc . mapTableChunk , 'RETENTION' : mtc . mapTableChunk , 'GREEN_AMPT_INFILTRATION' : mtc . mapTableChunk , 'GREEN_AMPT_INITIAL_SOIL_MOISTURE' : mtc . mapTableChunk , 'RICHARDS_EQN_INFILTRATION_BROOKS' : mtc . mapTableChunk , 'RICHARDS_EQN_INFILTRATION_HAVERCAMP' : mtc . mapTableChunk , 'EVAPOTRANSPIRATION' : mtc . mapTableChunk , 'WELL_TABLE' : mtc . mapTableChunk , 'OVERLAND_BOUNDARY' : mtc . mapTableChunk , 'TIME_SERIES_INDEX' : mtc . mapTableChunk , 'GROUNDWATER' : mtc . mapTableChunk , 'GROUNDWATER_BOUNDARY' : mtc . mapTableChunk , 'AREA_REDUCTION' : mtc . mapTableChunk , 'WETLAND_PROPERTIES' : mtc . mapTableChunk , 'MULTI_LAYER_SOIL' : mtc . mapTableChunk , 'SOIL_EROSION_PROPS' : mtc . mapTableChunk , 'CONTAMINANT_TRANSPORT' : mtc . contamChunk , 'SEDIMENTS' : mtc . sedimentChunk } indexMaps = dict ( ) mapTables = [ ] # Parse file into chunks associated with keywords/cards with io_open ( path , 'r' ) as f : chunks = pt . chunk ( KEYWORDS , f ) # Parse chunks associated with each key for key , chunkList in iteritems ( chunks ) : # Parse each chunk in the chunk list for chunk in chunkList : # Call chunk specific parsers for each chunk result = KEYWORDS [ key ] ( key , chunk ) # Index Map handler if key == 'INDEX_MAP' : # Create GSSHAPY IndexMap object from result object indexMap = IndexMap ( name = result [ 'idxName' ] ) # Dictionary used to map index maps to mapping tables indexMaps [ result [ 'idxName' ] ] = indexMap # Associate IndexMap with MapTableFile indexMap . mapTableFile = self if readIndexMaps : # Invoke IndexMap read method indexMap . read ( directory = directory , filename = result [ 'filename' ] , session = session , spatial = spatial , spatialReferenceID = spatialReferenceID ) else : # add path to file indexMap . filename = result [ 'filename' ] # Map Table handler else : # Create a list of all the map tables in the file if result : mapTables . append ( result ) # Create GSSHAPY ORM objects with the resulting objects that are # returned from the parser functions self . _createGsshaPyObjects ( mapTables , indexMaps , replaceParamFile , directory , session , spatial , spatialReferenceID ) | Mapping Table Read from File Method | 775 | 7 |
4,710 | def _write ( self , session , openFile , replaceParamFile = None , writeIndexMaps = True ) : # Extract directory directory = os . path . split ( openFile . name ) [ 0 ] # Derive a Unique Set of Contaminants for mapTable in self . getOrderedMapTables ( session ) : if mapTable . name == 'CONTAMINANT_TRANSPORT' : contaminantList = [ ] for mtValue in mapTable . values : if mtValue . contaminant not in contaminantList : contaminantList . append ( mtValue . contaminant ) contaminants = sorted ( contaminantList , key = lambda x : ( x . indexMap . name , x . name ) ) # Write first line to file openFile . write ( 'GSSHA_INDEX_MAP_TABLES\n' ) # Write list of index maps for indexMap in self . indexMaps : # Write to map table file openFile . write ( 'INDEX_MAP%s"%s" "%s"\n' % ( ' ' * 16 , indexMap . filename , indexMap . name ) ) if writeIndexMaps : # Initiate index map write indexMap . write ( directory , session = session ) for mapTable in self . getOrderedMapTables ( session ) : if mapTable . name == 'SEDIMENTS' : self . _writeSedimentTable ( session = session , fileObject = openFile , mapTable = mapTable , replaceParamFile = replaceParamFile ) elif mapTable . name == 'CONTAMINANT_TRANSPORT' : self . _writeContaminantTable ( session = session , fileObject = openFile , mapTable = mapTable , contaminants = contaminants , replaceParamFile = replaceParamFile ) else : self . _writeMapTable ( session = session , fileObject = openFile , mapTable = mapTable , replaceParamFile = replaceParamFile ) | Map Table Write to File Method | 414 | 6 |
4,711 | def getOrderedMapTables ( self , session ) : return session . query ( MapTable ) . filter ( MapTable . mapTableFile == self ) . order_by ( MapTable . name ) . all ( ) | Retrieve the map tables ordered by name | 47 | 8 |
4,712 | def deleteMapTable ( self , name , session ) : duplicate_map_tables = session . query ( MapTable ) . filter ( MapTable . mapTableFile == self ) . filter ( MapTable . name == name ) . all ( ) for duplicate_map_table in duplicate_map_tables : if duplicate_map_table . indexMap : session . delete ( duplicate_map_table . indexMap ) session . delete ( duplicate_map_table ) session . commit ( ) | Remove duplicate map table if it exists | 104 | 7 |
4,713 | def _createValueObjects ( self , valueList , varList , mapTable , indexMap , contaminant , replaceParamFile ) : def assign_values_to_table ( value_list , layer_id ) : for i , value in enumerate ( value_list ) : value = vrp ( value , replaceParamFile ) # Create MTValue object and associate with MTIndex and MapTable mtValue = MTValue ( variable = varList [ i ] , value = float ( value ) ) mtValue . index = mtIndex mtValue . mapTable = mapTable mtValue . layer_id = layer_id # MTContaminant handler (associate MTValue with MTContaminant) if contaminant : mtValue . contaminant = contaminant for row in valueList : # Create GSSHAPY MTIndex object and associate with IndexMap mtIndex = MTIndex ( index = row [ 'index' ] , description1 = row [ 'description1' ] , description2 = row [ 'description2' ] ) mtIndex . indexMap = indexMap if len ( np . shape ( row [ 'values' ] ) ) == 2 : # this is for ids with multiple layers for layer_id , values in enumerate ( row [ 'values' ] ) : assign_values_to_table ( values , layer_id ) else : assign_values_to_table ( row [ 'values' ] , 0 ) | Populate GSSHAPY MTValue and MTIndex Objects Method | 307 | 15 |
4,714 | def _readContaminantOutputFiles ( self , directory , baseFileName , session , spatial , spatialReferenceID ) : if not os . path . isdir ( directory ) : return if baseFileName == '' : return # Look for channel output files denoted by the ".chan" after the base filename chanBaseFileName = '.' . join ( [ baseFileName , 'chan' ] ) # Get contents of directory directoryList = os . listdir ( directory ) # Compile a list of files with "basename.chan" in them chanFiles = [ ] for thing in directoryList : if chanBaseFileName in thing : chanFiles . append ( thing ) # Assume all "chan" files are link node dataset files and try to read them for chanFile in chanFiles : linkNodeDatasetFile = LinkNodeDatasetFile ( ) linkNodeDatasetFile . projectFile = self . projectFile try : linkNodeDatasetFile . read ( directory = directory , filename = chanFile , session = session , spatial = spatial , spatialReferenceID = spatialReferenceID ) except : log . warning ( 'Attempted to read Contaminant Transport Output file {0}, but failed.' . format ( chanFile ) ) | Read any contaminant output files if available | 269 | 8 |
4,715 | def _writeMapTable ( self , session , fileObject , mapTable , replaceParamFile ) : # Write mapping name fileObject . write ( '%s "%s"\n' % ( mapTable . name , mapTable . indexMap . name ) ) # Write mapping table global variables if mapTable . numIDs : fileObject . write ( 'NUM_IDS %s\n' % ( mapTable . numIDs ) ) if mapTable . maxNumCells : fileObject . write ( 'MAX_NUMBER_CELLS %s\n' % ( mapTable . maxNumCells ) ) if mapTable . numSed : fileObject . write ( 'NUM_SED %s\n' % ( mapTable . numSed ) ) if mapTable . maxSoilID : fileObject . write ( 'MAX_SOIL_ID %s\n' % ( mapTable . maxSoilID ) ) # Write value lines from the database self . _writeValues ( session , fileObject , mapTable , None , replaceParamFile ) | Write Generic Map Table Method | 227 | 5 |
4,716 | def _writeContaminantTable ( self , session , fileObject , mapTable , contaminants , replaceParamFile ) : # Write the contaminant mapping table header fileObject . write ( '%s\n' % ( mapTable . name ) ) fileObject . write ( 'NUM_CONTAM %s\n' % ( mapTable . numContam ) ) # Write out each contaminant and it's values for contaminant in contaminants : fileObject . write ( '"%s" "%s" %s\n' % ( contaminant . name , contaminant . indexMap . name , contaminant . outputFilename ) ) # Add trailing zeros to values / replacement parameter precipConcString = vwp ( contaminant . precipConc , replaceParamFile ) partitionString = vwp ( contaminant . partition , replaceParamFile ) try : precipConc = '%.2f' % precipConcString except : precipConc = '%s' % precipConcString try : partition = '%.2f' % partitionString except : partition = '%s' % partitionString # Write global variables for the contaminant fileObject . write ( 'PRECIP_CONC%s%s\n' % ( ' ' * 10 , precipConc ) ) fileObject . write ( 'PARTITION%s%s\n' % ( ' ' * 12 , partition ) ) fileObject . write ( 'NUM_IDS %s\n' % contaminant . numIDs ) # Write value lines self . _writeValues ( session , fileObject , mapTable , contaminant , replaceParamFile ) | This method writes the contaminant transport mapping table case . | 341 | 11 |
4,717 | def _writeSedimentTable ( self , session , fileObject , mapTable , replaceParamFile ) : # Write the sediment mapping table header fileObject . write ( '%s\n' % ( mapTable . name ) ) fileObject . write ( 'NUM_SED %s\n' % ( mapTable . numSed ) ) # Write the value header line fileObject . write ( 'Sediment Description%sSpec. Grav%sPart. Dia%sOutput Filename\n' % ( ' ' * 22 , ' ' * 3 , ' ' * 5 ) ) # Retrive the sediment mapping table values sediments = session . query ( MTSediment ) . filter ( MTSediment . mapTable == mapTable ) . order_by ( MTSediment . id ) . all ( ) # Write sediments out to file for sediment in sediments : # Determine spacing for aesthetics space1 = 42 - len ( sediment . description ) # Pad values with zeros / Get replacement variable specGravString = vwp ( sediment . specificGravity , replaceParamFile ) partDiamString = vwp ( sediment . particleDiameter , replaceParamFile ) try : specGrav = '%.6f' % specGravString except : specGrav = '%s' % specGravString try : partDiam = '%.6f' % partDiamString except : partDiam = '%s' % partDiamString fileObject . write ( '%s%s%s%s%s%s%s\n' % ( sediment . description , ' ' * space1 , specGrav , ' ' * 5 , partDiam , ' ' * 6 , sediment . outputFilename ) ) | Write Sediment Mapping Table Method | 373 | 7 |
4,718 | def _preprocessContaminantOutFilePath ( outPath ) : if '/' in outPath : splitPath = outPath . split ( '/' ) elif '\\' in outPath : splitPath = outPath . split ( '\\' ) else : splitPath = [ outPath , ] if splitPath [ - 1 ] == '' : outputFilename = splitPath [ - 2 ] else : outputFilename = splitPath [ - 1 ] if '.' in outputFilename : outputFilename = outputFilename . split ( '.' ) [ 0 ] return outputFilename | Preprocess the contaminant output file path to a relative path . | 118 | 13 |
4,719 | def _set_wildcards ( self , inputs = None , outputs = None ) : w = self . _wildcards = set ( ) # Clean wildcards. if outputs and inputs : node , wi = self . nodes , self . _wait_in . get # Namespace shortcut. # Input data nodes that are in output_targets. w_crd = { u : node [ u ] for u in inputs if u in outputs or wi ( u , False ) } # Data nodes without the wildcard. w . update ( [ k for k , v in w_crd . items ( ) if v . get ( 'wildcard' , True ) ] ) | Update wildcards set with the input data nodes that are also outputs . | 142 | 14 |
4,720 | def result ( self , timeout = None ) : it , exceptions , future_lists = [ ] , [ ] , [ ] from concurrent . futures import Future , wait as wait_fut def update ( fut , data , key ) : if isinstance ( fut , Future ) : it . append ( ( fut , data , key ) ) elif isinstance ( fut , AsyncList ) and fut not in future_lists : future_lists . append ( fut ) it . extend ( [ ( j , fut , i ) for i , j in enumerate ( fut ) if isinstance ( j , Future ) ] [ : : - 1 ] ) for s in self . sub_sol . values ( ) : for k , v in list ( s . items ( ) ) : update ( v , s , k ) for d in s . workflow . nodes . values ( ) : if 'results' in d : update ( d [ 'results' ] , d , 'results' ) for d in s . workflow . edges . values ( ) : if 'value' in d : update ( d [ 'value' ] , d , 'value' ) wait_fut ( { v [ 0 ] for v in it } , timeout ) for f , d , k in it : try : d [ k ] = await_result ( f , 0 ) except SkipNode as e : exceptions . append ( ( f , d , k , e . ex ) ) del d [ k ] except ( Exception , ExecutorShutdown , DispatcherAbort ) as ex : exceptions . append ( ( f , d , k , ex ) ) del d [ k ] if exceptions : raise exceptions [ 0 ] [ - 1 ] return self | Set all asynchronous results . | 360 | 5 |
4,721 | def _check_targets ( self ) : if self . outputs : targets = self . outputs . copy ( ) # Namespace shortcut for speed. def check_targets ( node_id ) : """ Terminates ArciDispatch algorithm when all targets have been visited. :param node_id: Data or function node id. :type node_id: str :return: True if all targets have been visited, otherwise False. :rtype: bool """ try : targets . remove ( node_id ) # Remove visited node. return not targets # If no targets terminate the algorithm. except KeyError : # The node is not in the targets set. return False else : # noinspection PyUnusedLocal def check_targets ( node_id ) : return False return check_targets | Returns a function to terminate the ArciDispatch algorithm when all targets have been visited . | 169 | 17 |
4,722 | def _get_node_estimations ( self , node_attr , node_id ) : # Get data node estimations. estimations = self . _wf_pred [ node_id ] wait_in = node_attr [ 'wait_inputs' ] # Namespace shortcut. # Check if node has multiple estimations and it is not waiting inputs. if len ( estimations ) > 1 and not self . _wait_in . get ( node_id , wait_in ) : # Namespace shortcuts. dist , edg_length , adj = self . dist , self . _edge_length , self . dmap . adj est = [ ] # Estimations' heap. for k , v in estimations . items ( ) : # Calculate length. if k is not START : d = dist [ k ] + edg_length ( adj [ k ] [ node_id ] , node_attr ) heapq . heappush ( est , ( d , k , v ) ) # The estimation with minimum distance from the starting node. estimations = { est [ 0 ] [ 1 ] : est [ 0 ] [ 2 ] } # Remove unused workflow edges. self . workflow . remove_edges_from ( [ ( v [ 1 ] , node_id ) for v in est [ 1 : ] ] ) return estimations , wait_in | Returns the data nodes estimations and wait_inputs flag . | 290 | 13 |
4,723 | def _set_node_output ( self , node_id , no_call , next_nds = None , * * kw ) : # Namespace shortcuts. node_attr = self . nodes [ node_id ] node_type = node_attr [ 'type' ] if node_type == 'data' : # Set data node. return self . _set_data_node_output ( node_id , node_attr , no_call , next_nds , * * kw ) elif node_type == 'function' : # Set function node. return self . _set_function_node_output ( node_id , node_attr , no_call , next_nds , * * kw ) | Set the node outputs from node inputs . | 157 | 8 |
4,724 | def _set_data_node_output ( self , node_id , node_attr , no_call , next_nds = None , * * kw ) : # Get data node estimations. est , wait_in = self . _get_node_estimations ( node_attr , node_id ) if not no_call : if node_id is PLOT : est = est . copy ( ) est [ PLOT ] = { 'value' : { 'obj' : self } } sf , args = False , ( { k : v [ 'value' ] for k , v in est . items ( ) } , ) if not ( wait_in or 'function' in node_attr ) : # Data node that has just one estimation value. sf , args = True , tuple ( args [ 0 ] . values ( ) ) try : # Final estimation of the node and node status. value = async_thread ( self , args , node_attr , node_id , sf , * * kw ) except SkipNode : return False if value is not NONE : # Set data output. self [ node_id ] = value value = { 'value' : value } # Output value. else : self [ node_id ] = NONE # Set data output. value = { } # Output value. if next_nds : # namespace shortcuts for speed. wf_add_edge = self . _wf_add_edge for u in next_nds : # Set workflow. wf_add_edge ( node_id , u , * * value ) else : # namespace shortcuts for speed. n , has , sub_sol = self . nodes , self . workflow . has_edge , self . sub_sol def no_visited_in_sub_dsp ( i ) : node = n [ i ] if node [ 'type' ] == 'dispatcher' and has ( i , node_id ) : visited = sub_sol [ self . index + node [ 'index' ] ] . _visited return node [ 'inputs' ] [ node_id ] not in visited return True # List of functions. succ_fun = [ u for u in self . _succ [ node_id ] if no_visited_in_sub_dsp ( u ) ] # Check if it has functions as outputs and wildcard condition. if succ_fun and succ_fun [ 0 ] not in self . _visited : # namespace shortcuts for speed. wf_add_edge = self . _wf_add_edge for u in succ_fun : # Set workflow. wf_add_edge ( node_id , u , * * value ) return True | Set the data node output from node estimations . | 582 | 10 |
4,725 | def _set_function_node_output ( self , node_id , node_attr , no_call , next_nds = None , * * kw ) : # Namespace shortcuts for speed. o_nds , dist = node_attr [ 'outputs' ] , self . dist # List of nodes that can still be estimated by the function node. output_nodes = next_nds or set ( self . _succ [ node_id ] ) . difference ( dist ) if not output_nodes : # This function is not needed. self . workflow . remove_node ( node_id ) # Remove function node. return False wf_add_edge = self . _wf_add_edge # Namespace shortcuts for speed. if no_call : for u in output_nodes : # Set workflow out. wf_add_edge ( node_id , u ) return True args = self . _wf_pred [ node_id ] # List of the function's arguments. args = [ args [ k ] [ 'value' ] for k in node_attr [ 'inputs' ] ] try : self . _check_function_domain ( args , node_attr , node_id ) res = async_thread ( self , args , node_attr , node_id , * * kw ) # noinspection PyUnresolvedReferences self . workflow . node [ node_id ] [ 'results' ] = res except SkipNode : return False # Set workflow. for k , v in zip ( o_nds , res if len ( o_nds ) > 1 else [ res ] ) : if k in output_nodes and v is not NONE : wf_add_edge ( node_id , k , value = v ) return True | Set the function node output from node inputs . | 384 | 9 |
4,726 | def _add_initial_value ( self , data_id , value , initial_dist = 0.0 , fringe = None , check_cutoff = None , no_call = None ) : # Namespace shortcuts for speed. nodes , seen , edge_weight = self . nodes , self . seen , self . _edge_length wf_remove_edge , check_wait_in = self . _wf_remove_edge , self . check_wait_in wf_add_edge , dsp_in = self . _wf_add_edge , self . _set_sub_dsp_node_input update_view = self . _update_meeting if fringe is None : fringe = self . fringe if no_call is None : no_call = self . no_call check_cutoff = check_cutoff or self . check_cutoff if data_id not in nodes : # Data node is not in the dmap. return False wait_in = nodes [ data_id ] [ 'wait_inputs' ] # Store wait inputs flag. index = nodes [ data_id ] [ 'index' ] # Store node index. wf_add_edge ( START , data_id , * * value ) # Add edge. if data_id in self . _wildcards : # Check if the data node has wildcard. self . _visited . add ( data_id ) # Update visited nodes. self . workflow . add_node ( data_id ) # Add node to workflow. for w , edge_data in self . dmap [ data_id ] . items ( ) : # See func node. wf_add_edge ( data_id , w , * * value ) # Set workflow. node = nodes [ w ] # Node attributes. # Evaluate distance. vw_dist = initial_dist + edge_weight ( edge_data , node ) update_view ( w , vw_dist ) # Update view distance. # Check the cutoff limit and if all inputs are satisfied. if check_cutoff ( vw_dist ) : wf_remove_edge ( data_id , w ) # Remove workflow edge. continue # Pass the node. elif node [ 'type' ] == 'dispatcher' : dsp_in ( data_id , w , fringe , check_cutoff , no_call , vw_dist ) elif check_wait_in ( True , w ) : continue # Pass the node. seen [ w ] = vw_dist # Update distance. vd = ( True , w , self . index + node [ 'index' ] ) # Virtual distance. heapq . heappush ( fringe , ( vw_dist , vd , ( w , self ) ) ) # Add 2 heapq. return True update_view ( data_id , initial_dist ) # Update view distance. if check_cutoff ( initial_dist ) : # Check the cutoff limit. wf_remove_edge ( START , data_id ) # Remove workflow edge. elif not check_wait_in ( wait_in , data_id ) : # Check inputs. seen [ data_id ] = initial_dist # Update distance. vd = ( wait_in , data_id , self . index + index ) # Virtual distance. # Add node to heapq. heapq . heappush ( fringe , ( initial_dist , vd , ( data_id , self ) ) ) return True return False | Add initial values updating workflow seen and fringe . | 750 | 9 |
4,727 | def _visit_nodes ( self , node_id , dist , fringe , check_cutoff , no_call = False , * * kw ) : # Namespace shortcuts. wf_rm_edge , wf_has_edge = self . _wf_remove_edge , self . workflow . has_edge edge_weight , nodes = self . _edge_length , self . nodes self . dist [ node_id ] = dist # Set minimum dist. self . _visited . add ( node_id ) # Update visited nodes. if not self . _set_node_output ( node_id , no_call , * * kw ) : # Set output. # Some error occurs or inputs are not in the function domain. return True if self . check_targets ( node_id ) : # Check if the targets are satisfied. return False # Stop loop. for w , e_data in self . dmap [ node_id ] . items ( ) : if not wf_has_edge ( node_id , w ) : # Check wildcard option. continue node = nodes [ w ] # Get node attributes. vw_d = dist + edge_weight ( e_data , node ) # Evaluate dist. if check_cutoff ( vw_d ) : # Check the cutoff limit. wf_rm_edge ( node_id , w ) # Remove edge that cannot be see. continue if node [ 'type' ] == 'dispatcher' : self . _set_sub_dsp_node_input ( node_id , w , fringe , check_cutoff , no_call , vw_d ) else : # See the node. self . _see_node ( w , fringe , vw_d ) return True | Visits a node updating workflow seen and fringe .. | 383 | 10 |
4,728 | def _see_node ( self , node_id , fringe , dist , w_wait_in = 0 ) : # Namespace shortcuts. seen , dists = self . seen , self . dist wait_in = self . nodes [ node_id ] [ 'wait_inputs' ] # Wait inputs flag. self . _update_meeting ( node_id , dist ) # Update view distance. # Check if inputs are satisfied. if self . check_wait_in ( wait_in , node_id ) : pass # Pass the node elif node_id in dists : # The node w already estimated. if dist < dists [ node_id ] : # Error for negative paths. raise DispatcherError ( 'Contradictory paths found: ' 'negative weights?' , sol = self ) elif node_id not in seen or dist < seen [ node_id ] : # Check min dist. seen [ node_id ] = dist # Update dist. index = self . nodes [ node_id ] [ 'index' ] # Node index. # Virtual distance. vd = ( w_wait_in + int ( wait_in ) , node_id , self . index + index ) # Add to heapq. heapq . heappush ( fringe , ( dist , vd , ( node_id , self ) ) ) return True # The node is visible. return False | See a node updating seen and fringe . | 298 | 8 |
4,729 | def _remove_unused_nodes ( self ) : # Namespace shortcuts. nodes , wf_remove_node = self . nodes , self . workflow . remove_node add_visited , succ = self . _visited . add , self . workflow . succ # Remove unused function and sub-dispatcher nodes. for n in ( set ( self . _wf_pred ) - set ( self . _visited ) ) : node_type = nodes [ n ] [ 'type' ] # Node type. if node_type == 'data' : continue # Skip data node. if node_type == 'dispatcher' and succ [ n ] : add_visited ( n ) # Add to visited nodes. i = self . index + nodes [ n ] [ 'index' ] self . sub_sol [ i ] . _remove_unused_nodes ( ) continue # Skip sub-dispatcher node with outputs. wf_remove_node ( n ) | Removes unused function and sub - dispatcher nodes . | 211 | 10 |
4,730 | def _init_sub_dsp ( self , dsp , fringe , outputs , no_call , initial_dist , index , full_name ) : # Initialize as sub-dispatcher. sol = self . __class__ ( dsp , { } , outputs , False , None , None , no_call , False , wait_in = self . _wait_in . get ( dsp , None ) , index = self . index + index , full_name = full_name ) sol . sub_sol = self . sub_sol for f in sol . fringe : # Update the fringe. item = ( initial_dist + f [ 0 ] , ( 2 , ) + f [ 1 ] [ 1 : ] , f [ - 1 ] ) heapq . heappush ( fringe , item ) return sol | Initialize the dispatcher as sub - dispatcher and update the fringe . | 174 | 13 |
4,731 | def _set_sub_dsp_node_input ( self , node_id , dsp_id , fringe , check_cutoff , no_call , initial_dist ) : # Namespace shortcuts. node = self . nodes [ dsp_id ] dsp , pred = node [ 'function' ] , self . _wf_pred [ dsp_id ] distances , sub_sol = self . dist , self . sub_sol iv_nodes = [ node_id ] # Nodes do be added as initial values. self . _meet [ dsp_id ] = initial_dist # Set view distance. # Check if inputs are satisfied. if self . check_wait_in ( node [ 'wait_inputs' ] , dsp_id ) : return False # Pass the node if dsp_id not in distances : kw = { } dom = self . _check_sub_dsp_domain ( dsp_id , node , pred , kw ) if dom is True : iv_nodes = pred # Args respect the domain. elif dom is False : return False # Initialize the sub-dispatcher. sub_sol [ self . index + node [ 'index' ] ] = sol = self . _init_sub_dsp ( dsp , fringe , node [ 'outputs' ] , no_call , initial_dist , node [ 'index' ] , self . full_name + ( dsp_id , ) ) self . workflow . add_node ( dsp_id , solution = sol , * * kw ) distances [ dsp_id ] = initial_dist # Update min distance. else : sol = sub_sol [ self . index + node [ 'index' ] ] for n_id in iv_nodes : # Namespace shortcuts. val = pred [ n_id ] for n in stlp ( node [ 'inputs' ] [ n_id ] ) : # Add initial value to the sub-dispatcher. sol . _add_initial_value ( n , val , initial_dist , fringe , check_cutoff , no_call ) return True | Initializes the sub - dispatcher and set its inputs . | 461 | 11 |
4,732 | def _warning ( self , msg , node_id , ex , * args , * * kwargs ) : raises = self . raises ( ex ) if callable ( self . raises ) else self . raises if raises and isinstance ( ex , DispatcherError ) : ex . update ( self ) raise ex self . _errors [ node_id ] = msg % ( ( node_id , ex ) + args ) node_id = '/' . join ( self . full_name + ( node_id , ) ) if raises : raise DispatcherError ( msg , node_id , ex , * args , sol = self , * * kwargs ) else : kwargs [ 'exc_info' ] = kwargs . get ( 'exc_info' , 1 ) log . error ( msg , node_id , ex , * args , * * kwargs ) | Handles the error messages . | 189 | 6 |
4,733 | def _read ( self , directory , filename , session , path , name , extension , spatial , spatialReferenceID , replaceParamFile ) : # Set file extension property self . fileExtension = extension # Keywords KEYWORDS = ( 'STREAMCELLS' , 'CELLIJ' ) # Parse file into chunks associated with keywords/cards with open ( path , 'r' ) as f : chunks = pt . chunk ( KEYWORDS , f ) # Parse chunks associated with each key for key , chunkList in iteritems ( chunks ) : # Parse each chunk in the chunk list for chunk in chunkList : # Cases if key == 'STREAMCELLS' : # PIPECELLS Handler schunk = chunk [ 0 ] . strip ( ) . split ( ) self . streamCells = schunk [ 1 ] elif key == 'CELLIJ' : # CELLIJ Handler # Parse CELLIJ Chunk result = self . _cellChunk ( chunk ) # Create GSSHAPY object self . _createGsshaPyObjects ( result ) | Grid Stream File Read from File Method | 234 | 7 |
4,734 | def _write ( self , session , openFile , replaceParamFile ) : # Write lines openFile . write ( 'GRIDSTREAMFILE\n' ) openFile . write ( 'STREAMCELLS %s\n' % self . streamCells ) for cell in self . gridStreamCells : openFile . write ( 'CELLIJ %s %s\n' % ( cell . cellI , cell . cellJ ) ) openFile . write ( 'NUMNODES %s\n' % cell . numNodes ) for node in cell . gridStreamNodes : openFile . write ( 'LINKNODE %s %s %.6f\n' % ( node . linkNumber , node . nodeNumber , node . nodePercentGrid ) ) | Grid Stream File Write to File Method | 168 | 7 |
4,735 | def _createGsshaPyObjects ( self , cell ) : # Initialize GSSHAPY PipeGridCell object gridCell = GridStreamCell ( cellI = cell [ 'i' ] , cellJ = cell [ 'j' ] , numNodes = cell [ 'numNodes' ] ) # Associate GridStreamCell with GridStreamFile gridCell . gridStreamFile = self for linkNode in cell [ 'linkNodes' ] : # Create GSSHAPY GridStreamNode object gridNode = GridStreamNode ( linkNumber = linkNode [ 'linkNumber' ] , nodeNumber = linkNode [ 'nodeNumber' ] , nodePercentGrid = linkNode [ 'percent' ] ) # Associate GridStreamNode with GridStreamCell gridNode . gridStreamCell = gridCell | Create GSSHAPY PipeGridCell and PipeGridNode Objects Method | 169 | 15 |
4,736 | def _read ( self , directory , filename , session , path , name , extension , spatial , spatialReferenceID , replaceParamFile ) : # Set file extension property self . fileExtension = extension # Open file and read plain text into text field with open ( path , 'r' ) as f : self . rasterText = f . read ( ) # Retrieve metadata from header lines = self . rasterText . split ( '\n' ) for line in lines [ 0 : 6 ] : spline = line . split ( ) if 'north' in spline [ 0 ] . lower ( ) : self . north = float ( spline [ 1 ] ) elif 'south' in spline [ 0 ] . lower ( ) : self . south = float ( spline [ 1 ] ) elif 'east' in spline [ 0 ] . lower ( ) : self . east = float ( spline [ 1 ] ) elif 'west' in spline [ 0 ] . lower ( ) : self . west = float ( spline [ 1 ] ) elif 'rows' in spline [ 0 ] . lower ( ) : self . rows = int ( spline [ 1 ] ) elif 'cols' in spline [ 0 ] . lower ( ) : self . columns = int ( spline [ 1 ] ) if spatial : # Get well known binary from the raster file using the MapKit RasterLoader wkbRaster = RasterLoader . grassAsciiRasterToWKB ( session = session , grassRasterPath = path , srid = str ( spatialReferenceID ) , noData = '-1' ) self . raster = wkbRaster self . srid = spatialReferenceID # Assign other properties self . filename = filename | Index Map Read from File Method | 376 | 6 |
4,737 | def write ( self , directory , name = None , session = None , replaceParamFile = None ) : # Initiate file if name != None : filename = '%s.%s' % ( name , self . fileExtension ) filePath = os . path . join ( directory , filename ) else : filePath = os . path . join ( directory , self . filename ) # If the raster field is not empty, write from this field if type ( self . raster ) != type ( None ) : # Configure RasterConverter converter = RasterConverter ( session ) # Use MapKit RasterConverter to retrieve the raster as a GRASS ASCII Grid grassAsciiGrid = converter . getAsGrassAsciiRaster ( rasterFieldName = 'raster' , tableName = self . __tablename__ , rasterIdFieldName = 'id' , rasterId = self . id ) # Write to file with open ( filePath , 'w' ) as mapFile : mapFile . write ( grassAsciiGrid ) else : if self . rasterText is not None : # Open file and write, raster_text only with open ( filePath , 'w' ) as mapFile : mapFile . write ( self . rasterText ) | Index Map Write to File Method | 280 | 6 |
4,738 | def _write ( self , session , openFile , replaceParamFile ) : # Write Lines openFile . write ( 'GRIDPIPEFILE\n' ) openFile . write ( 'PIPECELLS %s\n' % self . pipeCells ) for cell in self . gridPipeCells : openFile . write ( 'CELLIJ %s %s\n' % ( cell . cellI , cell . cellJ ) ) openFile . write ( 'NUMPIPES %s\n' % cell . numPipes ) for node in cell . gridPipeNodes : openFile . write ( 'SPIPE %s %s %.6f\n' % ( node . linkNumber , node . nodeNumber , node . fractPipeLength ) ) | Grid Pipe File Write to File Method | 171 | 7 |
4,739 | def _createGsshaPyObjects ( self , cell ) : # Initialize GSSHAPY GridPipeCell object gridCell = GridPipeCell ( cellI = cell [ 'i' ] , cellJ = cell [ 'j' ] , numPipes = cell [ 'numPipes' ] ) # Associate GridPipeCell with GridPipeFile gridCell . gridPipeFile = self for spipe in cell [ 'spipes' ] : # Create GSSHAPY GridPipeNode object gridNode = GridPipeNode ( linkNumber = spipe [ 'linkNumber' ] , nodeNumber = spipe [ 'nodeNumber' ] , fractPipeLength = spipe [ 'fraction' ] ) # Associate GridPipeNode with GridPipeCell gridNode . gridPipeCell = gridCell | Create GSSHAPY GridPipeCell and GridPipeNode Objects Method | 180 | 17 |
4,740 | def _cellChunk ( self , lines ) : KEYWORDS = ( 'CELLIJ' , 'NUMPIPES' , 'SPIPE' ) result = { 'i' : None , 'j' : None , 'numPipes' : None , 'spipes' : [ ] } chunks = pt . chunk ( KEYWORDS , lines ) # Parse chunks associated with each key for card , chunkList in iteritems ( chunks ) : # Parse each chunk in the chunk list for chunk in chunkList : schunk = chunk [ 0 ] . strip ( ) . split ( ) # Cases if card == 'CELLIJ' : # CELLIJ handler result [ 'i' ] = schunk [ 1 ] result [ 'j' ] = schunk [ 2 ] elif card == 'NUMPIPES' : # NUMPIPES handler result [ 'numPipes' ] = schunk [ 1 ] elif card == 'SPIPE' : # SPIPE handler pipe = { 'linkNumber' : schunk [ 1 ] , 'nodeNumber' : schunk [ 2 ] , 'fraction' : schunk [ 3 ] } result [ 'spipes' ] . append ( pipe ) return result | Parse CELLIJ Chunk Method | 264 | 8 |
4,741 | def _read ( self , directory , filename , session , path , name , extension , spatial , spatialReferenceID , replaceParamFile ) : # Set file extension property self . fileExtension = extension # Open file and parse into a data structure with open ( path , 'r' ) as f : for line in f : sline = line . strip ( ) . split ( ) if len ( sline ) == 1 : self . numParameters = sline [ 0 ] else : # Create GSSHAPY TargetParameter object target = TargetParameter ( targetVariable = sline [ 0 ] , varFormat = sline [ 1 ] ) # Associate TargetParameter with ReplaceParamFile target . replaceParamFile = self | Replace Param File Read from File Method | 148 | 8 |
4,742 | def _write ( self , session , openFile , replaceParamFile ) : # Retrieve TargetParameter objects targets = self . targetParameters # Write lines openFile . write ( '%s\n' % self . numParameters ) for target in targets : openFile . write ( '%s %s\n' % ( target . targetVariable , target . varFormat ) ) | Replace Param File Write to File Method | 79 | 8 |
4,743 | def _read ( self , directory , filename , session , path , name , extension , spatial , spatialReferenceID , replaceParamFile ) : # Set file extension property self . fileExtension = extension # Open file and parse into a data structure with open ( path , 'r' ) as f : for line in f : valLine = ReplaceValLine ( ) valLine . contents = line valLine . replaceValFile = self | Replace Val File Read from File Method | 89 | 8 |
4,744 | def _write ( self , session , openFile , replaceParamFile ) : # Write lines for line in self . lines : openFile . write ( line . contents ) | Replace Val File Write to File Method | 35 | 8 |
4,745 | def emit ( self , data_frame ) : if self . result is not None : raise MultipleEmitsError ( ) data_frame . columns = [ self . prefix + '__' + c for c in data_frame . columns ] self . result = data_frame | Use this function in emit data into the store . | 57 | 10 |
4,746 | def trigger_hats ( self , command , arg = None , callback = None ) : threads = [ ] for scriptable in [ self . project . stage ] + self . project . sprites : threads += self . trigger_scriptable_hats ( scriptable , command , arg , callback ) return threads | Returns a list with each script that is triggered . | 64 | 10 |
4,747 | def push_script ( self , scriptable , script , callback = None ) : if script in self . threads : self . threads [ script ] . finish ( ) thread = Thread ( self . run_script ( scriptable , script ) , scriptable , callback ) self . new_threads [ script ] = thread return thread | Run the script and add it to the list of threads . | 68 | 12 |
4,748 | def tick ( self , events ) : self . add_new_threads ( ) if self . drag_sprite : ( mx , my ) = self . screen . get_mouse_pos ( ) ( ox , oy ) = self . drag_offset new_position = ( mx + ox , my + oy ) if self . drag_sprite . position != new_position : self . has_dragged = True self . drag_sprite . position = new_position for event in events : if event . kind == "key_pressed" : assert event . value in kurt . Insert ( None , "key" ) . options ( ) self . trigger_hats ( "whenKeyPressed" , event . value ) elif event . kind == "mouse_down" : mouse_pos = self . screen . get_mouse_pos ( ) for sprite in reversed ( self . project . sprites ) : rect = bounds ( sprite ) if rect . collide_point ( mouse_pos ) : if self . screen . touching_mouse ( sprite ) : scriptable = sprite break else : scriptable = self . project . stage if scriptable . is_draggable : ( mx , my ) = self . screen . get_mouse_pos ( ) ( x , y ) = scriptable . position self . drag_offset = ( x - mx , y - my ) self . drag_sprite = scriptable self . has_dragged = False go_to_front ( scriptable ) else : self . trigger_scriptable_hats ( scriptable , "whenClicked" ) elif event . kind == "mouse_up" : if self . drag_sprite : if not self . has_dragged : self . trigger_scriptable_hats ( self . drag_sprite , "whenClicked" ) self . drag_sprite = None remove_threads = [ ] while 1 : for ( script , thread ) in self . threads . items ( ) : modified = False for event in thread . tick ( ) : if event . kind == "stop" : if event . value == "all" : self . stop ( ) return elif event . value == "other scripts in sprite" : for ( script , other ) in self . threads . items ( ) : if other . scriptable == thread . scriptable : other . finish ( ) del self . threads [ script ] modified = True break else : thread . finish ( ) del self . threads [ script ] modified = True break else : # Pass to Screen yield event if modified : break else : break self . add_new_threads ( ) | Execute one frame of the interpreter . | 561 | 8 |
4,749 | def stop ( self ) : self . threads = { } self . new_threads = { } self . answer = "" self . ask_lock = False | Stop running threads . | 33 | 4 |
4,750 | def evaluate ( self , s , value , insert = None ) : assert not isinstance ( value , kurt . Script ) if insert and insert . unevaluated : return value if isinstance ( value , kurt . Block ) : if value . type . shape == "hat" : return [ ] if value . type not in self . COMMANDS : if getattr ( value . type , '_workaround' , None ) : value = value . type . _workaround ( value ) if not value : raise kurt . BlockNotSupported ( value . type ) else : raise kurt . BlockNotSupported ( value . type ) f = self . COMMANDS [ value . type ] args = [ self . evaluate ( s , arg , arg_insert ) for ( arg , arg_insert ) in zip ( list ( value . args ) , value . type . inserts ) ] value = f ( s , * args ) def flatten_generators ( gen ) : for item in gen : if inspect . isgenerator ( item ) : for x in flatten_generators ( item ) : yield x else : yield item if inspect . isgenerator ( value ) : value = flatten_generators ( value ) if value is None : value = [ ] if insert : if isinstance ( value , basestring ) : value = unicode ( value ) if insert . shape in ( "number" , "number-menu" , "string" ) : try : value = float ( value ) except ( TypeError , ValueError ) : if insert . shape == "number" : value = 0 if isinstance ( value , float ) and value == int ( value ) : value = int ( value ) if insert . kind in ( "spriteOrStage" , "spriteOrMouse" , "stageOrThis" , "spriteOnly" , "touching" ) : if value not in ( "mouse-pointer" , "edge" ) : value = ( self . project . stage if value == "Stage" else self . project . get_sprite ( value ) ) elif insert . kind == "var" : if value in s . variables : value = s . variables [ value ] else : value = s . project . variables [ value ] elif insert . kind == "list" : if value in s . lists : value = s . lists [ value ] else : value = s . project . lists [ value ] elif insert . kind == "sound" : for sound in s . sounds : if sound . name == value : value = sound break return value | Expression evaluator . | 545 | 6 |
4,751 | def get_cluster_name ( self ) : return self . _get ( url = self . url + '/api/cluster-name' , headers = self . headers , auth = self . auth ) | Name identifying this RabbitMQ cluster . | 44 | 7 |
4,752 | def get_connection ( self , name ) : return self . _api_get ( '/api/connections/{0}' . format ( urllib . parse . quote_plus ( name ) ) ) | An individual connection . | 45 | 4 |
4,753 | def delete_connection ( self , name , reason = None ) : headers = { 'X-Reason' : reason } if reason else { } self . _api_delete ( '/api/connections/{0}' . format ( urllib . parse . quote_plus ( name ) ) , headers = headers , ) | Closes an individual connection . Give an optional reason | 69 | 10 |
4,754 | def list_connection_channels ( self , name ) : return self . _api_get ( '/api/connections/{0}/channels' . format ( urllib . parse . quote_plus ( name ) ) ) | List of all channels for a given connection . | 51 | 9 |
4,755 | def get_channel ( self , name ) : return self . _api_get ( '/api/channels/{0}' . format ( urllib . parse . quote_plus ( name ) ) ) | Details about an individual channel . | 45 | 6 |
4,756 | def list_consumers_for_vhost ( self , vhost ) : return self . _api_get ( '/api/consumers/{0}' . format ( urllib . parse . quote_plus ( vhost ) ) ) | A list of all consumers in a given virtual host . | 53 | 11 |
4,757 | def list_exchanges_for_vhost ( self , vhost ) : return self . _api_get ( '/api/exchanges/{0}' . format ( urllib . parse . quote_plus ( vhost ) ) ) | A list of all exchanges in a given virtual host . | 53 | 11 |
4,758 | def get_exchange_for_vhost ( self , exchange , vhost ) : return self . _api_get ( '/api/exchanges/{0}/{1}' . format ( urllib . parse . quote_plus ( vhost ) , urllib . parse . quote_plus ( exchange ) ) ) | An individual exchange | 72 | 3 |
4,759 | def delete_exchange_for_vhost ( self , exchange , vhost , if_unused = False ) : self . _api_delete ( '/api/exchanges/{0}/{1}' . format ( urllib . parse . quote_plus ( vhost ) , urllib . parse . quote_plus ( exchange ) ) , params = { 'if-unused' : if_unused } , ) | Delete an individual exchange . You can add the parameter if_unused = True . This prevents the delete from succeeding if the exchange is bound to a queue or as a source to another exchange . | 95 | 39 |
4,760 | def list_bindings_for_vhost ( self , vhost ) : return self . _api_get ( '/api/bindings/{}' . format ( urllib . parse . quote_plus ( vhost ) ) ) | A list of all bindings in a given virtual host . | 52 | 11 |
4,761 | def get_vhost ( self , name ) : return self . _api_get ( '/api/vhosts/{0}' . format ( urllib . parse . quote_plus ( name ) ) ) | Details about an individual vhost . | 47 | 7 |
4,762 | def create_vhost ( self , name , tracing = False ) : data = { 'tracing' : True } if tracing else { } self . _api_put ( '/api/vhosts/{0}' . format ( urllib . parse . quote_plus ( name ) ) , data = data , ) | Create an individual vhost . | 70 | 6 |
4,763 | def get_user ( self , name ) : return self . _api_get ( '/api/users/{0}' . format ( urllib . parse . quote_plus ( name ) ) ) | Details about an individual user . | 44 | 6 |
4,764 | def list_user_permissions ( self , name ) : return self . _api_get ( '/api/users/{0}/permissions' . format ( urllib . parse . quote_plus ( name ) ) ) | A list of all permissions for a given user . | 50 | 10 |
4,765 | def list_policies_for_vhost ( self , vhost ) : return self . _api_get ( '/api/policies/{0}' . format ( urllib . parse . quote_plus ( vhost ) ) ) | A list of all policies for a vhost . | 55 | 10 |
4,766 | def get_policy_for_vhost ( self , vhost , name ) : return self . _api_get ( '/api/policies/{0}/{1}' . format ( urllib . parse . quote_plus ( vhost ) , urllib . parse . quote_plus ( name ) , ) ) | Get a specific policy for a vhost . | 73 | 9 |
4,767 | def create_policy_for_vhost ( self , vhost , name , definition , pattern = None , priority = 0 , apply_to = 'all' ) : data = { "pattern" : pattern , "definition" : definition , "priority" : priority , "apply-to" : apply_to } self . _api_put ( '/api/policies/{0}/{1}' . format ( urllib . parse . quote_plus ( vhost ) , urllib . parse . quote_plus ( name ) , ) , data = data , ) | Create a policy for a vhost . | 126 | 8 |
4,768 | def delete_policy_for_vhost ( self , vhost , name ) : self . _api_delete ( '/api/policies/{0}/{1}/' . format ( urllib . parse . quote_plus ( vhost ) , urllib . parse . quote_plus ( name ) , ) ) | Delete a specific policy for a vhost . | 73 | 9 |
4,769 | def is_vhost_alive ( self , vhost ) : return self . _api_get ( '/api/aliveness-test/{0}' . format ( urllib . parse . quote_plus ( vhost ) ) ) | Declares a test queue then publishes and consumes a message . Intended for use by monitoring tools . | 53 | 20 |
4,770 | def write ( self , session , directory , name , maskMap ) : # Assemble Path to file name_split = name . split ( '.' ) name = name_split [ 0 ] # Default extension extension = '' if len ( name_split ) >= 2 : extension = name_split [ - 1 ] # Run name preprocessor method if present try : name = self . _namePreprocessor ( name ) except : 'DO NOTHING' if extension == '' : filename = '{0}.{1}' . format ( name , self . fileExtension ) else : filename = '{0}.{1}' . format ( name , extension ) filePath = os . path . join ( directory , filename ) with open ( filePath , 'w' ) as openFile : # Write Lines self . _write ( session = session , openFile = openFile , maskMap = maskMap ) | Write from database to file . | 190 | 6 |
4,771 | def getAsKmlGridAnimation ( self , session , projectFile = None , path = None , documentName = None , colorRamp = None , alpha = 1.0 , noDataValue = 0.0 ) : # Prepare rasters timeStampedRasters = self . _assembleRasterParams ( projectFile , self . rasters ) # Create a raster converter converter = RasterConverter ( sqlAlchemyEngineOrSession = session ) # Configure color ramp if isinstance ( colorRamp , dict ) : converter . setCustomColorRamp ( colorRamp [ 'colors' ] , colorRamp [ 'interpolatedPoints' ] ) else : converter . setDefaultColorRamp ( colorRamp ) if documentName is None : documentName = self . fileExtension kmlString = converter . getAsKmlGridAnimation ( tableName = WMSDatasetRaster . tableName , timeStampedRasters = timeStampedRasters , rasterIdFieldName = 'id' , rasterFieldName = 'raster' , documentName = documentName , alpha = alpha , noDataValue = noDataValue ) if path : with open ( path , 'w' ) as f : f . write ( kmlString ) return kmlString | Retrieve the WMS dataset as a gridded time stamped KML string . | 276 | 17 |
4,772 | def getAsKmlPngAnimation ( self , session , projectFile = None , path = None , documentName = None , colorRamp = None , alpha = 1.0 , noDataValue = 0 , drawOrder = 0 , cellSize = None , resampleMethod = 'NearestNeighbour' ) : # Prepare rasters timeStampedRasters = self . _assembleRasterParams ( projectFile , self . rasters ) # Make sure the raster field is valid converter = RasterConverter ( sqlAlchemyEngineOrSession = session ) # Configure color ramp if isinstance ( colorRamp , dict ) : converter . setCustomColorRamp ( colorRamp [ 'colors' ] , colorRamp [ 'interpolatedPoints' ] ) else : converter . setDefaultColorRamp ( colorRamp ) if documentName is None : documentName = self . fileExtension kmlString , binaryPngStrings = converter . getAsKmlPngAnimation ( tableName = WMSDatasetRaster . tableName , timeStampedRasters = timeStampedRasters , rasterIdFieldName = 'id' , rasterFieldName = 'raster' , documentName = documentName , alpha = alpha , drawOrder = drawOrder , cellSize = cellSize , noDataValue = noDataValue , resampleMethod = resampleMethod ) if path : directory = os . path . dirname ( path ) archiveName = ( os . path . split ( path ) [ 1 ] ) . split ( '.' ) [ 0 ] kmzPath = os . path . join ( directory , ( archiveName + '.kmz' ) ) with ZipFile ( kmzPath , 'w' ) as kmz : kmz . writestr ( archiveName + '.kml' , kmlString ) for index , binaryPngString in enumerate ( binaryPngStrings ) : kmz . writestr ( 'raster{0}.png' . format ( index ) , binaryPngString ) return kmlString , binaryPngStrings | Retrieve the WMS dataset as a PNG time stamped KMZ | 449 | 13 |
4,773 | def _read ( self , directory , filename , session , path , name , extension , spatial , spatialReferenceID , maskMap ) : # Assign file extension attribute to file object self . fileExtension = extension if isinstance ( maskMap , RasterMapFile ) and maskMap . fileExtension == 'msk' : # Vars from mask map columns = maskMap . columns rows = maskMap . rows upperLeftX = maskMap . west upperLeftY = maskMap . north # Derive the cell size (GSSHA cells are square, so it is the same in both directions) cellSizeX = int ( abs ( maskMap . west - maskMap . east ) / columns ) cellSizeY = - 1 * cellSizeX # Dictionary of keywords/cards and parse function names KEYWORDS = { 'DATASET' : wdc . datasetHeaderChunk , 'TS' : wdc . datasetScalarTimeStepChunk } # Open file and read plain text into text field with open ( path , 'r' ) as f : chunks = pt . chunk ( KEYWORDS , f ) # Parse header chunk first header = wdc . datasetHeaderChunk ( 'DATASET' , chunks [ 'DATASET' ] [ 0 ] ) # Parse each time step chunk and aggregate timeStepRasters = [ ] for chunk in chunks [ 'TS' ] : timeStepRasters . append ( wdc . datasetScalarTimeStepChunk ( chunk , columns , header [ 'numberCells' ] ) ) # Set WMS dataset file properties self . name = header [ 'name' ] self . numberCells = header [ 'numberCells' ] self . numberData = header [ 'numberData' ] self . objectID = header [ 'objectID' ] if header [ 'type' ] == 'BEGSCL' : self . objectType = header [ 'objectType' ] self . type = self . SCALAR_TYPE elif header [ 'type' ] == 'BEGVEC' : self . vectorType = header [ 'objectType' ] self . type = self . VECTOR_TYPE # Create WMS raster dataset files for each raster for timeStep , timeStepRaster in enumerate ( timeStepRasters ) : # Create new WMS raster dataset file object wmsRasterDatasetFile = WMSDatasetRaster ( ) # Set the wms dataset for this WMS raster dataset file wmsRasterDatasetFile . wmsDataset = self # Set the time step and timestamp and other properties wmsRasterDatasetFile . iStatus = timeStepRaster [ 'iStatus' ] wmsRasterDatasetFile . timestamp = timeStepRaster [ 'timestamp' ] wmsRasterDatasetFile . timeStep = timeStep + 1 # If spatial is enabled create PostGIS rasters if spatial : # Process the values/cell array wmsRasterDatasetFile . raster = RasterLoader . makeSingleBandWKBRaster ( session , columns , rows , upperLeftX , upperLeftY , cellSizeX , cellSizeY , 0 , 0 , spatialReferenceID , timeStepRaster [ 'cellArray' ] ) # Otherwise, set the raster text properties else : wmsRasterDatasetFile . rasterText = timeStepRaster [ 'rasterText' ] # Add current file object to the session session . add ( self ) else : log . warning ( "Could not read {0}. Mask Map must be supplied " "to read WMS Datasets." . format ( filename ) ) | WMS Dataset File Read from File Method | 790 | 10 |
4,774 | def _write ( self , session , openFile , maskMap ) : # Magic numbers FIRST_VALUE_INDEX = 12 # Write the header openFile . write ( 'DATASET\r\n' ) if self . type == self . SCALAR_TYPE : openFile . write ( 'OBJTYPE {0}\r\n' . format ( self . objectType ) ) openFile . write ( 'BEGSCL\r\n' ) elif self . type == self . VECTOR_TYPE : openFile . write ( 'VECTYPE {0}\r\n' . format ( self . vectorType ) ) openFile . write ( 'BEGVEC\r\n' ) openFile . write ( 'OBJID {0}\r\n' . format ( self . objectID ) ) openFile . write ( 'ND {0}\r\n' . format ( self . numberData ) ) openFile . write ( 'NC {0}\r\n' . format ( self . numberCells ) ) openFile . write ( 'NAME {0}\r\n' . format ( self . name ) ) # Retrieve the mask map to use as the status rasters statusString = '' if isinstance ( maskMap , RasterMapFile ) : # Convert Mask Map to GRASS ASCII Raster statusGrassRasterString = maskMap . getAsGrassAsciiGrid ( session ) if statusGrassRasterString is not None : # Split by lines statusValues = statusGrassRasterString . split ( ) else : statusValues = maskMap . rasterText . split ( ) # Assemble into a string in the WMS Dataset format for i in range ( FIRST_VALUE_INDEX , len ( statusValues ) ) : statusString += statusValues [ i ] + '\r\n' # Write time steps for timeStepRaster in self . rasters : # Write time step header openFile . write ( 'TS {0} {1}\r\n' . format ( timeStepRaster . iStatus , timeStepRaster . timestamp ) ) # Write status raster (mask map) if applicable if timeStepRaster . iStatus == 1 : openFile . write ( statusString ) # Write value raster valueString = timeStepRaster . getAsWmsDatasetString ( session ) if valueString is not None : openFile . write ( valueString ) else : openFile . write ( timeStepRaster . rasterText ) # Write ending tag for the dataset openFile . write ( 'ENDDS\r\n' ) | WMS Dataset File Write to File Method | 564 | 10 |
4,775 | def getAsWmsDatasetString ( self , session ) : # Magic numbers FIRST_VALUE_INDEX = 12 # Write value raster if type ( self . raster ) != type ( None ) : # Convert to GRASS ASCII Raster valueGrassRasterString = self . getAsGrassAsciiGrid ( session ) # Split by lines values = valueGrassRasterString . split ( ) # Assemble into string wmsDatasetString = '' for i in range ( FIRST_VALUE_INDEX , len ( values ) ) : wmsDatasetString += '{0:.6f}\r\n' . format ( float ( values [ i ] ) ) return wmsDatasetString else : wmsDatasetString = self . rasterText | Retrieve the WMS Raster as a string in the WMS Dataset format | 171 | 18 |
4,776 | def check_watershed_boundary_geometry ( shapefile_path ) : wfg = gpd . read_file ( shapefile_path ) first_shape = wfg . iloc [ 0 ] . geometry if hasattr ( first_shape , 'geoms' ) : raise ValueError ( "Invalid watershed boundary geometry. " "To fix this, remove disconnected shapes or run " "gsshapy.modeling.GSSHAModel.clean_boundary_shapefile" ) | Make sure that there are no random artifacts in the file . | 106 | 12 |
4,777 | def get_batch ( sentences , token_dict , ignore_case = False , unk_index = 1 , eos_index = 2 ) : batch_size = len ( sentences ) max_sentence_len = max ( map ( len , sentences ) ) inputs = [ [ 0 ] * max_sentence_len for _ in range ( batch_size ) ] outputs_forward = [ [ 0 ] * max_sentence_len for _ in range ( batch_size ) ] outputs_backward = [ [ 0 ] * max_sentence_len for _ in range ( batch_size ) ] for i , sentence in enumerate ( sentences ) : outputs_forward [ i ] [ len ( sentence ) - 1 ] = eos_index outputs_backward [ i ] [ 0 ] = eos_index for j , token in enumerate ( sentence ) : if ignore_case : index = token_dict . get ( token . lower ( ) , unk_index ) else : index = token_dict . get ( token , unk_index ) inputs [ i ] [ j ] = index if j - 1 >= 0 : outputs_forward [ i ] [ j - 1 ] = index if j + 1 < len ( sentence ) : outputs_backward [ i ] [ j + 1 ] = index outputs_forward = np . expand_dims ( np . asarray ( outputs_forward ) , axis = - 1 ) outputs_backward = np . expand_dims ( np . asarray ( outputs_backward ) , axis = - 1 ) return np . asarray ( inputs ) , [ outputs_forward , outputs_backward ] | Get a batch of inputs and outputs from given sentences . | 353 | 11 |
4,778 | def fit ( self , inputs , outputs , epochs = 1 ) : self . model . fit ( inputs , outputs , epochs = epochs ) | Simple wrapper of model . fit . | 31 | 7 |
4,779 | def get_feature_layers ( self , input_layer = None , trainable = False , use_weighted_sum = False ) : model = keras . models . clone_model ( self . model , input_layer ) if not trainable : for layer in model . layers : layer . trainable = False if use_weighted_sum : rnn_layers_forward = list ( map ( lambda x : model . get_layer ( x . name . split ( '/' ) [ 0 ] . split ( ':' ) [ 0 ] . split ( '_' ) [ 0 ] ) . output , self . rnn_layers_forward , ) ) rnn_layers_backward = list ( map ( lambda x : model . get_layer ( x . name . split ( '/' ) [ 0 ] . split ( ':' ) [ 0 ] . split ( '_' ) [ 0 ] ) . output , self . rnn_layers_backward , ) ) forward_layer = WeightedSum ( name = 'Bi-LM-Forward-Sum' ) ( rnn_layers_forward ) backward_layer_rev = WeightedSum ( name = 'Bi-LM-Backward-Sum-Rev' ) ( rnn_layers_backward ) backward_layer = keras . layers . Lambda ( function = self . _reverse_x , mask = lambda _ , mask : self . _reverse_x ( mask ) , name = 'Bi-LM-Backward-Sum' ) ( backward_layer_rev ) else : forward_layer = model . get_layer ( name = 'Bi-LM-Forward' ) . output backward_layer = model . get_layer ( name = 'Bi-LM-Backward' ) . output output_layer = keras . layers . Concatenate ( name = 'Bi-LM-Feature' ) ( [ forward_layer , backward_layer ] ) if input_layer is None : input_layer = model . layers [ 0 ] . input return input_layer , output_layer return output_layer | Get layers that output the Bi - LM feature . | 449 | 10 |
4,780 | def join ( self , n1 ) : if self . id == n1 . get_id ( ) : for i in range ( k ) : self . finger [ i ] = self . proxy self . predecessor = self . proxy self . run = True return True else : try : self . init_finger_table ( n1 ) except Exception : print 'Join failed' # raise Exception('Join failed') return False else : self . run = True return True | if join returns false the node did not entry the ring . Retry it | 96 | 15 |
4,781 | def _read ( self , directory , filename , session , path , name , extension , spatial , spatialReferenceID , replaceParamFile ) : # Set file extension property self . fileExtension = extension # Open file and parse with open ( path , 'r' ) as nwsrfsFile : for line in nwsrfsFile : sline = line . strip ( ) . split ( ) # Cases if sline [ 0 ] . lower ( ) == 'number_bands:' : self . numBands = sline [ 1 ] elif sline [ 0 ] . lower ( ) == 'lower_elevation' : """DO NOTHING""" else : # Create GSSHAPY NwsrfsRecord object record = NwsrfsRecord ( lowerElev = sline [ 0 ] , upperElev = sline [ 1 ] , mfMin = sline [ 2 ] , mfMax = sline [ 3 ] , scf = sline [ 4 ] , frUse = sline [ 5 ] , tipm = sline [ 6 ] , nmf = sline [ 7 ] , fua = sline [ 8 ] , plwhc = sline [ 9 ] ) # Associate NwsrfsRecord with NwsrfsFile record . nwsrfsFile = self | NWSRFS Read from File Method | 279 | 7 |
4,782 | def _write ( self , session , openFile , replaceParamFile ) : # Write lines openFile . write ( 'Number_Bands: %s\n' % self . numBands ) openFile . write ( 'Lower_Elevation Upper_Elevation MF_Min MF_Max SCF FR_USE TIPM NMF FUA PCWHC\n' ) # Retrieve NwsrfsRecords records = self . nwsrfsRecords for record in records : openFile . write ( '%s%s%s%s%.1f%s%.1f%s%.1f%s%.1f%s%.1f%s%.1f%s%.1f%s%.1f\n' % ( record . lowerElev , ' ' * ( 17 - len ( str ( record . lowerElev ) ) ) , # Num Spaces record . upperElev , ' ' * ( 17 - len ( str ( record . upperElev ) ) ) , # Num Spaces record . mfMin , ' ' * ( 8 - len ( str ( record . mfMin ) ) ) , # Num Spaces record . mfMax , ' ' * ( 8 - len ( str ( record . mfMax ) ) ) , # Num Spaces record . scf , ' ' * ( 5 - len ( str ( record . scf ) ) ) , # Num Spaces record . frUse , ' ' * ( 8 - len ( str ( record . frUse ) ) ) , # Num Spaces record . tipm , ' ' * ( 6 - len ( str ( record . tipm ) ) ) , # Num Spaces record . nmf , ' ' * ( 5 - len ( str ( record . nmf ) ) ) , # Num Spaces record . fua , ' ' * ( 5 - len ( str ( record . fua ) ) ) , # Num Spaces record . plwhc ) ) | NWSRFS Write to File Method | 413 | 7 |
4,783 | def _read ( self , directory , filename , session , path , name , extension , spatial , spatialReferenceID , replaceParamFile ) : # Set file extension property self . fileExtension = extension # Open file and parse into HmetRecords with open ( path , 'r' ) as orthoFile : for line in orthoFile : sline = line . strip ( ) . split ( ) # Cases if sline [ 0 ] . lower ( ) == 'num_sites:' : self . numSites = sline [ 1 ] elif sline [ 0 ] . lower ( ) == 'elev_base' : self . elevBase = sline [ 1 ] elif sline [ 0 ] . lower ( ) == 'elev_2' : self . elev2 = sline [ 1 ] elif sline [ 0 ] . lower ( ) == 'year' : """DO NOTHING""" else : # Create datetime object dateTime = datetime ( year = int ( sline [ 0 ] ) , month = int ( sline [ 1 ] ) , day = int ( sline [ 2 ] ) , hour = int ( sline [ 3 ] ) ) # Create GSSHAPY OrthoMeasurement object measurement = OrographicMeasurement ( dateTime = dateTime , temp2 = sline [ 4 ] ) # Associate OrthoMeasurement with OrthographicGageFile self . orographicMeasurements . append ( measurement ) | Orographic Gage File Read from File Method | 310 | 10 |
4,784 | def _write ( self , session , openFile , replaceParamFile ) : # Write lines openFile . write ( 'Num_Sites: %s\n' % self . numSites ) openFile . write ( 'Elev_Base %s\n' % self . elevBase ) openFile . write ( 'Elev_2 %s\n' % self . elev2 ) openFile . write ( 'Year Month Day Hour Temp_2\n' ) # Retrieve OrographicMeasurements measurements = self . orographicMeasurements for measurement in measurements : dateTime = measurement . dateTime openFile . write ( '%s%s%s%s%s%s%s%s%.3f\n' % ( dateTime . year , ' ' , dateTime . month , ' ' * ( 8 - len ( str ( dateTime . month ) ) ) , dateTime . day , ' ' * ( 8 - len ( str ( dateTime . day ) ) ) , dateTime . hour , ' ' * ( 8 - len ( str ( dateTime . hour ) ) ) , measurement . temp2 ) ) | Orographic Gage File Write to File Method | 243 | 10 |
4,785 | def getFluvialLinks ( self ) : # Define fluvial types fluvialTypeKeywords = ( 'TRAPEZOID' , 'TRAP' , 'BREAKPOINT' , 'ERODE' , 'SUBSURFACE' ) fluvialLinks = [ ] for link in self . streamLinks : for fluvialTypeKeyword in fluvialTypeKeywords : if fluvialTypeKeyword in link . type : fluvialLinks . append ( link ) break return fluvialLinks | Retrieve only the links that represent fluvial portions of the stream . Returns a list of StreamLink instances . | 115 | 23 |
4,786 | def getOrderedLinks ( self , session ) : streamLinks = session . query ( StreamLink ) . filter ( StreamLink . channelInputFile == self ) . order_by ( StreamLink . linkNumber ) . all ( ) return streamLinks | Retrieve the links in the order of the link number . | 51 | 12 |
4,787 | def getStreamNetworkAsWkt ( self , session , withNodes = True ) : wkt_list = [ ] for link in self . streamLinks : wkt_link = link . getAsWkt ( session ) if wkt_link : wkt_list . append ( wkt_link ) if withNodes : for node in link . nodes : wkt_node = node . getAsWkt ( session ) if wkt_node : wkt_list . append ( wkt_node ) return 'GEOMCOLLECTION ({0})' . format ( ', ' . join ( wkt_list ) ) | Retrieve the stream network geometry in Well Known Text format . | 135 | 12 |
4,788 | def getStreamNetworkAsGeoJson ( self , session , withNodes = True ) : features_list = [ ] # Assemble link features for link in self . streamLinks : link_geoJson = link . getAsGeoJson ( session ) if link_geoJson : link_geometry = json . loads ( link . getAsGeoJson ( session ) ) link_properties = { "link_number" : link . linkNumber , "type" : link . type , "num_elements" : link . numElements , "dx" : link . dx , "erode" : link . erode , "subsurface" : link . subsurface } link_feature = { "type" : "Feature" , "geometry" : link_geometry , "properties" : link_properties , "id" : link . id } features_list . append ( link_feature ) # Assemble node features if withNodes : for node in link . nodes : node_geoJson = node . getAsGeoJson ( session ) if node_geoJson : node_geometry = json . loads ( node_geoJson ) node_properties = { "link_number" : link . linkNumber , "node_number" : node . nodeNumber , "elevation" : node . elevation } node_feature = { "type" : "Feature" , "geometry" : node_geometry , "properties" : node_properties , "id" : node . id } features_list . append ( node_feature ) feature_collection = { "type" : "FeatureCollection" , "features" : features_list } return json . dumps ( feature_collection ) | Retrieve the stream network geometry in GeoJSON format . | 378 | 11 |
4,789 | def _read ( self , directory , filename , session , path , name , extension , spatial , spatialReferenceID , replaceParamFile ) : # Set file extension property self . fileExtension = extension # Dictionary of keywords/cards and parse function names KEYWORDS = { 'ALPHA' : cic . cardChunk , 'BETA' : cic . cardChunk , 'THETA' : cic . cardChunk , 'LINKS' : cic . cardChunk , 'MAXNODES' : cic . cardChunk , 'CONNECT' : cic . connectChunk , 'LINK' : cic . linkChunk } links = [ ] connectivity = [ ] # Parse file into chunks associated with keywords/cards with open ( path , 'r' ) as f : chunks = pt . chunk ( KEYWORDS , f ) # Parse chunks associated with each key for key , chunkList in iteritems ( chunks ) : # Parse each chunk in the chunk list for chunk in chunkList : # Call chunk specific parsers for each chunk result = KEYWORDS [ key ] ( key , chunk ) # Cases if key == 'LINK' : # Link handler links . append ( self . _createLink ( result , replaceParamFile ) ) elif key == 'CONNECT' : # Connectivity handler connectivity . append ( result ) else : # Global variable handler card = result [ 'card' ] value = result [ 'values' ] [ 0 ] # Cases if card == 'LINKS' : self . links = int ( value ) elif card == 'MAXNODES' : self . maxNodes = int ( value ) elif card == 'ALPHA' : self . alpha = float ( vrp ( value , replaceParamFile ) ) elif card == 'BETA' : self . beta = float ( vrp ( value , replaceParamFile ) ) elif card == 'THETA' : self . theta = float ( vrp ( value , replaceParamFile ) ) self . _createConnectivity ( linkList = links , connectList = connectivity ) if spatial : self . _createGeometry ( session , spatialReferenceID ) | Channel Input File Read from File Method | 471 | 7 |
4,790 | def _write ( self , session , openFile , replaceParamFile ) : # Write lines openFile . write ( 'GSSHA_CHAN\n' ) alpha = vwp ( self . alpha , replaceParamFile ) try : openFile . write ( 'ALPHA%s%.6f\n' % ( ' ' * 7 , alpha ) ) except : openFile . write ( 'ALPHA%s%s\n' % ( ' ' * 7 , alpha ) ) beta = vwp ( self . beta , replaceParamFile ) try : openFile . write ( 'BETA%s%.6f\n' % ( ' ' * 8 , beta ) ) except : openFile . write ( 'BETA%s%s\n' % ( ' ' * 8 , beta ) ) theta = vwp ( self . theta , replaceParamFile ) try : openFile . write ( 'THETA%s%.6f\n' % ( ' ' * 7 , theta ) ) except : openFile . write ( 'THETA%s%s\n' % ( ' ' * 7 , theta ) ) openFile . write ( 'LINKS%s%s\n' % ( ' ' * 7 , self . links ) ) openFile . write ( 'MAXNODES%s%s\n' % ( ' ' * 4 , self . maxNodes ) ) # Retrieve StreamLinks links = self . getOrderedLinks ( session ) self . _writeConnectivity ( links = links , fileObject = openFile ) self . _writeLinks ( links = links , fileObject = openFile , replaceParamFile = replaceParamFile ) | Channel Input File Write to File Method | 361 | 7 |
4,791 | def _createLink ( self , linkResult , replaceParamFile ) : link = None # Cases if linkResult [ 'type' ] == 'XSEC' : # Cross section link handler link = self . _createCrossSection ( linkResult , replaceParamFile ) elif linkResult [ 'type' ] == 'STRUCTURE' : # Structure link handler link = self . _createStructure ( linkResult , replaceParamFile ) elif linkResult [ 'type' ] in ( 'RESERVOIR' , 'LAKE' ) : # Reservoir/lake handler link = self . _createReservoir ( linkResult , replaceParamFile ) return link | Create GSSHAPY Link Object Method | 139 | 9 |
4,792 | def _createConnectivity ( self , linkList , connectList ) : # Create StreamLink-Connectivity Pairs for idx , link in enumerate ( linkList ) : connectivity = connectList [ idx ] # Initialize GSSHAPY UpstreamLink objects for upLink in connectivity [ 'upLinks' ] : upstreamLink = UpstreamLink ( upstreamLinkID = int ( upLink ) ) upstreamLink . streamLink = link link . downstreamLinkID = int ( connectivity [ 'downLink' ] ) link . numUpstreamLinks = int ( connectivity [ 'numUpLinks' ] ) | Create GSSHAPY Connect Object Method | 127 | 9 |
4,793 | def _createCrossSection ( self , linkResult , replaceParamFile ) : # Extract header variables from link result object header = linkResult [ 'header' ] # Initialize GSSHAPY StreamLink object link = StreamLink ( linkNumber = int ( header [ 'link' ] ) , type = header [ 'xSecType' ] , numElements = header [ 'nodes' ] , dx = vrp ( header [ 'dx' ] , replaceParamFile ) , erode = header [ 'erode' ] , subsurface = header [ 'subsurface' ] ) # Associate StreamLink with ChannelInputFile link . channelInputFile = self # Initialize GSSHAPY TrapezoidalCS or BreakpointCS objects xSection = linkResult [ 'xSection' ] # Cases if 'TRAPEZOID' in link . type or 'TRAP' in link . type : # Trapezoid cross section handler # Initialize GSSHPY TrapeziodalCS object trapezoidCS = TrapezoidalCS ( mannings_n = vrp ( xSection [ 'mannings_n' ] , replaceParamFile ) , bottomWidth = vrp ( xSection [ 'bottom_width' ] , replaceParamFile ) , bankfullDepth = vrp ( xSection [ 'bankfull_depth' ] , replaceParamFile ) , sideSlope = vrp ( xSection [ 'side_slope' ] , replaceParamFile ) , mRiver = vrp ( xSection [ 'm_river' ] , replaceParamFile ) , kRiver = vrp ( xSection [ 'k_river' ] , replaceParamFile ) , erode = xSection [ 'erode' ] , subsurface = xSection [ 'subsurface' ] , maxErosion = vrp ( xSection [ 'max_erosion' ] , replaceParamFile ) ) # Associate TrapezoidalCS with StreamLink trapezoidCS . streamLink = link elif 'BREAKPOINT' in link . type : # Breakpoint cross section handler # Initialize GSSHAPY BreakpointCS objects breakpointCS = BreakpointCS ( mannings_n = vrp ( xSection [ 'mannings_n' ] , replaceParamFile ) , numPairs = xSection [ 'npairs' ] , numInterp = vrp ( xSection [ 'num_interp' ] , replaceParamFile ) , mRiver = vrp ( xSection [ 'm_river' ] , replaceParamFile ) , kRiver = vrp ( xSection [ 'k_river' ] , replaceParamFile ) , erode = xSection [ 'erode' ] , subsurface = xSection [ 'subsurface' ] , maxErosion = vrp ( xSection [ 'max_erosion' ] , replaceParamFile ) ) # Associate BreakpointCS with StreamLink breakpointCS . streamLink = link # Create GSSHAPY Breakpoint objects for b in xSection [ 'breakpoints' ] : breakpoint = Breakpoint ( x = b [ 'x' ] , y = b [ 'y' ] ) # Associate Breakpoint with BreakpointCS breakpoint . crossSection = breakpointCS # Initialize GSSHAPY StreamNode objects for n in linkResult [ 'nodes' ] : # Initialize GSSHAPY StreamNode object node = StreamNode ( nodeNumber = int ( n [ 'node' ] ) , x = n [ 'x' ] , y = n [ 'y' ] , elevation = n [ 'elev' ] ) # Associate StreamNode with StreamLink node . streamLink = link return link | Create GSSHAPY Cross Section Objects Method | 799 | 10 |
4,794 | def _createStructure ( self , linkResult , replaceParamFile ) : # Constants WEIRS = ( 'WEIR' , 'SAG_WEIR' ) CULVERTS = ( 'ROUND_CULVERT' , 'RECT_CULVERT' ) CURVES = ( 'RATING_CURVE' , 'SCHEDULED_RELEASE' , 'RULE_CURVE' ) header = linkResult [ 'header' ] # Initialize GSSHAPY StreamLink object link = StreamLink ( linkNumber = header [ 'link' ] , type = linkResult [ 'type' ] , numElements = header [ 'numstructs' ] ) # Associate StreamLink with ChannelInputFile link . channelInputFile = self # Create Structure objects for s in linkResult [ 'structures' ] : structType = s [ 'structtype' ] # Cases if structType in WEIRS : # Weir type handler # Initialize GSSHAPY Weir object weir = Weir ( type = structType , crestLength = vrp ( s [ 'crest_length' ] , replaceParamFile ) , crestLowElevation = vrp ( s [ 'crest_low_elev' ] , replaceParamFile ) , dischargeCoeffForward = vrp ( s [ 'discharge_coeff_forward' ] , replaceParamFile ) , dischargeCoeffReverse = vrp ( s [ 'discharge_coeff_reverse' ] , replaceParamFile ) , crestLowLocation = vrp ( s [ 'crest_low_loc' ] , replaceParamFile ) , steepSlope = vrp ( s [ 'steep_slope' ] , replaceParamFile ) , shallowSlope = vrp ( s [ 'shallow_slope' ] , replaceParamFile ) ) # Associate Weir with StreamLink weir . streamLink = link elif structType in CULVERTS : # Culvert type handler # Initialize GSSHAPY Culvert object culvert = Culvert ( type = structType , upstreamInvert = vrp ( s [ 'upinvert' ] , replaceParamFile ) , downstreamInvert = vrp ( s [ 'downinvert' ] , replaceParamFile ) , inletDischargeCoeff = vrp ( s [ 'inlet_disch_coeff' ] , replaceParamFile ) , reverseFlowDischargeCoeff = vrp ( s [ 'rev_flow_disch_coeff' ] , replaceParamFile ) , slope = vrp ( s [ 'slope' ] , replaceParamFile ) , length = vrp ( s [ 'length' ] , replaceParamFile ) , roughness = vrp ( s [ 'rough_coeff' ] , replaceParamFile ) , diameter = vrp ( s [ 'diameter' ] , replaceParamFile ) , width = vrp ( s [ 'width' ] , replaceParamFile ) , height = vrp ( s [ 'height' ] , replaceParamFile ) ) # Associate Culvert with StreamLink culvert . streamLink = link elif structType in CURVES : # Curve type handler pass return link | Create GSSHAPY Structure Objects Method | 711 | 9 |
4,795 | def _createReservoir ( self , linkResult , replaceParamFile ) : # Extract header variables from link result object header = linkResult [ 'header' ] # Cases if linkResult [ 'type' ] == 'LAKE' : # Lake handler initWSE = vrp ( header [ 'initwse' ] , replaceParamFile ) minWSE = vrp ( header [ 'minwse' ] , replaceParamFile ) maxWSE = vrp ( header [ 'maxwse' ] , replaceParamFile ) numPts = header [ 'numpts' ] elif linkResult [ 'type' ] == 'RESERVOIR' : # Reservoir handler initWSE = vrp ( header [ 'res_initwse' ] , replaceParamFile ) minWSE = vrp ( header [ 'res_minwse' ] , replaceParamFile ) maxWSE = vrp ( header [ 'res_maxwse' ] , replaceParamFile ) numPts = header [ 'res_numpts' ] # Initialize GSSHAPY Reservoir object reservoir = Reservoir ( initWSE = initWSE , minWSE = minWSE , maxWSE = maxWSE ) # Initialize GSSHAPY StreamLink object link = StreamLink ( linkNumber = int ( header [ 'link' ] ) , type = linkResult [ 'type' ] , numElements = numPts ) # Associate StreamLink with ChannelInputFile link . channelInputFile = self # Associate Reservoir with StreamLink reservoir . streamLink = link # Create ReservoirPoint objects for p in linkResult [ 'points' ] : # Initialize GSSHAPY ReservoirPoint object resPoint = ReservoirPoint ( i = p [ 'i' ] , j = p [ 'j' ] ) # Associate ReservoirPoint with Reservoir resPoint . reservoir = reservoir return link | Create GSSHAPY Reservoir Objects Method | 417 | 10 |
4,796 | def _createGeometry ( self , session , spatialReferenceID ) : # Flush the current session session . flush ( ) # Create geometry for each fluvial link for link in self . getFluvialLinks ( ) : # Retrieve the nodes for each link nodes = link . nodes nodeCoordinates = [ ] # Create geometry for each node for node in nodes : # Assemble coordinates in well known text format coordinates = '{0} {1} {2}' . format ( node . x , node . y , node . elevation ) nodeCoordinates . append ( coordinates ) # Create well known text string for point with z coordinate wktPoint = 'POINT Z ({0})' . format ( coordinates ) # Write SQL statement statement = self . _getUpdateGeometrySqlString ( geometryID = node . id , tableName = node . tableName , spatialReferenceID = spatialReferenceID , wktString = wktPoint ) session . execute ( statement ) # Assemble line string in well known text format wktLineString = 'LINESTRING Z ({0})' . format ( ', ' . join ( nodeCoordinates ) ) # Write SQL statement statement = self . _getUpdateGeometrySqlString ( geometryID = link . id , tableName = link . tableName , spatialReferenceID = spatialReferenceID , wktString = wktLineString ) session . execute ( statement ) | Create PostGIS geometric objects | 302 | 6 |
4,797 | def _writeConnectivity ( self , links , fileObject ) : for link in links : linkNum = link . linkNumber downLink = link . downstreamLinkID numUpLinks = link . numUpstreamLinks upLinks = '' for upLink in link . upstreamLinks : upLinks = '{}{:>5}' . format ( upLinks , str ( upLink . upstreamLinkID ) ) line = 'CONNECT{:>5}{:>5}{:>5}{}\n' . format ( linkNum , downLink , numUpLinks , upLinks ) fileObject . write ( line ) fileObject . write ( '\n' ) | Write Connectivity Lines to File Method | 138 | 7 |
4,798 | def _writeLinks ( self , links , fileObject , replaceParamFile ) : for link in links : linkType = link . type fileObject . write ( 'LINK %s\n' % link . linkNumber ) # Cases if 'TRAP' in linkType or 'TRAPEZOID' in linkType or 'BREAKPOINT' in linkType : self . _writeCrossSectionLink ( link , fileObject , replaceParamFile ) elif linkType == 'STRUCTURE' : self . _writeStructureLink ( link , fileObject , replaceParamFile ) elif linkType in ( 'RESERVOIR' , 'LAKE' ) : self . _writeReservoirLink ( link , fileObject , replaceParamFile ) else : log . error ( 'OOPS: CIF LINE 417' ) # THIS SHOULDN'T HAPPEN fileObject . write ( '\n' ) | Write Link Lines to File Method | 195 | 6 |
4,799 | def _writeCrossSectionLink ( self , link , fileObject , replaceParamFile ) : linkType = link . type # Write cross section link header dx = vwp ( link . dx , replaceParamFile ) try : fileObject . write ( 'DX %.6f\n' % dx ) except : fileObject . write ( 'DX %s\n' % dx ) fileObject . write ( '%s\n' % linkType ) fileObject . write ( 'NODES %s\n' % link . numElements ) for node in link . nodes : # Write node information fileObject . write ( 'NODE %s\n' % node . nodeNumber ) fileObject . write ( 'X_Y %.6f %.6f\n' % ( node . x , node . y ) ) fileObject . write ( 'ELEV %.6f\n' % node . elevation ) if node . nodeNumber == 1 : # Write cross section information after first node fileObject . write ( 'XSEC\n' ) # Cases if 'TRAPEZOID' in linkType or 'TRAP' in linkType : # Retrieve cross section xSec = link . trapezoidalCS # Write cross section properties mannings_n = vwp ( xSec . mannings_n , replaceParamFile ) bottomWidth = vwp ( xSec . bottomWidth , replaceParamFile ) bankfullDepth = vwp ( xSec . bankfullDepth , replaceParamFile ) sideSlope = vwp ( xSec . sideSlope , replaceParamFile ) try : fileObject . write ( 'MANNINGS_N %.6f\n' % mannings_n ) except : fileObject . write ( 'MANNINGS_N %s\n' % mannings_n ) try : fileObject . write ( 'BOTTOM_WIDTH %.6f\n' % bottomWidth ) except : fileObject . write ( 'BOTTOM_WIDTH %s\n' % bottomWidth ) try : fileObject . write ( 'BANKFULL_DEPTH %.6f\n' % bankfullDepth ) except : fileObject . write ( 'BANKFULL_DEPTH %s\n' % bankfullDepth ) try : fileObject . write ( 'SIDE_SLOPE %.6f\n' % sideSlope ) except : fileObject . write ( 'SIDE_SLOPE %s\n' % sideSlope ) # Write optional cross section properties self . _writeOptionalXsecCards ( fileObject = fileObject , xSec = xSec , replaceParamFile = replaceParamFile ) elif 'BREAKPOINT' in linkType : # Retrieve cross section xSec = link . breakpointCS # Write cross section properties mannings_n = vwp ( xSec . mannings_n , replaceParamFile ) try : fileObject . write ( 'MANNINGS_N %.6f\n' % mannings_n ) except : fileObject . write ( 'MANNINGS_N %s\n' % mannings_n ) fileObject . write ( 'NPAIRS %s\n' % xSec . numPairs ) fileObject . write ( 'NUM_INTERP %s\n' % vwp ( xSec . numInterp , replaceParamFile ) ) # Write optional cross section properties self . _writeOptionalXsecCards ( fileObject = fileObject , xSec = xSec , replaceParamFile = replaceParamFile ) # Write breakpoint lines for bp in xSec . breakpoints : fileObject . write ( 'X1 %.6f %.6f\n' % ( bp . x , bp . y ) ) else : log . error ( 'OOPS: MISSED A CROSS SECTION TYPE. CIF LINE 580. {0}' . format ( linkType ) ) | Write Cross Section Link to File Method | 846 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.