idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
2,700 | def _is_under_root ( self , full_path ) : if ( path . abspath ( full_path ) + path . sep ) . startswith ( path . abspath ( self . root ) + path . sep ) : return True else : return False | Guard against arbitrary file retrieval . | 57 | 6 |
2,701 | def _match_magic ( self , full_path ) : for magic in self . magics : if magic . matches ( full_path ) : return magic | Return the first magic that matches this path or None . | 33 | 11 |
2,702 | def _full_path ( self , path_info ) : full_path = self . root + path_info if path . exists ( full_path ) : return full_path else : for magic in self . magics : if path . exists ( magic . new_path ( full_path ) ) : return magic . new_path ( full_path ) else : return full_path | Return the full path from which to read . | 82 | 9 |
2,703 | def _guess_type ( self , full_path ) : magic = self . _match_magic ( full_path ) if magic is not None : return ( mimetypes . guess_type ( magic . old_path ( full_path ) ) [ 0 ] or 'text/plain' ) else : return mimetypes . guess_type ( full_path ) [ 0 ] or 'text/plain' | Guess the mime type magically or using the mimetypes module . | 88 | 15 |
2,704 | def _conditions ( self , full_path , environ ) : magic = self . _match_magic ( full_path ) if magic is not None : return magic . conditions ( full_path , environ ) else : mtime = stat ( full_path ) . st_mtime return str ( mtime ) , rfc822 . formatdate ( mtime ) | Return Etag and Last - Modified values defaults to now for both . | 80 | 14 |
2,705 | def _file_like ( self , full_path ) : magic = self . _match_magic ( full_path ) if magic is not None : return magic . file_like ( full_path , self . encoding ) else : return open ( full_path , 'rb' ) | Return the appropriate file object . | 60 | 6 |
2,706 | def old_path ( self , full_path ) : if self . matches ( full_path ) : return full_path [ : - len ( self . extension ) ] else : raise MagicError ( "Path does not match this magic." ) | Remove self . extension from path or raise MagicError . | 51 | 11 |
2,707 | def body ( self , environ , file_like ) : variables = environ . copy ( ) variables . update ( self . variables ) template = string . Template ( file_like . read ( ) ) if self . safe is True : return [ template . safe_substitute ( variables ) ] else : return [ template . substitute ( variables ) ] | Pass environ and self . variables in to template . | 74 | 11 |
2,708 | def get_rate_for ( self , currency : str , to : str , reverse : bool = False ) -> Number : # Return 1 when currencies match if currency . upper ( ) == to . upper ( ) : return self . _format_number ( '1.0' ) # Set base and quote currencies base , quote = currency , to if reverse : base , quote = to , currency try : # Ge... | Get current market rate for currency | 207 | 6 |
2,709 | def convert ( self , amount : Number , currency : str , to : str , reverse : bool = False ) -> Number : rate = self . get_rate_for ( currency , to , reverse ) if self . return_decimal : amount = Decimal ( amount ) return amount * rate | Convert amount to another currency | 61 | 6 |
2,710 | def convert_money ( self , money : Money , to : str , reverse : bool = False ) -> Money : converted = self . convert ( money . amount , money . currency , to , reverse ) return Money ( converted , to ) | Convert money to another currency | 49 | 6 |
2,711 | def add_icon_widget ( self , ref , x = 1 , y = 1 , name = "heart" ) : if ref not in self . widgets : widget = IconWidget ( screen = self , ref = ref , x = x , y = y , name = name ) self . widgets [ ref ] = widget return self . widgets [ ref ] | Add Icon Widget | 74 | 4 |
2,712 | def add_scroller_widget ( self , ref , left = 1 , top = 1 , right = 20 , bottom = 1 , direction = "h" , speed = 1 , text = "Message" ) : if ref not in self . widgets : widget = ScrollerWidget ( screen = self , ref = ref , left = left , top = top , right = right , bottom = bottom , direction = direction , speed = speed ... | Add Scroller Widget | 110 | 5 |
2,713 | def install_dir ( self ) : max_len = 500 directory = self . _get_str ( self . _iface . get_install_dir , [ self . app_id ] , max_len = max_len ) if not directory : # Fallback to restricted interface (can only be used by approved apps). directory = self . _get_str ( self . _iface_list . get_install_dir , [ self . app_id... | Returns application installation path . | 110 | 5 |
2,714 | def purchase_time ( self ) : ts = self . _iface . get_purchase_time ( self . app_id ) return datetime . utcfromtimestamp ( ts ) | Date and time of app purchase . | 41 | 7 |
2,715 | def get_args ( self ) : parser = argparse . ArgumentParser ( description = self . _desc , formatter_class = MyUniversalHelpFormatter ) # default args if self . _no_clean : parser . add_argument ( '--no-clean' , action = 'store_true' , help = 'If this flag is used, temporary work directory is not ' 'cleaned.' ) if self ... | Use this context manager to add arguments to an argparse object with the add_argument method . Arguments must be defined before the command is defined . Note that no - clean and resume are added upon exit and should not be added in the context manager . For more info about these default arguments see below . | 140 | 61 |
2,716 | def wrap_rankboost ( job , rsem_files , merged_mhc_calls , transgene_out , univ_options , rankboost_options ) : rankboost = job . addChildJobFn ( boost_ranks , rsem_files [ 'rsem.isoforms.results' ] , merged_mhc_calls , transgene_out , univ_options , rankboost_options ) return rankboost . rv ( ) | A wrapper for boost_ranks . | 104 | 8 |
2,717 | def _path_from_module ( module ) : # Convert paths to list because Python's _NamespacePath doesn't support # indexing. paths = list ( getattr ( module , '__path__' , [ ] ) ) if len ( paths ) != 1 : filename = getattr ( module , '__file__' , None ) if filename is not None : paths = [ os . path . dirname ( filename ) ] e... | Attempt to determine bot s filesystem path from its module . | 237 | 11 |
2,718 | def create ( cls , entry ) : # trading_bots.example.bot.ExampleBot try : # If import_module succeeds, entry is a path to a bot module, # which may specify a bot class with a default_bot attribute. # Otherwise, entry is a path to a bot class or an error. module = import_module ( entry ) except ImportError : # Track that... | Factory that creates an bot config from an entry in INSTALLED_APPS . | 418 | 17 |
2,719 | def get_config ( self , config_name , require_ready = True ) : if require_ready : self . bots . check_configs_ready ( ) else : self . bots . check_bots_ready ( ) return self . configs . get ( config_name . lower ( ) , { } ) | Return the config with the given case - insensitive config_name . Raise LookupError if no config exists with this name . | 67 | 25 |
2,720 | def get_configs ( self ) : self . bots . check_models_ready ( ) for config in self . configs . values ( ) : yield config | Return an iterable of models . | 34 | 7 |
2,721 | def populate ( self , installed_bots = None ) : if self . ready : return # populate() might be called by two threads in parallel on servers # that create threads before initializing the WSGI callable. with self . _lock : if self . ready : return # An RLock prevents other threads from entering this section. The # compar... | Load bots . Import each bot module . It is thread - safe and idempotent but not re - entrant . | 384 | 25 |
2,722 | def get_bot ( self , bot_label ) : self . check_bots_ready ( ) try : return self . bots [ bot_label ] except KeyError : message = "No installed bot with label '%s'." % bot_label for bot_cls in self . get_bots ( ) : if bot_cls . name == bot_label : message += " Did you mean '%s'?" % bot_cls . label break raise LookupErr... | Import all bots and returns a bot class for the given label . Raise LookupError if no bot exists with this label . | 104 | 25 |
2,723 | def get_configs ( self ) : self . check_configs_ready ( ) result = [ ] for bot in self . bots . values ( ) : result . extend ( list ( bot . get_models ( ) ) ) return result | Return a list of all installed configs . | 51 | 9 |
2,724 | def get_config ( self , bot_label , config_name = None , require_ready = True ) : if require_ready : self . check_configs_ready ( ) else : self . check_bots_ready ( ) if config_name is None : config_name = defaults . BOT_CONFIG bot = self . get_bot ( bot_label ) if not require_ready and bot . configs is None : bot . im... | Return the config matching the given bot_label and config_name . config_name is case - insensitive . Raise LookupError if no bot exists with this label or no config exists with this name in the bot . Raise ValueError if called with a single argument that doesn t contain exactly one dot . | 120 | 61 |
2,725 | def __to_float ( val , digits ) : try : return round ( float ( val ) , digits ) except ( ValueError , TypeError ) : return float ( 0 ) | Convert val into float with digits decimal . | 37 | 9 |
2,726 | def get_json_data ( latitude = 52.091579 , longitude = 5.119734 ) : final_result = { SUCCESS : False , MESSAGE : None , CONTENT : None , RAINCONTENT : None } log . info ( "Getting buienradar json data for latitude=%s, longitude=%s" , latitude , longitude ) result = __get_ws_data ( ) if result [ SUCCESS ] : # store json... | Get buienradar json data and return results . | 395 | 11 |
2,727 | def __get_precipfc_data ( latitude , longitude ) : url = 'https://gpsgadget.buienradar.nl/data/raintext?lat={}&lon={}' # rounding coordinates prevents unnecessary redirects/calls url = url . format ( round ( latitude , 2 ) , round ( longitude , 2 ) ) result = __get_url ( url ) return result | Get buienradar forecasted precipitation . | 90 | 9 |
2,728 | def __get_url ( url ) : log . info ( "Retrieving weather data (%s)..." , url ) result = { SUCCESS : False , MESSAGE : None } try : r = requests . get ( url ) result [ STATUS_CODE ] = r . status_code result [ HEADERS ] = r . headers result [ CONTENT ] = r . text if ( 200 == r . status_code ) : result [ SUCCESS ] = True ... | Load json data from url and return result . | 174 | 9 |
2,729 | def __parse_ws_data ( jsondata , latitude = 52.091579 , longitude = 5.119734 ) : log . info ( "Parse ws data: latitude: %s, longitude: %s" , latitude , longitude ) result = { SUCCESS : False , MESSAGE : None , DATA : None } # select the nearest weather station loc_data = __select_nearest_ws ( jsondata , latitude , long... | Parse the buienradar json and rain data . | 375 | 12 |
2,730 | def __parse_loc_data ( loc_data , result ) : result [ DATA ] = { ATTRIBUTION : ATTRIBUTION_INFO , FORECAST : [ ] , PRECIPITATION_FORECAST : None } for key , [ value , func ] in SENSOR_TYPES . items ( ) : result [ DATA ] [ key ] = None try : sens_data = loc_data [ value ] if key == CONDITION : # update weather symbol & ... | Parse the json data from selected weatherstation . | 324 | 10 |
2,731 | def __parse_fc_data ( fc_data ) : fc = [ ] for day in fc_data : fcdata = { CONDITION : __cond_from_desc ( __get_str ( day , __WEATHERDESCRIPTION ) ) , TEMPERATURE : __get_float ( day , __MAXTEMPERATURE ) , MIN_TEMP : __get_float ( day , __MINTEMPERATURE ) , MAX_TEMP : __get_float ( day , __MAXTEMPERATURE ) , SUN_CHANCE... | Parse the forecast data from the json section . | 319 | 10 |
2,732 | def __get_float ( section , name ) : try : return float ( section [ name ] ) except ( ValueError , TypeError , KeyError ) : return float ( 0 ) | Get the forecasted float from json section . | 38 | 9 |
2,733 | def __parse_precipfc_data ( data , timeframe ) : result = { AVERAGE : None , TOTAL : None , TIMEFRAME : None } log . debug ( "Precipitation data: %s" , data ) lines = data . splitlines ( ) index = 1 totalrain = 0 numberoflines = 0 nrlines = min ( len ( lines ) , round ( float ( timeframe ) / 5 ) + 1 ) # looping through... | Parse the forecasted precipitation data . | 558 | 8 |
2,734 | def __cond_from_desc ( desc ) : # '{ 'code': 'conditon', 'detailed', 'exact', 'exact_nl'} for code , [ condition , detailed , exact , exact_nl ] in __BRCONDITIONS . items ( ) : if exact_nl == desc : return { CONDCODE : code , CONDITION : condition , DETAILED : detailed , EXACT : exact , EXACTNL : exact_nl } return None | Get the condition name from the condition description . | 105 | 9 |
2,735 | def __get_ws_distance ( wstation , latitude , longitude ) : if wstation : try : wslat = float ( wstation [ __LAT ] ) wslon = float ( wstation [ __LON ] ) dist = vincenty ( ( latitude , longitude ) , ( wslat , wslon ) ) log . debug ( "calc distance: %s (latitude: %s, longitude: " "%s, wslat: %s, wslon: %s)" , dist , lat... | Get the distance to the weatherstation from wstation section of json . | 160 | 14 |
2,736 | def __getStationName ( name , id ) : name = name . replace ( "Meetstation" , "" ) name = name . strip ( ) name += " (%s)" % id return name | Construct a staiion name . | 41 | 7 |
2,737 | def as_view ( cls , * args , * * kwargs ) : initkwargs = cls . get_initkwargs ( * args , * * kwargs ) return super ( WizardView , cls ) . as_view ( * * initkwargs ) | This method is used within urls . py to create unique formwizard instances for every request . We need to override this method because we add some kwargs which are needed to make the formwizard usable . | 60 | 44 |
2,738 | def get_initkwargs ( cls , form_list , initial_dict = None , instance_dict = None , condition_dict = None , * args , * * kwargs ) : kwargs . update ( { 'initial_dict' : initial_dict or { } , 'instance_dict' : instance_dict or { } , 'condition_dict' : condition_dict or { } , } ) init_form_list = SortedDict ( ) assert le... | Creates a dict with all needed parameters for the form wizard instances . | 408 | 14 |
2,739 | def dispatch ( self , request , * args , * * kwargs ) : # add the storage engine to the current formwizard instance self . wizard_name = self . get_wizard_name ( ) self . prefix = self . get_prefix ( ) self . storage = get_storage ( self . storage_name , self . prefix , request , getattr ( self , 'file_storage' , None ... | This method gets called by the routing engine . The first argument is request which contains a HttpRequest instance . The request is stored in self . request for later use . The storage instance is stored in self . storage . | 146 | 44 |
2,740 | def get ( self , request , * args , * * kwargs ) : self . storage . reset ( ) # reset the current step to the first step. self . storage . current_step = self . steps . first return self . render ( self . get_form ( ) ) | This method handles GET requests . | 60 | 6 |
2,741 | def post ( self , * args , * * kwargs ) : # Look for a wizard_prev_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_prev_step = self . request . POST . get ( 'wizard_prev_step' , None ) if wizard_prev_step ... | This method handles POST requests . | 477 | 6 |
2,742 | def render_done ( self , form , * * kwargs ) : final_form_list = [ ] # walk through the form list and try to validate the data again. for form_key in self . get_form_list ( ) : form_obj = self . get_form ( step = form_key , data = self . storage . get_step_data ( form_key ) , files = self . storage . get_step_files ( f... | This method gets called when all forms passed . The method should also re - validate all steps to prevent manipulation . If any form don t validate render_revalidation_failure should get called . If everything is fine call done . | 214 | 47 |
2,743 | def get_form_prefix ( self , step = None , form = None ) : if step is None : step = self . steps . current return str ( step ) | Returns the prefix which will be used when calling the actual form for the given step . step contains the step - name form the form which will be called with the returned prefix . | 35 | 35 |
2,744 | def get_form ( self , step = None , data = None , files = None ) : if step is None : step = self . steps . current # prepare the kwargs for the form instance. kwargs = self . get_form_kwargs ( step ) kwargs . update ( { 'data' : data , 'files' : files , 'prefix' : self . get_form_prefix ( step , self . form_list [ step... | Constructs the form for a given step . If no step is defined the current step will be determined automatically . | 260 | 22 |
2,745 | def render_revalidation_failure ( self , step , form , * * kwargs ) : self . storage . current_step = step return self . render ( form , * * kwargs ) | Gets called when a form doesn t validate when rendering the done view . By default it changed the current step to failing forms step and renders the form . | 45 | 31 |
2,746 | def get_all_cleaned_data ( self ) : cleaned_data = { } for form_key in self . get_form_list ( ) : form_obj = self . get_form ( step = form_key , data = self . storage . get_step_data ( form_key ) , files = self . storage . get_step_files ( form_key ) ) if form_obj . is_valid ( ) : if isinstance ( form_obj . cleaned_dat... | Returns a merged dictionary of all step cleaned_data dictionaries . If a step contains a FormSet the key will be prefixed with formset and contain a list of the formset cleaned_data dictionaries . | 162 | 43 |
2,747 | def get_cleaned_data_for_step ( self , step ) : if step in self . form_list : form_obj = self . get_form ( step = step , data = self . storage . get_step_data ( step ) , files = self . storage . get_step_files ( step ) ) if form_obj . is_valid ( ) : return form_obj . cleaned_data return None | Returns the cleaned data for a given step . Before returning the cleaned data the stored values are being revalidated through the form . If the data doesn t validate None will be returned . | 91 | 37 |
2,748 | def get_step_index ( self , step = None ) : if step is None : step = self . steps . current return self . get_form_list ( ) . keyOrder . index ( step ) | Returns the index for the given step name . If no step is given the current step will be used to get the index . | 44 | 25 |
2,749 | def render ( self , form = None , * * kwargs ) : form = form or self . get_form ( ) context = self . get_context_data ( form , * * kwargs ) return self . render_to_response ( context ) | Returns a HttpResponse containing a all needed context data . | 56 | 12 |
2,750 | def get_initkwargs ( cls , * args , * * kwargs ) : assert 'url_name' in kwargs , 'URL name is needed to resolve correct wizard URLs' extra_kwargs = { 'done_step_name' : kwargs . pop ( 'done_step_name' , 'done' ) , 'url_name' : kwargs . pop ( 'url_name' ) , } initkwargs = super ( NamedUrlWizardView , cls ) . get_initkwa... | We require a url_name to reverse URLs later . Additionally users can pass a done_step_name to change the URL name of the done view . | 194 | 31 |
2,751 | def get ( self , * args , * * kwargs ) : step_url = kwargs . get ( 'step' , None ) if step_url is None : if 'reset' in self . request . GET : self . storage . reset ( ) self . storage . current_step = self . steps . first if self . request . GET : query_string = "?%s" % self . request . GET . urlencode ( ) else : query... | This renders the form or if needed does the http redirects . | 455 | 13 |
2,752 | def post ( self , * args , * * kwargs ) : prev_step = self . request . POST . get ( 'wizard_prev_step' , None ) if prev_step and prev_step in self . get_form_list ( ) : self . storage . current_step = prev_step return redirect ( self . url_name , step = prev_step ) return super ( NamedUrlWizardView , self ) . post ( * ... | Do a redirect if user presses the prev . step button . The rest of this is super d from FormWizard . | 106 | 24 |
2,753 | def render_next_step ( self , form , * * kwargs ) : next_step = self . get_next_step ( ) self . storage . current_step = next_step return redirect ( self . url_name , step = next_step ) | When using the NamedUrlFormWizard we have to redirect to update the browser s URL to match the shown step . | 57 | 24 |
2,754 | def render_revalidation_failure ( self , failed_step , form , * * kwargs ) : self . storage . current_step = failed_step return redirect ( self . url_name , step = failed_step ) | When a step fails we have to redirect the user to the first failing step . | 51 | 16 |
2,755 | def get_store ( logger : Logger = None ) -> 'Store' : from trading_bots . conf import settings store_settings = settings . storage store = store_settings . get ( 'name' , 'json' ) if store == 'json' : store = 'trading_bots.core.storage.JSONStore' elif store == 'redis' : store = 'trading_bots.core.storage.RedisStore' st... | Get and configure the storage backend | 141 | 6 |
2,756 | def parse_request_headers ( headers ) : request_header_keys = set ( headers . keys ( lower = True ) ) request_meta_keys = set ( XHEADERS_TO_ARGS_DICT . keys ( ) ) data_header_keys = request_header_keys . intersection ( request_meta_keys ) return dict ( ( [ XHEADERS_TO_ARGS_DICT [ key ] , headers . get ( key , None ) ] ... | convert headers in human readable format | 110 | 7 |
2,757 | def split_docstring ( docstring ) : docstring_list = [ line . strip ( ) for line in docstring . splitlines ( ) ] description_list = list ( takewhile ( lambda line : not ( line . startswith ( ':' ) or line . startswith ( '@inherit' ) ) , docstring_list ) ) description = ' ' . join ( description_list ) . strip ( ) first_... | Separates the method s description and paramter s | 269 | 11 |
2,758 | def get_method_docstring ( cls , method_name ) : method = getattr ( cls , method_name , None ) if method is None : return docstrign = inspect . getdoc ( method ) if docstrign is None : for base in cls . __bases__ : docstrign = get_method_docstring ( base , method_name ) if docstrign : return docstrign else : return Non... | return method docstring if method docstring is empty we get docstring from parent | 99 | 16 |
2,759 | def condition_from_code ( condcode ) : if condcode in __BRCONDITIONS : cond_data = __BRCONDITIONS [ condcode ] return { CONDCODE : condcode , CONDITION : cond_data [ 0 ] , DETAILED : cond_data [ 1 ] , EXACT : cond_data [ 2 ] , EXACTNL : cond_data [ 3 ] , } return None | Get the condition name from the condition code . | 92 | 9 |
2,760 | def validate ( self , * * kwargs ) : try : submission_file_schema = json . load ( open ( self . default_schema_file , 'r' ) ) additional_file_section_schema = json . load ( open ( self . additional_info_schema , 'r' ) ) # even though we are using the yaml package to load, # it supports JSON and YAML data = kwargs . pop... | Validates a submission file | 443 | 5 |
2,761 | def load_class_by_name ( name : str ) : mod_path , _ , cls_name = name . rpartition ( '.' ) mod = importlib . import_module ( mod_path ) cls = getattr ( mod , cls_name ) return cls | Given a dotted path returns the class | 63 | 7 |
2,762 | def load_yaml_file ( file_path : str ) : with codecs . open ( file_path , 'r' ) as f : return yaml . safe_load ( f ) | Load a YAML file from path | 42 | 8 |
2,763 | def run_itx_resistance_assessment ( job , rsem_files , univ_options , reports_options ) : return job . addChildJobFn ( assess_itx_resistance , rsem_files [ 'rsem.genes.results' ] , univ_options , reports_options ) . rv ( ) | A wrapper for assess_itx_resistance . | 76 | 11 |
2,764 | def CELERY_RESULT_BACKEND ( self ) : # allow specify directly configured = get ( 'CELERY_RESULT_BACKEND' , None ) if configured : return configured if not self . _redis_available ( ) : return None host , port = self . REDIS_HOST , self . REDIS_PORT if host and port : default = "redis://{host}:{port}/{db}" . format ( ho... | Redis result backend config | 123 | 5 |
2,765 | def BROKER_TYPE ( self ) : broker_type = get ( 'BROKER_TYPE' , DEFAULT_BROKER_TYPE ) if broker_type not in SUPPORTED_BROKER_TYPES : log . warn ( "Specified BROKER_TYPE {} not supported. Backing to default {}" . format ( broker_type , DEFAULT_BROKER_TYPE ) ) return DEFAULT_BROKER_TYPE else : return broker_type | Custom setting allowing switch between rabbitmq redis | 104 | 10 |
2,766 | def BROKER_URL ( self ) : # also allow specify broker_url broker_url = get ( 'BROKER_URL' , None ) if broker_url : log . info ( "Using BROKER_URL setting: {}" . format ( broker_url ) ) return broker_url redis_available = self . _redis_available ( ) broker_type = self . BROKER_TYPE if broker_type == 'redis' and not redi... | Sets BROKER_URL depending on redis or rabbitmq settings | 329 | 16 |
2,767 | def traverse_inventory ( self , item_filter = None ) : not self . _intentory_raw and self . _get_inventory_raw ( ) for item in self . _intentory_raw [ 'rgDescriptions' ] . values ( ) : tags = item [ 'tags' ] for tag in tags : internal_name = tag [ 'internal_name' ] if item_filter is None or internal_name == item_filter... | Generates market Item objects for each inventory item . | 152 | 10 |
2,768 | def validate ( self , * * kwargs ) : default_data_schema = json . load ( open ( self . default_schema_file , 'r' ) ) # even though we are using the yaml package to load, # it supports JSON and YAML data = kwargs . pop ( "data" , None ) file_path = kwargs . pop ( "file_path" , None ) if file_path is None : raise LookupE... | Validates a data file | 315 | 5 |
2,769 | def b ( s ) : if sys . version < '3' : if isinstance ( s , unicode ) : #pylint: disable=undefined-variable return s . encode ( 'utf-8' ) else : return s | Conversion to bytes | 51 | 4 |
2,770 | def validatefeatures ( self , features ) : validatedfeatures = [ ] for feature in features : if isinstance ( feature , int ) or isinstance ( feature , float ) : validatedfeatures . append ( str ( feature ) ) elif self . delimiter in feature and not self . sklearn : raise ValueError ( "Feature contains delimiter: " + fe... | Returns features in validated form or raises an Exception . Mostly for internal use | 115 | 14 |
2,771 | def addinstance ( self , testfile , features , classlabel = "?" ) : features = self . validatefeatures ( features ) if self . delimiter in classlabel : raise ValueError ( "Class label contains delimiter: " + self . delimiter ) f = io . open ( testfile , 'a' , encoding = self . encoding ) f . write ( self . delimiter . ... | Adds an instance to a specific file . Especially suitable for generating test files | 104 | 14 |
2,772 | def crossvalidate ( self , foldsfile ) : options = "-F " + self . format + " " + self . timbloptions + " -t cross_validate" print ( "Instantiating Timbl API : " + options , file = stderr ) if sys . version < '3' : self . api = timblapi . TimblAPI ( b ( options ) , b"" ) else : self . api = timblapi . TimblAPI ( options... | Train & Test using cross validation testfile is a file that contains the filenames of all the folds! | 216 | 22 |
2,773 | def leaveoneout ( self ) : traintestfile = self . fileprefix + '.train' options = "-F " + self . format + " " + self . timbloptions + " -t leave_one_out" if sys . version < '3' : self . api = timblapi . TimblAPI ( b ( options ) , b"" ) else : self . api = timblapi . TimblAPI ( options , "" ) if self . debug : print ( "... | Train & Test using leave one out | 251 | 7 |
2,774 | def set_action_cache ( self , action_key , data ) : if self . cache : self . cache . set ( self . app . config [ 'ACCESS_ACTION_CACHE_PREFIX' ] + action_key , data ) | Store action needs and excludes . | 55 | 6 |
2,775 | def get_action_cache ( self , action_key ) : data = None if self . cache : data = self . cache . get ( self . app . config [ 'ACCESS_ACTION_CACHE_PREFIX' ] + action_key ) return data | Get action needs and excludes from cache . | 58 | 8 |
2,776 | def delete_action_cache ( self , action_key ) : if self . cache : self . cache . delete ( self . app . config [ 'ACCESS_ACTION_CACHE_PREFIX' ] + action_key ) | Delete action needs and excludes from cache . | 51 | 8 |
2,777 | def register_action ( self , action ) : assert action . value not in self . actions self . actions [ action . value ] = action | Register an action to be showed in the actions list . | 29 | 11 |
2,778 | def register_system_role ( self , system_role ) : assert system_role . value not in self . system_roles self . system_roles [ system_role . value ] = system_role | Register a system role . | 45 | 5 |
2,779 | def load_entry_point_system_roles ( self , entry_point_group ) : for ep in pkg_resources . iter_entry_points ( group = entry_point_group ) : self . register_system_role ( ep . load ( ) ) | Load system roles from an entry point group . | 58 | 9 |
2,780 | def main ( argv = sys . argv [ 1 : ] ) : args = docopt ( __doc__ , argv = argv , version = pkg_resources . require ( 'buienradar' ) [ 0 ] . version ) level = logging . ERROR if args [ '-v' ] : level = logging . INFO if args [ '-v' ] == 2 : level = logging . DEBUG logging . basicConfig ( level = level ) log = logging . ... | Parse argument and start main program . | 287 | 8 |
2,781 | def global_unlock_percent ( self ) : percent = CRef . cfloat ( ) result = self . _iface . get_ach_progress ( self . name , percent ) if not result : return 0.0 return float ( percent ) | Global achievement unlock percent . | 53 | 5 |
2,782 | def unlocked ( self ) : achieved = CRef . cbool ( ) result = self . _iface . get_ach ( self . name , achieved ) if not result : return False return bool ( achieved ) | True if achievement is unlocked . | 44 | 6 |
2,783 | def unlock ( self , store = True ) : result = self . _iface . ach_unlock ( self . name ) result and store and self . _store ( ) return result | Unlocks the achievement . | 40 | 5 |
2,784 | def __parse_ws_data ( content , latitude = 52.091579 , longitude = 5.119734 ) : log . info ( "Parse ws data: latitude: %s, longitude: %s" , latitude , longitude ) result = { SUCCESS : False , MESSAGE : None , DATA : None } # convert the xml data into a dictionary: try : xmldata = xmltodict . parse ( content ) [ __BRROO... | Parse the buienradar xml and rain data . | 465 | 12 |
2,785 | def __parse_loc_data ( loc_data , result ) : result [ DATA ] = { ATTRIBUTION : ATTRIBUTION_INFO , FORECAST : [ ] , PRECIPITATION_FORECAST : None } for key , [ value , func ] in SENSOR_TYPES . items ( ) : result [ DATA ] [ key ] = None try : from buienradar . buienradar import condition_from_code sens_data = loc_data [ ... | Parse the xml data from selected weatherstation . | 362 | 10 |
2,786 | def __parse_fc_data ( fc_data ) : from buienradar . buienradar import condition_from_code fc = [ ] for daycnt in range ( 1 , 6 ) : daysection = __BRDAYFC % daycnt if daysection in fc_data : tmpsect = fc_data [ daysection ] fcdatetime = datetime . now ( pytz . timezone ( __TIMEZONE ) ) fcdatetime = fcdatetime . replace ... | Parse the forecast data from the xml section . | 414 | 10 |
2,787 | def __get_ws_distance ( wstation , latitude , longitude ) : if wstation : try : wslat = float ( wstation [ __BRLAT ] ) wslon = float ( wstation [ __BRLON ] ) dist = vincenty ( ( latitude , longitude ) , ( wslat , wslon ) ) log . debug ( "calc distance: %s (latitude: %s, longitude: " "%s, wslat: %s, wslon: %s)" , dist ,... | Get the distance to the weatherstation from wstation section of xml . | 162 | 14 |
2,788 | def predict_mhcii_binding ( job , peptfile , allele , univ_options , mhcii_options ) : work_dir = os . getcwd ( ) input_files = { 'peptfile.faa' : peptfile } input_files = get_files_from_filestore ( job , input_files , work_dir , docker = True ) peptides = read_peptide_file ( os . path . join ( os . getcwd ( ) , 'peptf... | Predict binding for each peptide in peptfile to allele using the IEDB mhcii binding prediction tool . | 623 | 25 |
2,789 | def predict_netmhcii_binding ( job , peptfile , allele , univ_options , netmhciipan_options ) : work_dir = os . getcwd ( ) input_files = { 'peptfile.faa' : peptfile } input_files = get_files_from_filestore ( job , input_files , work_dir , docker = True ) peptides = read_peptide_file ( os . path . join ( os . getcwd ( )... | Predict binding for each peptide in peptfile to allele using netMHCIIpan . | 549 | 19 |
2,790 | def update ( self , permission ) : self . needs . update ( permission . needs ) self . excludes . update ( permission . excludes ) | In - place update of permissions . | 28 | 7 |
2,791 | def _load_permissions ( self ) : result = _P ( needs = set ( ) , excludes = set ( ) ) if not self . allow_by_default : result . needs . update ( self . explicit_needs ) for explicit_need in self . explicit_needs : if explicit_need . method == 'action' : action = current_access . get_action_cache ( self . _cache_key ( e... | Load permissions associated to actions . | 305 | 6 |
2,792 | def lazy_result ( f ) : @ wraps ( f ) def decorated ( ctx , param , value ) : return LocalProxy ( lambda : f ( ctx , param , value ) ) return decorated | Decorate function to return LazyProxy . | 42 | 9 |
2,793 | def process_action ( ctx , param , value ) : actions = current_app . extensions [ 'invenio-access' ] . actions if value not in actions : raise click . BadParameter ( 'Action "%s" is not registered.' , value ) return actions [ value ] | Return an action if exists . | 60 | 6 |
2,794 | def process_email ( ctx , param , value ) : user = User . query . filter ( User . email == value ) . first ( ) if not user : raise click . BadParameter ( 'User with email \'%s\' not found.' , value ) return user | Return an user if it exists . | 57 | 7 |
2,795 | def process_role ( ctx , param , value ) : role = Role . query . filter ( Role . name == value ) . first ( ) if not role : raise click . BadParameter ( 'Role with name \'%s\' not found.' , value ) return role | Return a role if it exists . | 57 | 7 |
2,796 | def allow_user ( user ) : def processor ( action , argument ) : db . session . add ( ActionUsers . allow ( action , argument = argument , user_id = user . id ) ) return processor | Allow a user identified by an email address . | 44 | 9 |
2,797 | def allow_role ( role ) : def processor ( action , argument ) : db . session . add ( ActionRoles . allow ( action , argument = argument , role_id = role . id ) ) return processor | Allow a role identified by an email address . | 45 | 9 |
2,798 | def process_allow_action ( processors , action , argument ) : for processor in processors : processor ( action , argument ) db . session . commit ( ) | Process allow action . | 32 | 4 |
2,799 | def deny_user ( user ) : def processor ( action , argument ) : db . session . add ( ActionUsers . deny ( action , argument = argument , user_id = user . id ) ) return processor | Deny a user identified by an email address . | 44 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.