idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
15,500 | def get_stats ( self ) : try : query = { 'size' : 0 , 'aggs' : { 'num_packages' : { 'value_count' : { 'field' : 'id' , } , } , 'num_records' : { 'sum' : { 'field' : 'package.count_of_rows' , } , } , 'num_countries' : { 'cardinality' : { 'field' : 'package.countryCode.keyword' , } , } , } , } aggregations = self . es . search ( index = self . index_name , body = query ) [ 'aggregations' ] return { key : int ( value [ 'value' ] ) for key , value in aggregations . items ( ) } except NotFoundError : return { } | Get some stats on the packages in the registry |
15,501 | def cmd ( send , msg , args ) : req = get ( "http://api.fmylife.com/view/random" , params = { 'language' : 'en' , 'key' : args [ 'config' ] [ 'api' ] [ 'fmlkey' ] } ) doc = fromstring ( req . content ) send ( doc . xpath ( '//text' ) [ 0 ] . text ) | Gets a random FML post . |
15,502 | def cmd ( send , msg , args ) : if not args [ 'config' ] [ 'feature' ] . getboolean ( 'hooks' ) : send ( "Hooks are disabled, and this command depends on hooks. Please contact the bot admin(s)." ) return session = args [ 'db' ] parser = arguments . ArgParser ( args [ 'config' ] ) group = parser . add_mutually_exclusive_group ( ) group . add_argument ( '--high' , action = 'store_true' ) group . add_argument ( '--low' , action = 'store_true' ) group . add_argument ( 'nick' , nargs = '?' , action = arguments . NickParser ) try : cmdargs = parser . parse_args ( msg ) except arguments . ArgumentException as e : send ( str ( e ) ) return if cmdargs . high : data = session . query ( Scores ) . order_by ( Scores . score . desc ( ) ) . limit ( 3 ) . all ( ) send ( 'High Scores:' ) for x in data : send ( "%s: %s" % ( x . nick , x . score ) ) elif cmdargs . low : data = session . query ( Scores ) . order_by ( Scores . score ) . limit ( 3 ) . all ( ) send ( 'Low Scores:' ) for x in data : send ( "%s: %s" % ( x . nick , x . score ) ) elif cmdargs . nick : name = cmdargs . nick . lower ( ) if name == 'c' : send ( "We all know you love C better than anything else, so why rub it in?" ) return score = session . query ( Scores ) . filter ( Scores . nick == name ) . scalar ( ) if score is not None : plural = '' if abs ( score . score ) == 1 else 's' if name == args [ 'botnick' ] . lower ( ) : emote = ':)' if score . score > 0 else ':(' if score . score < 0 else ':|' output = 'has %s point%s! %s' % ( score . score , plural , emote ) send ( output , 'action' ) else : send ( "%s has %i point%s!" % ( name , score . score , plural ) ) else : send ( "Nobody cares about %s" % name ) else : if session . query ( Scores ) . count ( ) == 0 : send ( "Nobody cares about anything =(" ) else : query = session . query ( Scores ) . order_by ( func . random ( ) ) . first ( ) plural = '' if abs ( query . score ) == 1 else 's' send ( "%s has %i point%s!" % ( query . nick , query . score , plural ) ) | Gets scores . |
15,503 | def add_affect ( self , name , src , dest , val , condition = None ) : self . affects . append ( ParamAffects ( name , src , dest , val , condition ) ) | adds how param src affects param dest to the list |
15,504 | def get_by_name ( self , nme ) : for p in self . params : if p . name == nme : return p return None | searches list of all parameters and returns the first param that matches on name |
15,505 | def get_affects_for_param ( self , nme ) : res = [ ] for a in self . affects : if a . name == nme : res . append ( a ) return res | searches all affects and returns a list that affect the param named nme |
15,506 | def buildPrices ( data , roles = None , regex = default_price_regex , default = None , additional = { } ) : if isinstance ( data , dict ) : data = [ ( item [ 0 ] , convertPrice ( item [ 1 ] ) ) for item in data . items ( ) ] return dict ( [ v for v in data if v [ 1 ] is not None ] ) elif isinstance ( data , ( str , float , int ) ) and not isinstance ( data , bool ) : if default is None : raise ValueError ( 'You have to call setAdditionalCharges ' 'before it is possible to pass a string as price' ) basePrice = convertPrice ( data ) if basePrice is None : return { } prices = { default : basePrice } for role in additional : extraCharge = convertPrice ( additional [ role ] ) if extraCharge is None : continue prices [ role ] = basePrice + extraCharge return prices elif roles : prices = { } priceRoles = iter ( roles ) for priceData in data : price = convertPrice ( priceData ) if price is None : continue prices [ next ( priceRoles ) ] = price return prices else : raise TypeError ( 'This type is for prices not supported!' ) | Create a dictionary with price information . Multiple ways are supported . |
15,507 | def buildLegend ( legend = None , text = None , regex = None , key = lambda v : v ) : if legend is None : legend = { } if text is not None : for match in re . finditer ( regex or default_legend_regex , text , re . UNICODE ) : legend [ key ( match . group ( 'name' ) ) ] = match . group ( 'value' ) . strip ( ) return legend | Helper method to build or extend a legend from a text . The given regex will be used to find legend inside the text . |
15,508 | def toTag ( self , output ) : feed = output . createElement ( 'feed' ) feed . setAttribute ( 'name' , self . name ) feed . setAttribute ( 'priority' , str ( self . priority ) ) schedule = output . createElement ( 'schedule' ) schedule . setAttribute ( 'dayOfMonth' , self . dayOfMonth ) schedule . setAttribute ( 'dayOfWeek' , self . dayOfWeek ) schedule . setAttribute ( 'hour' , self . hour ) schedule . setAttribute ( 'minute' , self . minute ) if self . retry : schedule . setAttribute ( 'retry' , self . retry ) feed . appendChild ( schedule ) url = output . createElement ( 'url' ) url . appendChild ( output . createTextNode ( self . url ) ) feed . appendChild ( url ) if self . source : source = output . createElement ( 'source' ) source . appendChild ( output . createTextNode ( self . source ) ) feed . appendChild ( source ) return feed | This methods returns all data of this feed as feed xml tag |
15,509 | def hasMealsFor ( self , date ) : date = self . _handleDate ( date ) if date not in self . _days or self . _days [ date ] is False : return False return len ( self . _days [ date ] ) > 0 | Checks whether for this day are information stored . |
15,510 | def toXMLFeed ( self ) : feed = self . toXML ( ) xml_header = '<?xml version="1.0" encoding="UTF-8"?>\n' return xml_header + feed . toprettyxml ( indent = ' ' ) | Convert this cateen information into string which is a valid OpenMensa v2 xml feed |
15,511 | def toTag ( self , output ) : canteen = output . createElement ( 'canteen' ) if self . _name is not None : canteen . appendChild ( self . _buildStringTag ( 'name' , self . _name , output ) ) if self . _address is not None : canteen . appendChild ( self . _buildStringTag ( 'address' , self . _address , output ) ) if self . _city is not None : canteen . appendChild ( self . _buildStringTag ( 'city' , self . _city , output ) ) if self . _phone is not None : canteen . appendChild ( self . _buildStringTag ( 'phone' , self . _phone , output ) ) if self . _email is not None : canteen . appendChild ( self . _buildStringTag ( 'email' , self . _email , output ) ) if self . _location is not None : canteen . appendChild ( self . _buildLocationTag ( self . _location , output ) ) if self . _availability is not None : canteen . appendChild ( self . _buildStringTag ( 'availability' , self . _availability , output ) ) for feed in sorted ( self . feeds , key = lambda v : v . priority ) : canteen . appendChild ( feed . toTag ( output ) ) for date in sorted ( self . _days . keys ( ) ) : day = output . createElement ( 'day' ) day . setAttribute ( 'date' , str ( date ) ) if self . _days [ date ] is False : closed = output . createElement ( 'closed' ) day . appendChild ( closed ) canteen . appendChild ( day ) continue for categoryname in self . _days [ date ] : day . appendChild ( self . _buildCategoryTag ( categoryname , self . _days [ date ] [ categoryname ] , output ) ) canteen . appendChild ( day ) return canteen | This methods adds all data of this canteen as canteen xml tag to the given xml Document . |
15,512 | def add_session ( self , session , input_dataset = True , summary_table = True , recommendation_details = True , recommended_model = True , all_models = False , ) : self . doc . add_paragraph ( session . dataset . _get_dataset_name ( ) , self . styles . header_1 ) self . doc . add_paragraph ( "BMDS version: {}" . format ( session . version_pretty ) ) if input_dataset : self . _add_dataset ( session ) self . doc . add_paragraph ( ) if summary_table : self . _add_session_summary_table ( session ) self . doc . add_paragraph ( ) if recommendation_details : self . _add_recommendation_details_table ( session ) self . doc . add_paragraph ( ) if recommended_model and all_models : self . _add_recommended_model ( session ) self . _add_all_models ( session , except_recommended = True ) self . doc . add_paragraph ( ) elif recommended_model : self . _add_recommended_model ( session ) self . doc . add_paragraph ( ) elif all_models : self . _add_all_models ( session , except_recommended = False ) self . doc . add_paragraph ( ) self . doc . add_page_break ( ) | Add an existing session to a Word report . |
15,513 | def save ( self , filename ) : self . doc . save ( os . path . expanduser ( filename ) ) | Save document to a file . |
15,514 | def _get_session_for_table ( self , base_session ) : if base_session . recommended_model is None and base_session . doses_dropped > 0 : return base_session . doses_dropped_sessions [ 0 ] return base_session | Only present session for modeling when doses were dropped if it s succesful ; otherwise show the original modeling session . |
15,515 | def set_driver_simulated ( self ) : self . _device_dict [ "servermain.MULTIPLE_TYPES_DEVICE_DRIVER" ] = "Simulator" if self . _is_sixteen_bit : self . _device_dict [ "servermain.DEVICE_MODEL" ] = 0 else : self . _device_dict [ "servermain.DEVICE_MODEL" ] = 1 self . _device_dict [ "servermain.DEVICE_ID_OCTAL" ] = 1 | Sets the device driver type to simulated |
15,516 | def parse_tag_groups ( self ) : tag_groups = [ ] if 'tag_groups' not in self . _device_dict : return tag_groups to_remove = [ ] for tag_group in self . _device_dict [ 'tag_groups' ] : if tag_group [ 'common.ALLTYPES_NAME' ] in self . _ignore_list : to_remove . append ( tag_group ) continue tag_groups . append ( TagGroup ( tag_group ) ) for removable in to_remove : self . _device_dict [ 'tag_groups' ] . remove ( removable ) return tag_groups | Gets an array of TagGroup objects in the Kepware device |
15,517 | def update ( self ) : if "tag_groups" not in self . _device_dict : return for group in self . tag_groups : group . update ( ) for i in range ( len ( self . _device_dict [ "tag_groups" ] ) ) : tag_group_dict = self . _device_dict [ "tag_groups" ] [ i ] for group in self . tag_groups : if group . name == tag_group_dict [ "common.ALLTYPES_NAME" ] : self . _device_dict [ "tag_groups" ] [ i ] = group . as_dict ( ) | Updates the dictionary of the device |
15,518 | def AddAnalogShortIdMsecRecord ( site_service , tag , time_value , msec , value , low_warn = False , high_warn = False , low_alarm = False , high_alarm = False , oor_low = False , oor_high = False , unreliable = False , manual = False ) : szService = c_char_p ( site_service . encode ( 'utf-8' ) ) szPointId = c_char_p ( tag . encode ( 'utf-8' ) ) tTime = c_long ( int ( time_value ) ) dValue = c_double ( value ) bLowWarning = c_int ( int ( low_warn ) ) bHighWarning = c_int ( int ( high_warn ) ) bLowAlarm = c_int ( int ( low_alarm ) ) bHighAlarm = c_int ( int ( high_alarm ) ) bOutOfRangeLow = c_int ( int ( oor_low ) ) bOutOfRangeHigh = c_int ( int ( oor_high ) ) bUnReliable = c_int ( int ( unreliable ) ) bManual = c_int ( int ( manual ) ) usMsec = c_ushort ( msec ) nRet = dnaserv_dll . DnaAddAnalogShortIdMsecRecord ( szService , szPointId , tTime , dValue , bLowWarning , bHighWarning , bLowAlarm , bHighAlarm , bOutOfRangeLow , bOutOfRangeHigh , bUnReliable , bManual , usMsec ) return nRet | This function will add an analog value to the specified eDNA service and tag with many optional status definitions . |
15,519 | def FlushShortIdRecords ( site_service ) : szService = c_char_p ( site_service . encode ( 'utf-8' ) ) szMessage = create_string_buffer ( b" " ) nMessage = c_ushort ( 20 ) nRet = dnaserv_dll . DnaFlushShortIdRecords ( szService , byref ( szMessage ) , nMessage ) return str ( nRet ) + szMessage . value . decode ( 'utf-8' ) | Flush all the queued records . |
15,520 | def set_scheduler ( self , host , username = 'root' , password = None , private_key = None , private_key_pass = None ) : self . _remote = RemoteClient ( host , username , password , private_key , private_key_pass ) self . _remote_id = uuid . uuid4 ( ) . hex | Defines the remote scheduler |
15,521 | def set_cwd ( fn ) : def wrapped ( self , * args , ** kwargs ) : log . info ( 'Calling function: %s with args=%s' , fn , args if args else [ ] ) cwd = os . getcwd ( ) log . info ( 'Saved cwd: %s' , cwd ) os . chdir ( self . _cwd ) log . info ( 'Changing working directory to: %s' , self . _cwd ) try : return fn ( self , * args , ** kwargs ) finally : os . chdir ( cwd ) log . info ( 'Restored working directory to: %s' , cwd ) return wrapped | Decorator to set the specified working directory to execute the function and then restore the previous cwd . |
15,522 | def remove ( self , options = [ ] , sub_job_num = None ) : args = [ 'condor_rm' ] args . extend ( options ) job_id = '%s.%s' % ( self . cluster_id , sub_job_num ) if sub_job_num else str ( self . cluster_id ) args . append ( job_id ) out , err = self . _execute ( args ) return out , err | Removes a job from the job queue or from being executed . |
15,523 | def close_remote ( self ) : if self . _remote : try : self . _remote . execute ( 'ls %s' % ( self . _remote_id , ) ) if self . status != 'Completed' : self . remove ( ) self . _remote . execute ( 'rm -rf %s' % ( self . _remote_id , ) ) except RuntimeError : pass self . _remote . close ( ) del self . _remote | Cleans up and closes connection to remote server if defined . |
15,524 | def gini_impurity ( s ) : return 1 - sum ( prop ( s [ i ] , s ) ** 2 for i in range ( len ( s ) ) ) | Calculate the Gini Impurity for a list of samples . |
15,525 | def entropy ( s ) : return - sum ( p * np . log ( p ) for i in range ( len ( s ) ) for p in [ prop ( s [ i ] , s ) ] ) | Calculate the Entropy Impurity for a list of samples . |
15,526 | def info_gain ( current_impurity , true_branch , false_branch , criterion ) : measure_impurity = gini_impurity if criterion == "gini" else entropy p = float ( len ( true_branch ) ) / ( len ( true_branch ) + len ( false_branch ) ) return current_impurity - p * measure_impurity ( true_branch ) - ( 1 - p ) * measure_impurity ( false_branch ) | Information Gain . The uncertainty of the starting node minus the weighted impurity of two child nodes . |
15,527 | def _update_statuses ( self , sub_job_num = None ) : status_dict = dict ( ) for val in CONDOR_JOB_STATUSES . values ( ) : status_dict [ val ] = 0 for node in self . node_set : job = node . job try : job_status = job . status status_dict [ job_status ] += 1 except ( KeyError , HTCondorError ) : status_dict [ 'Unexpanded' ] += 1 return status_dict | Update statuses of jobs nodes in workflow . |
15,528 | def update_node_ids ( self , sub_job_num = None ) : dag_id = '%s.%s' % ( self . cluster_id , sub_job_num ) if sub_job_num else str ( self . cluster_id ) job_delimiter = '+++' attr_delimiter = ';;;' format = [ '-format' , '"%d' + attr_delimiter + '"' , 'ClusterId' , '-format' , '"%v' + attr_delimiter + '"' , 'Cmd' , '-format' , '"%v' + attr_delimiter + '"' , 'Args' , '-format' , '"%v' + job_delimiter + '"' , 'Arguments' ] cmd = 'condor_q -constraint DAGManJobID=={0} {1} && condor_history -constraint DAGManJobID=={0} {1}' . format ( dag_id , ' ' . join ( format ) ) _args = [ cmd ] out , err = self . _execute ( _args , shell = True , run_in_job_dir = False ) if err : log . error ( 'Error while associating ids for jobs dag %s: %s' , dag_id , err ) raise HTCondorError ( err ) if not out : log . warning ( 'Error while associating ids for jobs in dag %s: No jobs found for dag.' , dag_id ) try : jobs_out = out . split ( job_delimiter ) for node in self . _node_set : job = node . job if job . cluster_id != job . NULL_CLUSTER_ID : continue for job_out in jobs_out : if not job_out or attr_delimiter not in job_out : continue cluster_id , cmd , _args , _arguments = job_out . split ( attr_delimiter ) if _args == 'undefined' and _arguments != 'undefined' : args = _arguments . strip ( ) elif _args == 'undefined' and _arguments == 'undefined' : args = None else : args = _args . strip ( ) job_cmd = job . executable job_args = job . arguments . strip ( ) if job . arguments else None if job_cmd in cmd and job_args == args : log . info ( 'Linking cluster_id %s to job with command and arguments: %s %s' , cluster_id , job_cmd , job_args ) job . _cluster_id = int ( cluster_id ) break except ValueError as e : log . warning ( str ( e ) ) | Associate Jobs with respective cluster ids . |
15,529 | def submit ( self , options = [ ] ) : self . complete_node_set ( ) self . _write_job_file ( ) args = [ 'condor_submit_dag' ] args . extend ( options ) args . append ( self . dag_file ) log . info ( 'Submitting workflow %s with options: %s' , self . name , args ) return super ( Workflow , self ) . submit ( args ) | ensures that all relatives of nodes in node_set are also added to the set before submitting |
15,530 | def safe_reload ( modname : types . ModuleType ) -> Union [ None , str ] : try : importlib . reload ( modname ) return None except Exception as e : logging . error ( "Failed to reimport module: %s" , modname ) msg , _ = backtrace . output_traceback ( e ) return msg | Catch and log any errors that arise from reimporting a module but do not die . |
15,531 | def safe_load ( modname : str ) -> Union [ None , str ] : try : importlib . import_module ( modname ) return None except Exception as ex : logging . error ( "Failed to import module: %s" , modname ) msg , _ = backtrace . output_traceback ( ex ) return msg | Load a module logging errors instead of dying if it fails to load . |
15,532 | def scan_and_reimport ( mod_type : str ) -> List [ Tuple [ str , str ] ] : mod_enabled , mod_disabled = get_modules ( mod_type ) errors = [ ] for mod in mod_enabled + mod_disabled : if mod in sys . modules : msg = safe_reload ( sys . modules [ mod ] ) else : msg = safe_load ( mod ) if msg is not None : errors . append ( ( mod , msg ) ) return errors | Scans folder for modules . |
15,533 | def _ranging ( self ) : agg_ranges = [ ] for i , val in enumerate ( self . range_list ) : if i == 0 : agg_ranges . append ( { "to" : val } ) else : previous = self . range_list [ i - 1 ] agg_ranges . append ( { "from" : previous , "to" : val } ) if i + 1 == len ( self . range_list ) : agg_ranges . append ( { "from" : val } ) return agg_ranges | Should be a list of values to designate the buckets |
15,534 | def get_random_surah ( self , lang = 'id' ) : if lang not in self . SUPPORTED_LANGUAGES : message = 'Currently your selected language not yet supported.' raise ODOAException ( message ) rand_surah = random . randint ( 1 , self . TOTAL_SURAH ) surah_url = '{base}/surah/surah_{pages}.json' . format ( base = self . BASE_API , pages = rand_surah ) try : response = urlopen ( surah_url ) data = json . loads ( response . read ( ) . decode ( 'utf-8' ) ) except IOError : traceback . print_exc ( file = sys . stdout ) raise ODOAException else : random_ayah = random . randint ( 1 , int ( data . get ( 'count' ) ) ) ayah_key = 'verse_{index}' . format ( index = random_ayah ) ayah = data [ 'verse' ] [ ayah_key ] . encode ( 'utf-8' ) surah_index = data . get ( 'index' ) surah_name = data . get ( 'name' ) translation = self . __get_translation ( surah = surah_index , ayah = ayah_key , lang = lang ) sound = self . __get_sound ( surah = surah_index , ayah = random_ayah ) desc = '{name}:{ayah}' . format ( name = surah_name , ayah = random_ayah ) meta = Metadata ( ayah , desc , translation , sound ) return meta | Perform http request to get random surah . |
15,535 | def __get_translation ( self , surah , ayah , lang ) : url = '{base}/translations/{lang}/{lang}_translation_{surah}.json' . format ( base = self . BASE_API , lang = lang , surah = int ( surah ) ) try : response = urlopen ( url ) data = json . loads ( response . read ( ) . decode ( 'utf-8' ) ) translation = data [ 'verse' ] [ ayah ] except ODOAException : return None else : return translation | Perform http request to get translation from given surah ayah and language . |
15,536 | def __get_sound ( self , surah , ayah ) : format_ayah = '{0:0>3}' . format ( ayah ) sound_url = '{base}/sounds/{surah}/{ayah}.mp3' . format ( base = self . BASE_API , surah = surah , ayah = format_ayah ) return sound_url | Perform http request to get sound from given surah and ayah . |
15,537 | def get_fipscode ( self , obj ) : if obj . division . level . name == DivisionLevel . COUNTY : return obj . division . code return None | County FIPS code |
15,538 | def get_statepostal ( self , obj ) : if obj . division . level . name == DivisionLevel . STATE : return us . states . lookup ( obj . division . code ) . abbr elif obj . division . level . name == DivisionLevel . COUNTY : return us . states . lookup ( obj . division . parent . code ) . abbr return None | State postal abbreviation if county or state else None . |
15,539 | def get_polid ( self , obj ) : ap_id = obj . candidate_election . candidate . ap_candidate_id if 'polid-' in ap_id : return ap_id . replace ( 'polid-' , '' ) return None | AP polid minus polid prefix if polid else None . |
15,540 | def get_polnum ( self , obj ) : ap_id = obj . candidate_election . candidate . ap_candidate_id if 'polnum-' in ap_id : return ap_id . replace ( 'polnum-' , '' ) return None | AP polnum minus polnum prefix if polnum else None . |
15,541 | def get_precinctsreporting ( self , obj ) : if obj . division . level == obj . candidate_election . election . division . level : return obj . candidate_election . election . meta . precincts_reporting return None | Precincts reporting if vote is top level result else None . |
15,542 | def get_precinctsreportingpct ( self , obj ) : if obj . division . level == obj . candidate_election . election . division . level : return obj . candidate_election . election . meta . precincts_reporting_pct return None | Precincts reporting percent if vote is top level result else None . |
15,543 | def get_precinctstotal ( self , obj ) : if obj . division . level == obj . candidate_election . election . division . level : return obj . candidate_election . election . meta . precincts_total return None | Precincts total if vote is top level result else None . |
15,544 | def load ( self , tableName = 'rasters' , rasters = [ ] ) : Base . metadata . create_all ( self . _engine ) Session = sessionmaker ( bind = self . _engine ) session = Session ( ) for raster in rasters : rasterPath = raster [ 'path' ] if 'srid' in raster : srid = str ( raster [ 'srid' ] ) else : srid = '4326' if 'no-data' in raster : noData = str ( raster [ 'no-data' ] ) else : noData = '-1' wellKnownBinary = RasterLoader . rasterToWKB ( rasterPath , srid , noData , self . _raster2pgsql ) rasterBinary = wellKnownBinary filename = os . path . split ( rasterPath ) [ 1 ] mapKitRaster = MapKitRaster ( ) mapKitRaster . filename = filename mapKitRaster . raster = rasterBinary if 'timestamp' in raster : mapKitRaster . timestamp = raster [ 'timestamp' ] session . add ( mapKitRaster ) session . commit ( ) | Accepts a list of paths to raster files to load into the database . Returns the ids of the rasters loaded successfully in the same order as the list passed in . |
15,545 | def rasterToWKB ( cls , rasterPath , srid , noData , raster2pgsql ) : raster2pgsqlProcess = subprocess . Popen ( [ raster2pgsql , '-s' , srid , '-N' , noData , rasterPath , 'n_a' ] , stdout = subprocess . PIPE ) sql , error = raster2pgsqlProcess . communicate ( ) if sql : wellKnownBinary = sql . split ( "'" ) [ 1 ] else : print ( error ) raise return wellKnownBinary | Accepts a raster file and converts it to Well Known Binary text using the raster2pgsql executable that comes with PostGIS . This is the format that rasters are stored in a PostGIS database . |
15,546 | def grassAsciiRasterToWKB ( cls , session , grassRasterPath , srid , noData = 0 ) : NUM_HEADER_LINES = 6 north = 0.0 east = 0.0 west = 0.0 rows = 0 columns = 0 if grassRasterPath is not None : with open ( grassRasterPath , 'r' ) as f : rasterLines = f . readlines ( ) else : print ( "RASTER LOAD ERROR: Must provide the path the raster." ) raise for line in rasterLines [ 0 : NUM_HEADER_LINES ] : spline = line . split ( ) if 'north' in spline [ 0 ] . lower ( ) : north = float ( spline [ 1 ] ) elif 'east' in spline [ 0 ] . lower ( ) : east = float ( spline [ 1 ] ) elif 'west' in spline [ 0 ] . lower ( ) : west = float ( spline [ 1 ] ) elif 'rows' in spline [ 0 ] . lower ( ) : rows = int ( spline [ 1 ] ) elif 'cols' in spline [ 0 ] . lower ( ) : columns = int ( spline [ 1 ] ) width = columns height = rows upperLeftX = west upperLeftY = north cellSizeX = int ( abs ( west - east ) / columns ) cellSizeY = - 1 * cellSizeX dataArrayList = [ ] for line in rasterLines [ NUM_HEADER_LINES : len ( rasterLines ) ] : dataArrayList . append ( '[{0}]' . format ( ', ' . join ( line . split ( ) ) ) ) dataArrayString = '[{0}]' . format ( ', ' . join ( dataArrayList ) ) wellKnownBinary = cls . makeSingleBandWKBRaster ( session = session , width = width , height = height , upperLeftX = upperLeftX , upperLeftY = upperLeftY , cellSizeX = cellSizeX , cellSizeY = cellSizeY , skewX = 0 , skewY = 0 , srid = srid , dataArray = dataArrayString , noDataValue = noData ) return wellKnownBinary | Load GRASS ASCII rasters directly using the makeSingleBandWKBRaster method . Do this to eliminate the raster2pgsql dependency . |
15,547 | def cmd ( send , msg , args ) : parser = arguments . ArgParser ( args [ 'config' ] ) parser . add_argument ( 'delay' ) parser . add_argument ( 'msg' , nargs = '+' ) try : cmdargs = parser . parse_args ( msg ) except arguments . ArgumentException as e : send ( str ( e ) ) return if isinstance ( cmdargs . msg , list ) : cmdargs . msg = ' ' . join ( cmdargs . msg ) cmdargs . delay = parse_time ( cmdargs . delay ) if cmdargs . delay is None : send ( "Invalid unit." ) elif cmdargs . delay < 0 : send ( "Time travel not yet implemented, sorry." ) else : ident = args [ 'handler' ] . workers . defer ( cmdargs . delay , False , send , cmdargs . msg ) send ( "Message deferred, ident: %s" % ident ) | Says something at a later time . |
15,548 | def _replace ( self , ** kwds ) : 'Return a new NamedTuple object replacing specified fields with new values' result = self . _make ( map ( kwds . pop , self . _fields , self ) ) if kwds : raise ValueError ( 'Got unexpected field names: %r' % kwds . keys ( ) ) return result | Return a new NamedTuple object replacing specified fields with new values |
15,549 | def concat_cols ( df1 , df2 , idx_col , df1_cols , df2_cols , df1_suffix , df2_suffix , wc_cols = [ ] , suffix_all = False ) : df1 = df1 . set_index ( idx_col ) df2 = df2 . set_index ( idx_col ) if not len ( wc_cols ) == 0 : for wc in wc_cols : df1_cols = df1_cols + [ c for c in df1 . columns if wc in c ] df2_cols = df2_cols + [ c for c in df2 . columns if wc in c ] combo = pd . concat ( [ df1 . loc [ : , df1_cols ] , df2 . loc [ : , df2_cols ] ] , axis = 1 ) if suffix_all : df1_cols = [ "%s%s" % ( c , df1_suffix ) for c in df1_cols ] df2_cols = [ "%s%s" % ( c , df2_suffix ) for c in df2_cols ] else : common_cols = [ col for col in df1_cols if col in df2_cols ] for col in common_cols : df1_cols [ df1_cols . index ( col ) ] = "%s%s" % ( col , df1_suffix ) df2_cols [ df2_cols . index ( col ) ] = "%s%s" % ( col , df2_suffix ) combo . columns = df1_cols + df2_cols combo . index . name = idx_col return combo | Concatenates two pandas tables |
15,550 | def get_colmin ( data ) : data = data . T colmins = [ ] for col in data : colmins . append ( data [ col ] . idxmin ( ) ) return colmins | Get rowwise column names with minimum values |
15,551 | def fhs2data_combo_appended ( fhs , cols = None , labels = None , labels_coln = 'labels' , sep = ',' , error_bad_lines = True ) : if labels is None : labels = [ basename ( fh ) for fh in fhs ] if len ( fhs ) > 0 : data_all = pd . DataFrame ( columns = cols ) for fhi , fh in enumerate ( fhs ) : label = labels [ fhi ] try : data = pd . read_csv ( fh , sep = sep , error_bad_lines = error_bad_lines ) except : raise ValueError ( f"something wrong with file pd.read_csv({fh},sep={sep})" ) if len ( data ) != 0 : data . loc [ : , labels_coln ] = label if not cols is None : data = data . loc [ : , cols ] data_all = data_all . append ( data , sort = True ) return del_Unnamed ( data_all ) | to be deprecated Collates data from multiple csv files vertically |
15,552 | def rename_cols ( df , names , renames = None , prefix = None , suffix = None ) : if not prefix is None : renames = [ "%s%s" % ( prefix , s ) for s in names ] if not suffix is None : renames = [ "%s%s" % ( s , suffix ) for s in names ] if not renames is None : for i , name in enumerate ( names ) : rename = renames [ i ] df . loc [ : , rename ] = df . loc [ : , name ] df = df . drop ( names , axis = 1 ) return df | rename columns of a pandas table |
15,553 | def reorderbydf ( df2 , df1 ) : df3 = pd . DataFrame ( ) for idx , row in df1 . iterrows ( ) : df3 = df3 . append ( df2 . loc [ idx , : ] ) return df3 | Reorder rows of a dataframe by other dataframe |
15,554 | def df2unstack ( df , coln = 'columns' , idxn = 'index' , col = 'value' ) : return dmap2lin ( df , idxn = idxn , coln = coln , colvalue_name = col ) | will be deprecated |
15,555 | def get_offdiag_vals ( dcorr ) : del_indexes = [ ] for spc1 in np . unique ( dcorr . index . get_level_values ( 0 ) ) : for spc2 in np . unique ( dcorr . index . get_level_values ( 0 ) ) : if ( not ( spc1 , spc2 ) in del_indexes ) and ( not ( spc2 , spc1 ) in del_indexes ) : del_indexes . append ( ( spc1 , spc2 ) ) for spc1 in np . unique ( dcorr . index . get_level_values ( 0 ) ) : for spc2 in np . unique ( dcorr . index . get_level_values ( 0 ) ) : if spc1 == spc2 : del_indexes . append ( ( spc1 , spc2 ) ) return dcorr . drop ( del_indexes ) | for lin dcorr i guess |
15,556 | def from_dict ( data ) : data = deepcopy ( data ) created_at = data . get ( 'created_at' , None ) if created_at is not None : data [ 'created_at' ] = dateutil . parser . parse ( created_at ) return Image ( ** data ) | Create a new instance from dict |
15,557 | def to_json ( self , indent = None , sort_keys = True ) : return json . dumps ( self . to_dict ( ) , indent = indent , sort_keys = sort_keys ) | Return a JSON string representation of this instance |
15,558 | def to_dict ( self ) : data = { } if self . created_at : data [ 'created_at' ] = self . created_at . strftime ( '%Y-%m-%dT%H:%M:%S%z' ) if self . image_id : data [ 'image_id' ] = self . image_id if self . permalink_url : data [ 'permalink_url' ] = self . permalink_url if self . thumb_url : data [ 'thumb_url' ] = self . thumb_url if self . type : data [ 'type' ] = self . type if self . url : data [ 'url' ] = self . url return data | Return a dict representation of this instance |
15,559 | def download ( self ) : if self . url : try : return requests . get ( self . url ) . content except requests . RequestException as e : raise GyazoError ( str ( e ) ) return None | Download an image file if it exists |
15,560 | def download_thumb ( self ) : try : return requests . get ( self . thumb_url ) . content except requests . RequestException as e : raise GyazoError ( str ( e ) ) | Download a thumbnail image file |
15,561 | def has_next_page ( self ) : return self . current_page < math . ceil ( self . total_count / self . per_page ) | Whether there is a next page or not |
15,562 | def set_attributes_from_headers ( self , headers ) : self . total_count = headers . get ( 'x-total-count' , None ) self . current_page = headers . get ( 'x-current-page' , None ) self . per_page = headers . get ( 'x-per-page' , None ) self . user_type = headers . get ( 'x-user-type' , None ) if self . total_count : self . total_count = int ( self . total_count ) if self . current_page : self . current_page = int ( self . current_page ) if self . per_page : self . per_page = int ( self . per_page ) | Set instance attributes with HTTP header |
15,563 | def _validate_base_classes ( meta , bases ) : for base in bases : if meta . _is_final ( base ) : raise ClassError ( "cannot inherit from @final class %s" % ( base . __name__ , ) ) | Validate the base classes of the new class to be created making sure none of them are |
15,564 | def _validate_method_decoration ( meta , class_ ) : super_mro = class_ . __mro__ [ 1 : ] own_methods = ( ( name , member ) for name , member in class_ . __dict__ . items ( ) if is_method ( member ) ) for name , method in own_methods : shadowed_method , base_class = next ( ( ( getattr ( base , name ) , base ) for base in super_mro if hasattr ( base , name ) ) , ( None , None ) ) if meta . _is_override ( method ) : if not shadowed_method : raise ClassError ( "unnecessary @override on %s.%s" % ( class_ . __name__ , name ) , class_ = class_ ) if meta . _is_final ( shadowed_method ) : raise ClassError ( "illegal @override on a @final method %s.%s" % ( base_class . __name__ , name ) , class_ = class_ ) override_base = meta . _get_override_base ( method ) if override_base and base_class is not override_base : if is_class ( override_base ) : raise ClassError ( "incorrect override base: expected %s, got %s" % ( base_class . __name__ , override_base . __name__ ) ) else : raise ClassError ( "invalid override base specified: %s" % ( override_base , ) ) setattr ( class_ , name , method . method ) else : if shadowed_method and name not in meta . OVERRIDE_EXEMPTIONS : if meta . _is_final ( shadowed_method ) : msg = "%s.%s is hiding a @final method %s.%s" % ( class_ . __name__ , name , base_class . __name__ , name ) else : msg = ( "overridden method %s.%s " "must be marked with @override" % ( class_ . __name__ , name ) ) raise ClassError ( msg , class_ = class_ ) | Validate the usage of |
15,565 | def _is_final ( meta , arg ) : if inspect . isclass ( arg ) and not isinstance ( arg , ObjectMetaclass ) : return False from taipan . objective . modifiers import _WrappedMethod if isinstance ( arg , _WrappedMethod ) : arg = arg . method return getattr ( arg , '__final__' , False ) | Checks whether given class or method has been marked with the |
15,566 | def _is_override ( meta , method ) : from taipan . objective . modifiers import _OverriddenMethod return isinstance ( method , _OverriddenMethod ) | Checks whether given class or instance method has been marked with the |
15,567 | def trace_dependencies ( req , requirement_set , dependencies , _visited = None ) : _visited = _visited or set ( ) if req in _visited : return _visited . add ( req ) for reqName in req . requirements ( ) : try : name = pkg_resources . Requirement . parse ( reqName ) . project_name except ValueError , e : logger . error ( 'Invalid requirement: %r (%s) in requirement %s' % ( reqName , e , req ) ) continue subreq = requirement_set . get_requirement ( name ) dependencies . append ( ( req , subreq ) ) trace_dependencies ( subreq , requirement_set , dependencies , _visited ) | Trace all dependency relationship |
15,568 | def pad_zeroes ( addr , n_zeroes ) : if len ( addr ) < n_zeroes : return pad_zeroes ( "0" + addr , n_zeroes ) return addr | Padds the address with zeroes |
15,569 | def next_addr ( addr , i ) : str_addr = pad_zeroes ( str ( int_addr ( addr ) + i ) , len ( addr [ 1 : ] ) ) return addr [ 0 ] + str_addr | Gets address after the current + i |
15,570 | def mark_address ( self , addr , size ) : i = 0 while i < size : self . _register_map [ addr ] = True i += 1 | Marks address as being used in simulator |
15,571 | def next_address_avoid_collision ( self , start_addr ) : i = 1 while self . is_address_in_use ( next_addr ( start_addr , i ) ) : i += 1 return next_addr ( start_addr , i ) | Finds the next address recursively which does not collide with any other address |
15,572 | def move_to_next_bit_address ( self ) : self . _current_bit_address = self . next_bit_address ( ) self . mark_address ( self . _current_bit_address . split ( '.' ) [ 0 ] , self . _size_of_current_register_address ) | Moves to next available bit address position |
15,573 | def next_bit_address ( self ) : if self . _current_bit_address == "" : if self . _is_16bit : return "{0}.{1}" . format ( self . next_address ( ) , "00" ) return "{0}.{1}" . format ( self . next_address ( ) , "0" ) if self . _is_16bit : bool_half = int ( self . _current_bit_address . split ( "." ) [ 1 ] ) if bool_half < 4 : register_half = self . _current_bit_address . split ( "." ) [ 0 ] return "{0}.{1}" . format ( register_half , pad_zeroes ( str ( bool_half + 1 ) , 2 ) ) self . move_to_next_address ( self . _size_of_current_register_address ) return "{0}.{1}" . format ( self . next_address ( ) , "00" ) bool_half = int ( self . _current_bit_address . split ( "." ) [ 1 ] ) if bool_half < 3 : register_half = self . _current_bit_address . split ( "." ) [ 0 ] return "{0}.{1}" . format ( register_half , bool_half + 1 ) self . move_to_next_address ( self . _size_of_current_register_address ) return "{0}.{1}" . format ( self . next_address ( ) , "0" ) | Gets the next boolean address |
15,574 | def route_election ( self , election ) : if ( election . election_type . slug == ElectionType . GENERAL or ElectionType . GENERAL_RUNOFF ) : self . bootstrap_general_election ( election ) elif election . race . special : self . bootstrap_special_election ( election ) if election . race . office . is_executive : self . bootstrap_executive_office ( election ) else : self . bootstrap_legislative_office ( election ) | Legislative or executive office? |
15,575 | def get_status ( * nrs ) : bugs = [ ] list_ = [ ] for nr in nrs : if isinstance ( nr , list ) : list_ . extend ( nr ) else : list_ . append ( nr ) soap_client = _build_soap_client ( ) for i in range ( 0 , len ( list_ ) , BATCH_SIZE ) : slice_ = list_ [ i : i + BATCH_SIZE ] method_el = SimpleXMLElement ( '<get_status></get_status>' ) _build_int_array_el ( 'arg0' , method_el , slice_ ) reply = soap_client . call ( 'get_status' , method_el ) for bug_item_el in reply ( 's-gensym3' ) . children ( ) or [ ] : bug_el = bug_item_el . children ( ) [ 1 ] bugs . append ( _parse_status ( bug_el ) ) return bugs | Returns a list of Bugreport objects . |
15,576 | def get_usertag ( email , * tags ) : reply = _soap_client_call ( 'get_usertag' , email , * tags ) map_el = reply ( 's-gensym3' ) mapping = { } type_attr = map_el . attributes ( ) . get ( 'xsi:type' ) if type_attr and type_attr . value == 'apachens:Map' : for usertag_el in map_el . children ( ) or [ ] : tag = _uc ( str ( usertag_el ( 'key' ) ) ) buglist_el = usertag_el ( 'value' ) mapping [ tag ] = [ int ( bug ) for bug in buglist_el . children ( ) or [ ] ] else : for usertag_el in map_el . children ( ) or [ ] : tag = _uc ( usertag_el . get_name ( ) ) mapping [ tag ] = [ int ( bug ) for bug in usertag_el . children ( ) or [ ] ] return mapping | Get buglists by usertags . |
15,577 | def get_bug_log ( nr ) : reply = _soap_client_call ( 'get_bug_log' , nr ) items_el = reply ( 'soapenc:Array' ) buglogs = [ ] for buglog_el in items_el . children ( ) : buglog = { } buglog [ "header" ] = _parse_string_el ( buglog_el ( "header" ) ) buglog [ "body" ] = _parse_string_el ( buglog_el ( "body" ) ) buglog [ "msg_num" ] = int ( buglog_el ( "msg_num" ) ) buglog [ "attachments" ] = [ ] mail_parser = email . feedparser . FeedParser ( ) mail_parser . feed ( buglog [ "header" ] ) mail_parser . feed ( "\n\n" ) mail_parser . feed ( buglog [ "body" ] ) buglog [ "message" ] = mail_parser . close ( ) buglogs . append ( buglog ) return buglogs | Get Buglogs . |
15,578 | def newest_bugs ( amount ) : reply = _soap_client_call ( 'newest_bugs' , amount ) items_el = reply ( 'soapenc:Array' ) return [ int ( item_el ) for item_el in items_el . children ( ) or [ ] ] | Returns the newest bugs . |
15,579 | def get_bugs ( * key_value ) : if len ( key_value ) == 1 and isinstance ( key_value [ 0 ] , list ) : key_value = tuple ( key_value [ 0 ] ) method_el = SimpleXMLElement ( '<get_bugs></get_bugs>' ) for arg_n , kv in enumerate ( key_value ) : arg_name = 'arg' + str ( arg_n ) if isinstance ( kv , ( list , tuple ) ) : _build_int_array_el ( arg_name , method_el , kv ) else : method_el . marshall ( arg_name , kv ) soap_client = _build_soap_client ( ) reply = soap_client . call ( 'get_bugs' , method_el ) items_el = reply ( 'soapenc:Array' ) return [ int ( item_el ) for item_el in items_el . children ( ) or [ ] ] | Get list of bugs matching certain criteria . |
15,580 | def _parse_status ( bug_el ) : bug = Bugreport ( ) for field in ( 'originator' , 'subject' , 'msgid' , 'package' , 'severity' , 'owner' , 'summary' , 'location' , 'source' , 'pending' , 'forwarded' ) : setattr ( bug , field , _parse_string_el ( bug_el ( field ) ) ) bug . date = datetime . utcfromtimestamp ( float ( bug_el ( 'date' ) ) ) bug . log_modified = datetime . utcfromtimestamp ( float ( bug_el ( 'log_modified' ) ) ) bug . tags = [ _uc ( tag ) for tag in str ( bug_el ( 'tags' ) ) . split ( ) ] bug . done = _parse_bool ( bug_el ( 'done' ) ) bug . archived = _parse_bool ( bug_el ( 'archived' ) ) bug . unarchived = _parse_bool ( bug_el ( 'unarchived' ) ) bug . bug_num = int ( bug_el ( 'bug_num' ) ) bug . mergedwith = [ int ( i ) for i in str ( bug_el ( 'mergedwith' ) ) . split ( ) ] bug . blockedby = [ int ( i ) for i in str ( bug_el ( 'blockedby' ) ) . split ( ) ] bug . blocks = [ int ( i ) for i in str ( bug_el ( 'blocks' ) ) . split ( ) ] bug . found_versions = [ _uc ( str ( el ) ) for el in bug_el ( 'found_versions' ) . children ( ) or [ ] ] bug . fixed_versions = [ _uc ( str ( el ) ) for el in bug_el ( 'fixed_versions' ) . children ( ) or [ ] ] affects = [ _f for _f in str ( bug_el ( 'affects' ) ) . split ( ',' ) if _f ] bug . affects = [ _uc ( a ) . strip ( ) for a in affects ] return bug | Return a bugreport object from a given status xml element |
15,581 | def _convert_soap_method_args ( * args ) : soap_args = [ ] for arg_n , arg in enumerate ( args ) : soap_args . append ( ( 'arg' + str ( arg_n ) , arg ) ) return soap_args | Convert arguments to be consumed by a SoapClient method |
15,582 | def _soap_client_call ( method_name , * args ) : soap_client = _build_soap_client ( ) soap_args = _convert_soap_method_args ( * args ) if PYSIMPLESOAP_1_16_2 : return getattr ( soap_client , method_name ) ( * soap_args ) else : return getattr ( soap_client , method_name ) ( soap_client , * soap_args ) | Wrapper to call SoapClient method |
15,583 | def _parse_string_el ( el ) : value = str ( el ) el_type = el . attributes ( ) . get ( 'xsi:type' ) if el_type and el_type . value == 'xsd:base64Binary' : value = base64 . b64decode ( value ) if not PY2 : value = value . decode ( 'utf-8' , errors = 'replace' ) value = _uc ( value ) return value | read a string element maybe encoded in base64 |
15,584 | def get_solc_input ( self ) : def legal ( r , file_name ) : hidden = file_name [ 0 ] == '.' dotsol = len ( file_name ) > 3 and file_name [ - 4 : ] == '.sol' path = os . path . normpath ( os . path . join ( r , file_name ) ) notfile = not os . path . isfile ( path ) symlink = Path ( path ) . is_symlink ( ) return dotsol and ( not ( symlink or hidden or notfile ) ) solc_input = { 'language' : 'Solidity' , 'sources' : { file_name : { 'urls' : [ os . path . realpath ( os . path . join ( r , file_name ) ) ] } for r , d , f in os . walk ( self . contracts_dir ) for file_name in f if legal ( r , file_name ) } , 'settings' : { 'optimizer' : { 'enabled' : 1 , 'runs' : 10000 } , 'outputSelection' : { "*" : { "" : [ "legacyAST" , "ast" ] , "*" : [ "abi" , "evm.bytecode.object" , "evm.bytecode.sourceMap" , "evm.deployedBytecode.object" , "evm.deployedBytecode.sourceMap" ] } } } } return solc_input | Walks the contract directory and returns a Solidity input dict |
15,585 | def compile_all ( self ) : solc_input = self . get_solc_input ( ) real_path = os . path . realpath ( self . contracts_dir ) compilation_result = compile_standard ( solc_input , allow_paths = real_path ) os . makedirs ( self . output_dir , exist_ok = True ) compiled_contracts = compilation_result [ 'contracts' ] for contract_file in compiled_contracts : for contract in compiled_contracts [ contract_file ] : contract_name = contract . split ( '.' ) [ 0 ] contract_data = compiled_contracts [ contract_file ] [ contract_name ] contract_data_path = self . output_dir + '/{0}.json' . format ( contract_name ) with open ( contract_data_path , "w+" ) as contract_data_file : json . dump ( contract_data , contract_data_file ) | Compiles all of the contracts in the self . contracts_dir directory |
15,586 | def get_contract_data ( self , contract_name ) : contract_data_path = self . output_dir + '/{0}.json' . format ( contract_name ) with open ( contract_data_path , 'r' ) as contract_data_file : contract_data = json . load ( contract_data_file ) abi = contract_data [ 'abi' ] bytecode = contract_data [ 'evm' ] [ 'bytecode' ] [ 'object' ] return abi , bytecode | Returns the contract data for a given contract |
15,587 | def exception ( maxTBlevel = None ) : try : from marrow . util . bunch import Bunch cls , exc , trbk = sys . exc_info ( ) excName = cls . __name__ excArgs = getattr ( exc , 'args' , None ) excTb = '' . join ( traceback . format_exception ( cls , exc , trbk , maxTBlevel ) ) return Bunch ( name = excName , cls = cls , exception = exc , trace = trbk , formatted = excTb , args = excArgs ) finally : del cls , exc , trbk | Retrieve useful information about an exception . |
15,588 | def native ( s , encoding = 'utf-8' , fallback = 'iso-8859-1' ) : if isinstance ( s , str ) : return s if str is unicode : return unicodestr ( s , encoding , fallback ) return bytestring ( s , encoding , fallback ) | Convert a given string into a native string . |
15,589 | def unicodestr ( s , encoding = 'utf-8' , fallback = 'iso-8859-1' ) : if isinstance ( s , unicode ) : return s try : return s . decode ( encoding ) except UnicodeError : return s . decode ( fallback ) | Convert a string to unicode if it isn t already . |
15,590 | def uvalues ( a , encoding = 'utf-8' , fallback = 'iso-8859-1' ) : try : return encoding , [ s . decode ( encoding ) for s in a ] except UnicodeError : return fallback , [ s . decode ( fallback ) for s in a ] | Return a list of decoded values from an iterator . |
15,591 | def _build_query ( self ) : if isinstance ( self . _query_string , QueryString ) : self . _query_dsl = self . _query_string elif isinstance ( self . _query_string , string_types ) : self . _query_dsl = QueryString ( self . _query_string ) else : self . _query_dsl = MatchAll ( ) | Build the base query dictionary |
15,592 | def _build_filtered_query ( self , f , operator ) : self . _filtered = True if isinstance ( f , Filter ) : filter_object = f else : filter_object = Filter ( operator ) . filter ( f ) self . _filter_dsl = filter_object | Create the root of the filter tree |
15,593 | def filter ( self , f , operator = "and" ) : if self . _filtered : self . _filter_dsl . filter ( f ) else : self . _build_filtered_query ( f , operator ) return self | Add a filter to the query |
15,594 | def check ( self , inst , value ) : if not ( self . or_none and value is None ) : if self . seq : self . checktype_seq ( value , self . kind , unique = self . unique , inst = inst ) else : self . checktype ( value , self . kind , inst = inst ) | Raise TypeError if value doesn t satisfy the constraints for use on instance inst . |
15,595 | def normalize ( self , inst , value ) : if ( not ( self . or_none and value is None ) and self . seq ) : value = tuple ( value ) return value | Return value or a normalized form of it for use on instance inst . |
15,596 | def plot_decision_boundary ( model , X , y , step = 0.1 , figsize = ( 10 , 8 ) , alpha = 0.4 , size = 20 ) : x_min , x_max = X [ : , 0 ] . min ( ) - 1 , X [ : , 0 ] . max ( ) + 1 y_min , y_max = X [ : , 1 ] . min ( ) - 1 , X [ : , 1 ] . max ( ) + 1 xx , yy = np . meshgrid ( np . arange ( x_min , x_max , step ) , np . arange ( y_min , y_max , step ) ) f , ax = plt . subplots ( figsize = figsize ) Z = model . predict ( np . c_ [ xx . ravel ( ) , yy . ravel ( ) ] ) Z = Z . reshape ( xx . shape ) ax . contourf ( xx , yy , Z , alpha = alpha ) ax . scatter ( X [ : , 0 ] , X [ : , 1 ] , c = y , s = size , edgecolor = 'k' ) plt . show ( ) | Plots the classification decision boundary of model on X with labels y . Using numpy and matplotlib . |
15,597 | def ensure_argcount ( args , min_ = None , max_ = None ) : ensure_sequence ( args ) has_min = min_ is not None has_max = max_ is not None if not ( has_min or has_max ) : raise ValueError ( "minimum and/or maximum number of arguments must be provided" ) if has_min and has_max and min_ > max_ : raise ValueError ( "maximum number of arguments must be greater or equal to minimum" ) if has_min and len ( args ) < min_ : raise TypeError ( "expected at least %s arguments, got %s" % ( min_ , len ( args ) ) ) if has_max and len ( args ) > max_ : raise TypeError ( "expected at most %s arguments, got %s" % ( max_ , len ( args ) ) ) return args | Checks whether iterable of positional arguments satisfies conditions . |
15,598 | def ensure_keyword_args ( kwargs , mandatory = ( ) , optional = ( ) ) : from taipan . strings import ensure_string ensure_mapping ( kwargs ) mandatory = list ( map ( ensure_string , ensure_iterable ( mandatory ) ) ) optional = list ( map ( ensure_string , ensure_iterable ( optional ) ) ) if not ( mandatory or optional ) : raise ValueError ( "mandatory and/or optional argument names must be provided" ) names = set ( kwargs ) for name in mandatory : try : names . remove ( name ) except KeyError : raise TypeError ( "no value for mandatory keyword argument '%s'" % name ) excess = names - set ( optional ) if excess : if len ( excess ) == 1 : raise TypeError ( "unexpected keyword argument '%s'" % excess . pop ( ) ) else : raise TypeError ( "unexpected keyword arguments: %s" % ( tuple ( excess ) , ) ) return kwargs | Checks whether dictionary of keyword arguments satisfies conditions . |
15,599 | def _api_call ( self , path , data = { } , http_method = requests . get ) : log . info ( 'performing api request' , path = path ) response = http_method ( '/' . join ( [ self . api_url , path ] ) , params = { 'auth_token' : self . api_key } , data = data ) log . debug ( '{} remaining calls' . format ( response . headers [ 'x-ratelimit-remaining' ] ) ) return response . json ( ) | Process an http call against the hipchat api |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.