idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
245,000 | def bucket ( self , experiment , user_id , bucketing_id ) : if not experiment : return None if experiment . groupPolicy in GROUP_POLICIES : group = self . config . get_group ( experiment . groupId ) if not group : return None user_experiment_id = self . find_bucket ( bucketing_id , experiment . groupId , group . traffi... | For a given experiment and bucketing ID determines variation to be shown to user . |
245,001 | def _generate_key_map ( entity_list , key , entity_class ) : key_map = { } for obj in entity_list : key_map [ obj [ key ] ] = entity_class ( ** obj ) return key_map | Helper method to generate map from key to entity object for given list of dicts . |
245,002 | def _deserialize_audience ( audience_map ) : for audience in audience_map . values ( ) : condition_structure , condition_list = condition_helper . loads ( audience . conditions ) audience . __dict__ . update ( { 'conditionStructure' : condition_structure , 'conditionList' : condition_list } ) return audience_map | Helper method to de - serialize and populate audience map with the condition list and structure . |
245,003 | def get_typecast_value ( self , value , type ) : if type == entities . Variable . Type . BOOLEAN : return value == 'true' elif type == entities . Variable . Type . INTEGER : return int ( value ) elif type == entities . Variable . Type . DOUBLE : return float ( value ) else : return value | Helper method to determine actual value based on type of feature variable . |
245,004 | def get_experiment_from_key ( self , experiment_key ) : experiment = self . experiment_key_map . get ( experiment_key ) if experiment : return experiment self . logger . error ( 'Experiment key "%s" is not in datafile.' % experiment_key ) self . error_handler . handle_error ( exceptions . InvalidExperimentException ( e... | Get experiment for the provided experiment key . |
245,005 | def get_experiment_from_id ( self , experiment_id ) : experiment = self . experiment_id_map . get ( experiment_id ) if experiment : return experiment self . logger . error ( 'Experiment ID "%s" is not in datafile.' % experiment_id ) self . error_handler . handle_error ( exceptions . InvalidExperimentException ( enums .... | Get experiment for the provided experiment ID . |
245,006 | def get_group ( self , group_id ) : group = self . group_id_map . get ( group_id ) if group : return group self . logger . error ( 'Group ID "%s" is not in datafile.' % group_id ) self . error_handler . handle_error ( exceptions . InvalidGroupException ( enums . Errors . INVALID_GROUP_ID_ERROR ) ) return None | Get group for the provided group ID . |
245,007 | def get_audience ( self , audience_id ) : audience = self . audience_id_map . get ( audience_id ) if audience : return audience self . logger . error ( 'Audience ID "%s" is not in datafile.' % audience_id ) self . error_handler . handle_error ( exceptions . InvalidAudienceException ( ( enums . Errors . INVALID_AUDIENCE... | Get audience object for the provided audience ID . |
245,008 | def get_variation_from_key ( self , experiment_key , variation_key ) : variation_map = self . variation_key_map . get ( experiment_key ) if variation_map : variation = variation_map . get ( variation_key ) if variation : return variation else : self . logger . error ( 'Variation key "%s" is not in datafile.' % variatio... | Get variation given experiment and variation key . |
245,009 | def get_variation_from_id ( self , experiment_key , variation_id ) : variation_map = self . variation_id_map . get ( experiment_key ) if variation_map : variation = variation_map . get ( variation_id ) if variation : return variation else : self . logger . error ( 'Variation ID "%s" is not in datafile.' % variation_id ... | Get variation given experiment and variation ID . |
245,010 | def get_event ( self , event_key ) : event = self . event_key_map . get ( event_key ) if event : return event self . logger . error ( 'Event "%s" is not in datafile.' % event_key ) self . error_handler . handle_error ( exceptions . InvalidEventException ( enums . Errors . INVALID_EVENT_KEY_ERROR ) ) return None | Get event for the provided event key . |
245,011 | def get_attribute_id ( self , attribute_key ) : attribute = self . attribute_key_map . get ( attribute_key ) has_reserved_prefix = attribute_key . startswith ( RESERVED_ATTRIBUTE_PREFIX ) if attribute : if has_reserved_prefix : self . logger . warning ( ( 'Attribute %s unexpectedly has reserved prefix %s; using attribu... | Get attribute ID for the provided attribute key . |
245,012 | def get_feature_from_key ( self , feature_key ) : feature = self . feature_key_map . get ( feature_key ) if feature : return feature self . logger . error ( 'Feature "%s" is not in datafile.' % feature_key ) return None | Get feature for the provided feature key . |
245,013 | def get_rollout_from_id ( self , rollout_id ) : layer = self . rollout_id_map . get ( rollout_id ) if layer : return layer self . logger . error ( 'Rollout with ID "%s" is not in datafile.' % rollout_id ) return None | Get rollout for the provided ID . |
245,014 | def get_variable_value_for_variation ( self , variable , variation ) : if not variable or not variation : return None if variation . id not in self . variation_variable_usage_map : self . logger . error ( 'Variation with ID "%s" is not in the datafile.' % variation . id ) return None variable_usages = self . variation_... | Get the variable value for the given variation . |
245,015 | def get_variable_for_feature ( self , feature_key , variable_key ) : feature = self . feature_key_map . get ( feature_key ) if not feature : self . logger . error ( 'Feature with key "%s" not found in the datafile.' % feature_key ) return None if variable_key not in feature . variables : self . logger . error ( 'Variab... | Get the variable with the given variable key for the given feature . |
245,016 | def set_forced_variation ( self , experiment_key , user_id , variation_key ) : experiment = self . get_experiment_from_key ( experiment_key ) if not experiment : return False experiment_id = experiment . id if variation_key is None : if user_id in self . forced_variation_map : experiment_to_variation_map = self . force... | Sets users to a map of experiments to forced variations . |
245,017 | def get_forced_variation ( self , experiment_key , user_id ) : if user_id not in self . forced_variation_map : self . logger . debug ( 'User "%s" is not in the forced variation map.' % user_id ) return None experiment = self . get_experiment_from_key ( experiment_key ) if not experiment : return None experiment_to_vari... | Gets the forced variation key for the given user and experiment . |
245,018 | def dispatch_event ( event ) : try : if event . http_verb == enums . HTTPVerbs . GET : requests . get ( event . url , params = event . params , timeout = REQUEST_TIMEOUT ) . raise_for_status ( ) elif event . http_verb == enums . HTTPVerbs . POST : requests . post ( event . url , data = json . dumps ( event . params ) ,... | Dispatch the event being represented by the Event object . |
245,019 | def _validate_instantiation_options ( self , datafile , skip_json_validation ) : if not skip_json_validation and not validator . is_datafile_valid ( datafile ) : raise exceptions . InvalidInputException ( enums . Errors . INVALID_INPUT_ERROR . format ( 'datafile' ) ) if not validator . is_event_dispatcher_valid ( self ... | Helper method to validate all instantiation parameters . |
245,020 | def _validate_user_inputs ( self , attributes = None , event_tags = None ) : if attributes and not validator . are_attributes_valid ( attributes ) : self . logger . error ( 'Provided attributes are in an invalid format.' ) self . error_handler . handle_error ( exceptions . InvalidAttributeException ( enums . Errors . I... | Helper method to validate user inputs . |
245,021 | def _send_impression_event ( self , experiment , variation , user_id , attributes ) : impression_event = self . event_builder . create_impression_event ( experiment , variation . id , user_id , attributes ) self . logger . debug ( 'Dispatching impression event to URL %s with params %s.' % ( impression_event . url , imp... | Helper method to send impression event . |
245,022 | def _get_feature_variable_for_type ( self , feature_key , variable_key , variable_type , user_id , attributes ) : if not validator . is_non_empty_string ( feature_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'feature_key' ) ) return None if not validator . is_non_empty_string ( variab... | Helper method to determine value for a certain variable attached to a feature flag based on type of variable . |
245,023 | def activate ( self , experiment_key , user_id , attributes = None ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'activate' ) ) return None if not validator . is_non_empty_string ( experiment_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . forma... | Buckets visitor and sends impression event to Optimizely . |
245,024 | def track ( self , event_key , user_id , attributes = None , event_tags = None ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'track' ) ) return if not validator . is_non_empty_string ( event_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format... | Send conversion event to Optimizely . |
245,025 | def get_variation ( self , experiment_key , user_id , attributes = None ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'get_variation' ) ) return None if not validator . is_non_empty_string ( experiment_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERR... | Gets variation where user will be bucketed . |
245,026 | def is_feature_enabled ( self , feature_key , user_id , attributes = None ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'is_feature_enabled' ) ) return False if not validator . is_non_empty_string ( feature_key ) : self . logger . error ( enums . Errors . INVALID_INPU... | Returns true if the feature is enabled for the given user . |
245,027 | def get_enabled_features ( self , user_id , attributes = None ) : enabled_features = [ ] if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'get_enabled_features' ) ) return enabled_features if not isinstance ( user_id , string_types ) : self . logger . error ( enums . Errors ... | Returns the list of features that are enabled for the user . |
245,028 | def get_feature_variable_boolean ( self , feature_key , variable_key , user_id , attributes = None ) : variable_type = entities . Variable . Type . BOOLEAN return self . _get_feature_variable_for_type ( feature_key , variable_key , variable_type , user_id , attributes ) | Returns value for a certain boolean variable attached to a feature flag . |
245,029 | def get_feature_variable_double ( self , feature_key , variable_key , user_id , attributes = None ) : variable_type = entities . Variable . Type . DOUBLE return self . _get_feature_variable_for_type ( feature_key , variable_key , variable_type , user_id , attributes ) | Returns value for a certain double variable attached to a feature flag . |
245,030 | def get_feature_variable_integer ( self , feature_key , variable_key , user_id , attributes = None ) : variable_type = entities . Variable . Type . INTEGER return self . _get_feature_variable_for_type ( feature_key , variable_key , variable_type , user_id , attributes ) | Returns value for a certain integer variable attached to a feature flag . |
245,031 | def get_feature_variable_string ( self , feature_key , variable_key , user_id , attributes = None ) : variable_type = entities . Variable . Type . STRING return self . _get_feature_variable_for_type ( feature_key , variable_key , variable_type , user_id , attributes ) | Returns value for a certain string variable attached to a feature . |
245,032 | def set_forced_variation ( self , experiment_key , user_id , variation_key ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'set_forced_variation' ) ) return False if not validator . is_non_empty_string ( experiment_key ) : self . logger . error ( enums . Errors . INVALI... | Force a user into a variation for a given experiment . |
245,033 | def get_forced_variation ( self , experiment_key , user_id ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'get_forced_variation' ) ) return None if not validator . is_non_empty_string ( experiment_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . f... | Gets the forced variation for a given user and experiment . |
245,034 | def is_user_in_experiment ( config , experiment , attributes , logger ) : audience_conditions = experiment . getAudienceConditionsOrIds ( ) logger . debug ( audience_logs . EVALUATING_AUDIENCES_COMBINED . format ( experiment . key , json . dumps ( audience_conditions ) ) ) if audience_conditions is None or audience_con... | Determine for given experiment if user satisfies the audiences for the experiment . |
245,035 | def _get_common_params ( self , user_id , attributes ) : commonParams = { } commonParams [ self . EventParams . PROJECT_ID ] = self . _get_project_id ( ) commonParams [ self . EventParams . ACCOUNT_ID ] = self . _get_account_id ( ) visitor = { } visitor [ self . EventParams . END_USER_ID ] = user_id visitor [ self . Ev... | Get params which are used same in both conversion and impression events . |
245,036 | def _get_required_params_for_impression ( self , experiment , variation_id ) : snapshot = { } snapshot [ self . EventParams . DECISIONS ] = [ { self . EventParams . EXPERIMENT_ID : experiment . id , self . EventParams . VARIATION_ID : variation_id , self . EventParams . CAMPAIGN_ID : experiment . layerId } ] snapshot [... | Get parameters that are required for the impression event to register . |
245,037 | def _get_required_params_for_conversion ( self , event_key , event_tags ) : snapshot = { } event_dict = { self . EventParams . EVENT_ID : self . config . get_event ( event_key ) . id , self . EventParams . TIME : self . _get_time ( ) , self . EventParams . KEY : event_key , self . EventParams . UUID : str ( uuid . uuid... | Get parameters that are required for the conversion event to register . |
245,038 | def create_impression_event ( self , experiment , variation_id , user_id , attributes ) : params = self . _get_common_params ( user_id , attributes ) impression_params = self . _get_required_params_for_impression ( experiment , variation_id ) params [ self . EventParams . USERS ] [ 0 ] [ self . EventParams . SNAPSHOTS ... | Create impression Event to be sent to the logging endpoint . |
245,039 | def create_conversion_event ( self , event_key , user_id , attributes , event_tags ) : params = self . _get_common_params ( user_id , attributes ) conversion_params = self . _get_required_params_for_conversion ( event_key , event_tags ) params [ self . EventParams . USERS ] [ 0 ] [ self . EventParams . SNAPSHOTS ] . ap... | Create conversion Event to be sent to the logging endpoint . |
245,040 | def _audience_condition_deserializer ( obj_dict ) : return [ obj_dict . get ( 'name' ) , obj_dict . get ( 'value' ) , obj_dict . get ( 'type' ) , obj_dict . get ( 'match' ) ] | Deserializer defining how dict objects need to be decoded for audience conditions . |
245,041 | def _get_condition_json ( self , index ) : condition = self . condition_data [ index ] condition_log = { 'name' : condition [ 0 ] , 'value' : condition [ 1 ] , 'type' : condition [ 2 ] , 'match' : condition [ 3 ] } return json . dumps ( condition_log ) | Method to generate json for logging audience condition . |
245,042 | def is_value_type_valid_for_exact_conditions ( self , value ) : if isinstance ( value , string_types ) or isinstance ( value , ( numbers . Integral , float ) ) : return True return False | Method to validate if the value is valid for exact match type evaluation . |
245,043 | def exists_evaluator ( self , index ) : attr_name = self . condition_data [ index ] [ 0 ] return self . attributes . get ( attr_name ) is not None | Evaluate the given exists match condition for the user attributes . |
245,044 | def greater_than_evaluator ( self , index ) : condition_name = self . condition_data [ index ] [ 0 ] condition_value = self . condition_data [ index ] [ 1 ] user_value = self . attributes . get ( condition_name ) if not validator . is_finite_number ( condition_value ) : self . logger . warning ( audience_logs . UNKNOWN... | Evaluate the given greater than match condition for the user attributes . |
245,045 | def substring_evaluator ( self , index ) : condition_name = self . condition_data [ index ] [ 0 ] condition_value = self . condition_data [ index ] [ 1 ] user_value = self . attributes . get ( condition_name ) if not isinstance ( condition_value , string_types ) : self . logger . warning ( audience_logs . UNKNOWN_CONDI... | Evaluate the given substring match condition for the given user attributes . |
245,046 | def evaluate ( self , index ) : if self . condition_data [ index ] [ 2 ] != self . CUSTOM_ATTRIBUTE_CONDITION_TYPE : self . logger . warning ( audience_logs . UNKNOWN_CONDITION_TYPE . format ( self . _get_condition_json ( index ) ) ) return None condition_match = self . condition_data [ index ] [ 3 ] if condition_match... | Given a custom attribute audience condition and user attributes evaluate the condition against the attributes . |
245,047 | def object_hook ( self , object_dict ) : instance = self . decoder ( object_dict ) self . condition_list . append ( instance ) self . index += 1 return self . index | Hook which when passed into a json . JSONDecoder will replace each dict in a json string with its index and convert the dict to an object as defined by the passed in condition_decoder . The newly created condition object is appended to the conditions_list . |
245,048 | def _get_bucketing_id ( self , user_id , attributes ) : attributes = attributes or { } bucketing_id = attributes . get ( enums . ControlAttributes . BUCKETING_ID ) if bucketing_id is not None : if isinstance ( bucketing_id , string_types ) : return bucketing_id self . logger . warning ( 'Bucketing ID attribute is not a... | Helper method to determine bucketing ID for the user . |
245,049 | def get_forced_variation ( self , experiment , user_id ) : forced_variations = experiment . forcedVariations if forced_variations and user_id in forced_variations : variation_key = forced_variations . get ( user_id ) variation = self . config . get_variation_from_key ( experiment . key , variation_key ) if variation : ... | Determine if a user is forced into a variation for the given experiment and return that variation . |
245,050 | def get_stored_variation ( self , experiment , user_profile ) : user_id = user_profile . user_id variation_id = user_profile . get_variation_for_experiment ( experiment . id ) if variation_id : variation = self . config . get_variation_from_id ( experiment . key , variation_id ) if variation : self . logger . info ( 'F... | Determine if the user has a stored variation available for the given experiment and return that . |
245,051 | def get_variation ( self , experiment , user_id , attributes , ignore_user_profile = False ) : if not experiment_helper . is_experiment_running ( experiment ) : self . logger . info ( 'Experiment "%s" is not running.' % experiment . key ) return None variation = self . config . get_forced_variation ( experiment . key ,... | Top - level function to help determine variation user should be put in . |
245,052 | def get_experiment_in_group ( self , group , bucketing_id ) : experiment_id = self . bucketer . find_bucket ( bucketing_id , group . id , group . trafficAllocation ) if experiment_id : experiment = self . config . get_experiment_from_id ( experiment_id ) if experiment : self . logger . info ( 'User with bucketing ID "%... | Determine which experiment in the group the user is bucketed into . |
245,053 | def add_notification_listener ( self , notification_type , notification_callback ) : if notification_type not in self . notifications : self . notifications [ notification_type ] = [ ( self . notification_id , notification_callback ) ] else : if reduce ( lambda a , b : a + 1 , filter ( lambda tup : tup [ 1 ] == notific... | Add a notification callback to the notification center . |
245,054 | def remove_notification_listener ( self , notification_id ) : for v in self . notifications . values ( ) : toRemove = list ( filter ( lambda tup : tup [ 0 ] == notification_id , v ) ) if len ( toRemove ) > 0 : v . remove ( toRemove [ 0 ] ) return True return False | Remove a previously added notification callback . |
245,055 | def send_notifications ( self , notification_type , * args ) : if notification_type in self . notifications : for notification_id , callback in self . notifications [ notification_type ] : try : callback ( * args ) except : self . logger . exception ( 'Problem calling notify callback!' ) | Fires off the notification for the specific event . Uses var args to pass in a arbitrary list of parameter according to which notification type was fired . |
245,056 | def and_evaluator ( conditions , leaf_evaluator ) : saw_null_result = False for condition in conditions : result = evaluate ( condition , leaf_evaluator ) if result is False : return False if result is None : saw_null_result = True return None if saw_null_result else True | Evaluates a list of conditions as if the evaluator had been applied to each entry and the results AND - ed together . |
245,057 | def not_evaluator ( conditions , leaf_evaluator ) : if not len ( conditions ) > 0 : return None result = evaluate ( conditions [ 0 ] , leaf_evaluator ) return None if result is None else not result | Evaluates a list of conditions as if the evaluator had been applied to a single entry and NOT was applied to the result . |
245,058 | def evaluate ( conditions , leaf_evaluator ) : if isinstance ( conditions , list ) : if conditions [ 0 ] in list ( EVALUATORS_BY_OPERATOR_TYPE . keys ( ) ) : return EVALUATORS_BY_OPERATOR_TYPE [ conditions [ 0 ] ] ( conditions [ 1 : ] , leaf_evaluator ) else : return EVALUATORS_BY_OPERATOR_TYPE [ ConditionOperatorTypes... | Top level method to evaluate conditions . |
245,059 | def data_objet_class ( data_mode = 'value' , time_mode = 'framewise' ) : classes_table = { ( 'value' , 'global' ) : GlobalValueObject , ( 'value' , 'event' ) : EventValueObject , ( 'value' , 'segment' ) : SegmentValueObject , ( 'value' , 'framewise' ) : FrameValueObject , ( 'label' , 'global' ) : GlobalLabelObject , ( ... | Factory function for Analyzer result |
245,060 | def JSON_NumpyArrayEncoder ( obj ) : if isinstance ( obj , np . ndarray ) : return { 'numpyArray' : obj . tolist ( ) , 'dtype' : obj . dtype . __str__ ( ) } elif isinstance ( obj , np . generic ) : return np . asscalar ( obj ) else : print type ( obj ) raise TypeError ( repr ( obj ) + " is not JSON serializable" ) | Define Specialize JSON encoder for numpy array |
245,061 | def render ( self ) : fig , ax = plt . subplots ( ) self . data_object . _render_plot ( ax ) return fig | Render a matplotlib figure from the analyzer result |
245,062 | def new_result ( self , data_mode = 'value' , time_mode = 'framewise' ) : from datetime import datetime result = AnalyzerResult ( data_mode = data_mode , time_mode = time_mode ) result . id_metadata . date = datetime . now ( ) . replace ( microsecond = 0 ) . isoformat ( ' ' ) result . id_metadata . version = timeside .... | Create a new result |
245,063 | def downmix_to_mono ( process_func ) : import functools @ functools . wraps ( process_func ) def wrapper ( analyzer , frames , eod ) : if frames . ndim > 1 : downmix_frames = frames . mean ( axis = - 1 ) else : downmix_frames = frames process_func ( analyzer , downmix_frames , eod ) return frames , eod return wrapper | Pre - processing decorator that downmixes frames from multi - channel to mono |
245,064 | def frames_adapter ( process_func ) : import functools import numpy as np class framesBuffer ( object ) : def __init__ ( self , blocksize , stepsize ) : self . blocksize = blocksize self . stepsize = stepsize self . buffer = None def frames ( self , frames , eod ) : if self . buffer is not None : stack = np . concatena... | Pre - processing decorator that adapt frames to match input_blocksize and input_stepsize of the decorated analyzer |
245,065 | def get_uri ( self ) : if self . source_file and os . path . exists ( self . source_file . path ) : return self . source_file . path elif self . source_url : return self . source_url return None | Return the Item source |
245,066 | def get_audio_duration ( self ) : decoder = timeside . core . get_processor ( 'file_decoder' ) ( uri = self . get_uri ( ) ) return decoder . uri_total_duration | Return item audio duration |
245,067 | def get_results_path ( self ) : result_path = os . path . join ( RESULTS_ROOT , self . uuid ) if not os . path . exists ( result_path ) : os . makedirs ( result_path ) return result_path | Return Item result path |
245,068 | def get_uri ( source ) : import gst src_info = source_info ( source ) if src_info [ 'is_file' ] : return get_uri ( src_info [ 'uri' ] ) elif gst . uri_is_valid ( source ) : uri_protocol = gst . uri_get_protocol ( source ) if gst . uri_protocol_is_supported ( gst . URI_SRC , uri_protocol ) : return source else : raise I... | Check a media source as a valid file or uri and return the proper uri |
245,069 | def sha1sum_file ( filename ) : import hashlib import io sha1 = hashlib . sha1 ( ) chunk_size = sha1 . block_size * io . DEFAULT_BUFFER_SIZE with open ( filename , 'rb' ) as f : for chunk in iter ( lambda : f . read ( chunk_size ) , b'' ) : sha1 . update ( chunk ) return sha1 . hexdigest ( ) | Return the secure hash digest with sha1 algorithm for a given file |
245,070 | def sha1sum_url ( url ) : import hashlib import urllib from contextlib import closing sha1 = hashlib . sha1 ( ) chunk_size = sha1 . block_size * 8192 max_file_size = 10 * 1024 * 1024 total_read = 0 with closing ( urllib . urlopen ( url ) ) as url_obj : for chunk in iter ( lambda : url_obj . read ( chunk_size ) , b'' ) ... | Return the secure hash digest with sha1 algorithm for a given url |
245,071 | def sha1sum_numpy ( np_array ) : import hashlib return hashlib . sha1 ( np_array . view ( np . uint8 ) ) . hexdigest ( ) | Return the secure hash digest with sha1 algorithm for a numpy array |
245,072 | def import_module_with_exceptions ( name , package = None ) : from timeside . core import _WITH_AUBIO , _WITH_YAAFE , _WITH_VAMP if name . count ( '.server.' ) : return try : import_module ( name , package ) except VampImportError : if _WITH_VAMP : raise VampImportError else : return except ImportError as e : if str ( ... | Wrapper around importlib . import_module to import TimeSide subpackage and ignoring ImportError if Aubio Yaafe and Vamp Host are not available |
245,073 | def check_vamp ( ) : "Check Vamp host availability" try : from timeside . plugins . analyzer . externals import vamp_plugin except VampImportError : warnings . warn ( 'Vamp host is not available' , ImportWarning , stacklevel = 2 ) _WITH_VAMP = False else : _WITH_VAMP = True del vamp_plugin return _WITH_VAMP | Check Vamp host availability |
245,074 | def im_watermark ( im , inputtext , font = None , color = None , opacity = .6 , margin = ( 30 , 30 ) ) : if im . mode != "RGBA" : im = im . convert ( "RGBA" ) textlayer = Image . new ( "RGBA" , im . size , ( 0 , 0 , 0 , 0 ) ) textdraw = ImageDraw . Draw ( textlayer ) textsize = textdraw . textsize ( inputtext , font = ... | imprints a PIL image with the indicated text in lower - right corner |
245,075 | def nextpow2 ( value ) : if value >= 1 : return 2 ** np . ceil ( np . log2 ( value ) ) . astype ( int ) elif value > 0 : return 1 elif value == 0 : return 0 else : raise ValueError ( 'Value must be positive' ) | Compute the nearest power of two greater or equal to the input value |
245,076 | def blocksize ( self , input_totalframes ) : blocksize = input_totalframes if self . pad : mod = input_totalframes % self . buffer_size if mod : blocksize += self . buffer_size - mod return blocksize | Return the total number of frames that this adapter will output according to the input_totalframes argument |
245,077 | def append_processor ( self , proc , source_proc = None ) : "Append a new processor to the pipe" if source_proc is None and len ( self . processors ) : source_proc = self . processors [ 0 ] if source_proc and not isinstance ( source_proc , Processor ) : raise TypeError ( 'source_proc must be a Processor or None' ) if n... | Append a new processor to the pipe |
245,078 | def simple_host_process ( argslist ) : vamp_host = 'vamp-simple-host' command = [ vamp_host ] command . extend ( argslist ) stdout = subprocess . check_output ( command , stderr = subprocess . STDOUT ) . splitlines ( ) return stdout | Call vamp - simple - host |
245,079 | def set_scale ( self ) : f_min = float ( self . lower_freq ) f_max = float ( self . higher_freq ) y_min = f_min y_max = f_max for y in range ( self . image_height ) : freq = y_min + y / ( self . image_height - 1.0 ) * ( y_max - y_min ) fft_bin = freq / f_max * ( self . fft_size / 2 + 1 ) if fft_bin < self . fft_size / ... | generate the lookup which translates y - coordinate to fft - bin |
245,080 | def dict_from_hdf5 ( dict_like , h5group ) : for name , value in h5group . attrs . items ( ) : dict_like [ name ] = value | Load a dictionnary - like object from a h5 file group |
245,081 | def get_frames ( self ) : "Define an iterator that will return frames at the given blocksize" nb_frames = self . input_totalframes // self . output_blocksize if self . input_totalframes % self . output_blocksize == 0 : nb_frames -= 1 for index in xrange ( 0 , nb_frames * self . output_blocksize , self . output_blocksiz... | Define an iterator that will return frames at the given blocksize |
245,082 | def implementations ( interface , recurse = True , abstract = False ) : result = [ ] find_implementations ( interface , recurse , abstract , result ) return result | Returns the components implementing interface and if recurse any of the descendants of interface . If abstract is True also return the abstract implementations . |
245,083 | def find_implementations ( interface , recurse , abstract , result ) : for item in MetaComponent . implementations : if ( item [ 'interface' ] == interface and ( abstract or not item [ 'abstract' ] ) ) : extend_unique ( result , [ item [ 'class' ] ] ) if recurse : subinterfaces = interface . __subclasses__ ( ) if subin... | Find implementations of an interface or of one of its descendants and extend result with the classes found . |
245,084 | def draw_peaks ( self , x , peaks , line_color ) : y1 = self . image_height * 0.5 - peaks [ 0 ] * ( self . image_height - 4 ) * 0.5 y2 = self . image_height * 0.5 - peaks [ 1 ] * ( self . image_height - 4 ) * 0.5 if self . previous_y : self . draw . line ( [ self . previous_x , self . previous_y , x , y1 , x , y2 ] , l... | Draw 2 peaks at x |
245,085 | def draw_peaks_inverted ( self , x , peaks , line_color ) : y1 = self . image_height * 0.5 - peaks [ 0 ] * ( self . image_height - 4 ) * 0.5 y2 = self . image_height * 0.5 - peaks [ 1 ] * ( self . image_height - 4 ) * 0.5 if self . previous_y and x < self . image_width - 1 : if y1 < y2 : self . draw . line ( ( x , 0 , ... | Draw 2 inverted peaks at x |
245,086 | def draw_anti_aliased_pixels ( self , x , y1 , y2 , color ) : y_max = max ( y1 , y2 ) y_max_int = int ( y_max ) alpha = y_max - y_max_int if alpha > 0.0 and alpha < 1.0 and y_max_int + 1 < self . image_height : current_pix = self . pixel [ int ( x ) , y_max_int + 1 ] r = int ( ( 1 - alpha ) * current_pix [ 0 ] + alpha ... | vertical anti - aliasing at y1 and y2 |
245,087 | def post_process ( self ) : self . image . putdata ( self . pixels ) self . image = self . image . transpose ( Image . ROTATE_90 ) | Apply last 2D transforms |
245,088 | def write_metadata ( self ) : import mutagen from mutagen import id3 id3 = id3 . ID3 ( self . filename ) for tag in self . metadata . keys ( ) : value = self . metadata [ tag ] frame = mutagen . id3 . Frames [ tag ] ( 3 , value ) try : id3 . add ( frame ) except : raise IOError ( 'EncoderError: cannot tag "' + tag + '"... | Write all ID3v2 . 4 tags to file from self . metadata |
245,089 | def main ( args = sys . argv [ 1 : ] ) : opt = docopt ( main . __doc__ . strip ( ) , args , options_first = True ) config_logging ( opt [ '--verbose' ] ) if opt [ 'check' ] : check_backends ( opt [ '--title' ] ) elif opt [ 'extract' ] : handler = fulltext . get if opt [ '--file' ] : handler = _handle_open for path in o... | Extract text from a file . |
245,090 | def is_binary ( f ) : if getattr ( f , "encoding" , None ) : return False if not PY3 : return True try : if 'b' in getattr ( f , 'mode' , '' ) : return True except TypeError : import gzip if isinstance ( f , gzip . GzipFile ) : return True raise try : f . seek ( 0 , os . SEEK_CUR ) except ( AttributeError , IOError ) :... | Return True if binary mode . |
245,091 | def handle_path ( backend_inst , path , ** kwargs ) : if callable ( getattr ( backend_inst , 'handle_path' , None ) ) : LOGGER . debug ( "using handle_path" ) return backend_inst . handle_path ( path ) elif callable ( getattr ( backend_inst , 'handle_fobj' , None ) ) : LOGGER . debug ( "using handle_fobj" ) with open (... | Handle a path . |
245,092 | def handle_fobj ( backend , f , ** kwargs ) : if not is_binary ( f ) : raise AssertionError ( 'File must be opened in binary mode.' ) if callable ( getattr ( backend , 'handle_fobj' , None ) ) : LOGGER . debug ( "using handle_fobj" ) return backend . handle_fobj ( f ) elif callable ( getattr ( backend , 'handle_path' ,... | Handle a file - like object . |
245,093 | def backend_from_mime ( mime ) : try : mod_name = MIMETYPE_TO_BACKENDS [ mime ] except KeyError : msg = "No handler for %r, defaulting to %r" % ( mime , DEFAULT_MIME ) if 'FULLTEXT_TESTING' in os . environ : warn ( msg ) else : LOGGER . debug ( msg ) mod_name = MIMETYPE_TO_BACKENDS [ DEFAULT_MIME ] mod = import_mod ( m... | Determine backend module object from a mime string . |
245,094 | def backend_from_fname ( name ) : ext = splitext ( name ) [ 1 ] try : mime = EXTS_TO_MIMETYPES [ ext ] except KeyError : try : f = open ( name , 'rb' ) except IOError as e : if e . errno != errno . ENOENT : raise msg = "No handler for %r, defaulting to %r" % ( ext , DEFAULT_MIME ) if 'FULLTEXT_TESTING' in os . environ ... | Determine backend module object from a file name . |
245,095 | def backend_from_fobj ( f ) : if magic is None : warn ( "magic lib is not installed; assuming mime type %r" % ( DEFAULT_MIME ) ) return backend_from_mime ( DEFAULT_MIME ) else : offset = f . tell ( ) try : f . seek ( 0 ) chunk = f . read ( MAGIC_BUFFER_SIZE ) mime = magic . from_buffer ( chunk , mime = True ) return ba... | Determine backend module object from a file object . |
245,096 | def backend_inst_from_mod ( mod , encoding , encoding_errors , kwargs ) : kw = dict ( encoding = encoding , encoding_errors = encoding_errors , kwargs = kwargs ) try : klass = getattr ( mod , "Backend" ) except AttributeError : raise AttributeError ( "%r mod does not define any backend class" % mod ) inst = klass ( ** ... | Given a mod and a set of opts return an instantiated Backend class . |
245,097 | def get ( path_or_file , default = SENTINAL , mime = None , name = None , backend = None , encoding = None , encoding_errors = None , kwargs = None , _wtitle = False ) : try : text , title = _get ( path_or_file , default = default , mime = mime , name = name , backend = backend , kwargs = kwargs , encoding = encoding ,... | Get document full text . |
245,098 | def hilite ( s , ok = True , bold = False ) : if not term_supports_colors ( ) : return s attr = [ ] if ok is None : pass elif ok : attr . append ( '32' ) else : attr . append ( '31' ) if bold : attr . append ( '1' ) return '\x1b[%sm%s\x1b[0m' % ( ';' . join ( attr ) , s ) | Return an highlighted version of string . |
245,099 | def fobj_to_tempfile ( f , suffix = '' ) : with tempfile . NamedTemporaryFile ( dir = TEMPDIR , suffix = suffix , delete = False ) as t : shutil . copyfileobj ( f , t ) try : yield t . name finally : os . remove ( t . name ) | Context manager which copies a file object to disk and return its name . When done the file is deleted . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.