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 . ...
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...
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 , flo...
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 leg...
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 ( 'dayOfW...
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 sel...
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: {}" . forma...
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 ( TagGrou...
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 [...
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 (...
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...
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 ,...
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_impur...
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...
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' , '-f...
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 ...
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" : v...
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_A...
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 [ 'vers...
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-dat...
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 ] els...
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 ...
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 ) : ...
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 = df...
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 ] tr...
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 ...
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...
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 ....
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 : sel...
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 i...
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...
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 <...
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 . ...
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></...
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 ...
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 [ "m...
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 ) ) : _buil...
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...
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...
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 con...
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'...
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 , ex...
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 . a...
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 ( "maximu...
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 ...
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 . header...
Process an http call against the hipchat api