idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
10,700 | def binarize_signal ( signal , treshold = "auto" , cut = "higher" ) : if treshold == "auto" : treshold = ( np . max ( np . array ( signal ) ) - np . min ( np . array ( signal ) ) ) / 2 signal = list ( signal ) binary_signal = [ ] for i in range ( len ( signal ) ) : if cut == "higher" : if signal [ i ] > treshold : binary_signal . append ( 1 ) else : binary_signal . append ( 0 ) else : if signal [ i ] < treshold : binary_signal . append ( 1 ) else : binary_signal . append ( 0 ) return ( binary_signal ) | Binarize a channel based on a continuous channel . |
10,701 | def localize_events ( events_channel , treshold = "auto" , cut = "higher" , time_index = None ) : events_channel = binarize_signal ( events_channel , treshold = treshold , cut = cut ) events = { "onsets" : [ ] , "durations" : [ ] } if time_index is not None : events [ "onsets_time" ] = [ ] index = 0 for key , g in ( groupby ( events_channel ) ) : duration = len ( list ( g ) ) if key == 1 : events [ "onsets" ] . append ( index ) events [ "durations" ] . append ( duration ) if time_index is not None : events [ "onsets_time" ] . append ( time_index [ index ] ) index += duration return ( events ) | Find the onsets of all events based on a continuous signal . |
10,702 | def find_events ( events_channel , treshold = "auto" , cut = "higher" , time_index = None , number = "all" , after = 0 , before = None , min_duration = 1 ) : events = localize_events ( events_channel , treshold = treshold , cut = cut , time_index = time_index ) if len ( events [ "onsets" ] ) == 0 : print ( "NeuroKit warning: find_events(): No events found. Check your events_channel or adjust trehsold." ) return ( ) toremove = [ ] for event in range ( len ( events [ "onsets" ] ) ) : if events [ "durations" ] [ event ] < min_duration : toremove . append ( False ) else : toremove . append ( True ) events [ "onsets" ] = np . array ( events [ "onsets" ] ) [ np . array ( toremove ) ] events [ "durations" ] = np . array ( events [ "durations" ] ) [ np . array ( toremove ) ] if time_index is not None : events [ "onsets_time" ] = np . array ( events [ "onsets_time" ] ) [ np . array ( toremove ) ] if isinstance ( number , int ) : after_times = [ ] after_onsets = [ ] after_length = [ ] before_times = [ ] before_onsets = [ ] before_length = [ ] if after != None : if events [ "onsets_time" ] == [ ] : events [ "onsets_time" ] = np . array ( events [ "onsets" ] ) else : events [ "onsets_time" ] = np . array ( events [ "onsets_time" ] ) after_onsets = list ( np . array ( events [ "onsets" ] ) [ events [ "onsets_time" ] > after ] ) [ : number ] after_times = list ( np . array ( events [ "onsets_time" ] ) [ events [ "onsets_time" ] > after ] ) [ : number ] after_length = list ( np . array ( events [ "durations" ] ) [ events [ "onsets_time" ] > after ] ) [ : number ] if before != None : if events [ "onsets_time" ] == [ ] : events [ "onsets_time" ] = np . array ( events [ "onsets" ] ) else : events [ "onsets_time" ] = np . array ( events [ "onsets_time" ] ) before_onsets = list ( np . array ( events [ "onsets" ] ) [ events [ "onsets_time" ] < before ] ) [ : number ] before_times = list ( np . array ( events [ "onsets_time" ] ) [ events [ "onsets_time" ] < before ] ) [ : number ] before_length = list ( np . array ( events [ "durations" ] ) [ events [ "onsets_time" ] < before ] ) [ : number ] events [ "onsets" ] = before_onsets + after_onsets events [ "onsets_time" ] = before_times + after_times events [ "durations" ] = before_length + after_length return ( events ) | Find and select events based on a continuous signal . |
10,703 | def plot_events_in_signal ( signal , events_onsets , color = "red" , marker = None ) : df = pd . DataFrame ( signal ) ax = df . plot ( ) def plotOnSignal ( x , color , marker = None ) : if ( marker is None ) : plt . axvline ( x = event , color = color ) else : plt . plot ( x , signal [ x ] , marker , color = color ) events_onsets = np . array ( events_onsets ) try : len ( events_onsets [ 0 ] ) for index , dim in enumerate ( events_onsets ) : for event in dim : plotOnSignal ( x = event , color = color [ index ] if isinstance ( color , list ) else color , marker = marker [ index ] if isinstance ( marker , list ) else marker ) except TypeError : for event in events_onsets : plotOnSignal ( x = event , color = color [ 0 ] if isinstance ( color , list ) else color , marker = marker [ 0 ] if isinstance ( marker , list ) else marker ) return ax | Plot events in signal . |
10,704 | def eda_scr ( signal , sampling_rate = 1000 , treshold = 0.1 , method = "fast" ) : if method == "slow" : gradient = np . gradient ( signal ) size = int ( 0.1 * sampling_rate ) smooth , _ = biosppy . tools . smoother ( signal = gradient , kernel = 'bartlett' , size = size , mirror = True ) zeros , = biosppy . tools . zero_cross ( signal = smooth , detrend = True ) onsets = [ ] peaks = [ ] for i in zeros : if smooth [ i + 1 ] > smooth [ i - 1 ] : onsets . append ( i ) else : peaks . append ( i ) peaks = np . array ( peaks ) onsets = np . array ( onsets ) else : peaks , _ = biosppy . tools . find_extrema ( signal = signal , mode = 'max' ) onsets , _ = biosppy . tools . find_extrema ( signal = signal , mode = 'min' ) peaks = peaks [ peaks > onsets [ 0 ] ] onsets = onsets [ onsets < peaks [ - 1 ] ] risingtimes = peaks - onsets risingtimes = risingtimes / sampling_rate * 1000 peaks = peaks [ risingtimes > 100 ] onsets = onsets [ risingtimes > 100 ] amplitudes = signal [ peaks ] - signal [ onsets ] mask = amplitudes > np . std ( signal ) * treshold peaks = peaks [ mask ] onsets = onsets [ mask ] amplitudes = amplitudes [ mask ] recoveries = [ ] for x , peak in enumerate ( peaks ) : try : window = signal [ peak : onsets [ x + 1 ] ] except IndexError : window = signal [ peak : ] recovery_amp = signal [ peak ] - amplitudes [ x ] / 2 try : smaller = find_closest_in_list ( recovery_amp , window , "smaller" ) recovery_pos = peak + list ( window ) . index ( smaller ) recoveries . append ( recovery_pos ) except ValueError : recoveries . append ( np . nan ) recoveries = np . array ( recoveries ) return ( onsets , peaks , amplitudes , recoveries ) | Skin - Conductance Responses extraction algorithm . |
10,705 | def add_response ( self , response , value ) : if value != "stop" : self . X = pd . concat ( [ self . X , pd . DataFrame ( { "Signal" : [ value ] } ) ] ) self . y = np . array ( list ( self . y ) + [ response ] ) if len ( set ( list ( self . y ) ) ) > 1 : self . model = self . fit_model ( self . X , self . y ) | Add response to staircase . |
10,706 | def create_epochs ( data , events_onsets , sampling_rate = 1000 , duration = 1 , onset = 0 , index = None ) : if isinstance ( duration , list ) or isinstance ( duration , np . ndarray ) : duration = np . array ( duration ) else : duration = np . array ( [ duration ] * len ( events_onsets ) ) if isinstance ( onset , list ) or isinstance ( onset , np . ndarray ) : onset = np . array ( onset ) else : onset = np . array ( [ onset ] * len ( events_onsets ) ) if isinstance ( data , list ) or isinstance ( data , np . ndarray ) or isinstance ( data , pd . Series ) : data = pd . DataFrame ( { "Signal" : list ( data ) } ) duration_in_s = duration . copy ( ) onset_in_s = onset . copy ( ) duration = duration * sampling_rate onset = onset * sampling_rate if index is None : index = list ( range ( len ( events_onsets ) ) ) else : if len ( list ( set ( index ) ) ) != len ( index ) : print ( "NeuroKit Warning: create_epochs(): events_names does not contain uniques names, replacing them by numbers." ) index = list ( range ( len ( events_onsets ) ) ) else : index = list ( index ) epochs = { } for event , event_onset in enumerate ( events_onsets ) : epoch_onset = int ( event_onset + onset [ event ] ) epoch_end = int ( event_onset + duration [ event ] + 1 ) epoch = data [ epoch_onset : epoch_end ] . copy ( ) epoch . index = np . linspace ( start = onset_in_s [ event ] , stop = duration_in_s [ event ] , num = len ( epoch ) , endpoint = True ) relative_time = np . linspace ( start = onset [ event ] , stop = duration [ event ] , num = len ( epoch ) , endpoint = True ) . astype ( int ) . tolist ( ) absolute_time = np . linspace ( start = epoch_onset , stop = epoch_end , num = len ( epoch ) , endpoint = True ) . astype ( int ) . tolist ( ) epoch [ "Epoch_Relative_Time" ] = relative_time epoch [ "Epoch_Absolute_Time" ] = absolute_time epochs [ index [ event ] ] = epoch return ( epochs ) | Epoching a dataframe . |
10,707 | def interpolate ( values , value_times , sampling_rate = 1000 ) : initial_index = value_times [ 0 ] value_times = np . array ( value_times ) - initial_index spline = scipy . interpolate . splrep ( x = value_times , y = values , k = 3 , s = 0 ) x = np . arange ( 0 , value_times [ - 1 ] , 1 ) signal = scipy . interpolate . splev ( x = x , tck = spline , der = 0 ) signal = pd . Series ( signal ) signal . index = np . array ( np . arange ( initial_index , initial_index + len ( signal ) , 1 ) ) return ( signal ) | 3rd order spline interpolation . |
10,708 | def find_peaks ( signal ) : derivative = np . gradient ( signal , 2 ) peaks = np . where ( np . diff ( np . sign ( derivative ) ) ) [ 0 ] return ( peaks ) | Locate peaks based on derivative . |
10,709 | def eeg_name_frequencies ( freqs ) : freqs = list ( freqs ) freqs_names = [ ] for freq in freqs : if freq < 1 : freqs_names . append ( "UltraLow" ) elif freq <= 3 : freqs_names . append ( "Delta" ) elif freq <= 7 : freqs_names . append ( "Theta" ) elif freq <= 9 : freqs_names . append ( "Alpha1/Mu" ) elif freq <= 12 : freqs_names . append ( "Alpha2/Mu" ) elif freq <= 13 : freqs_names . append ( "Beta1/Mu" ) elif freq <= 17 : freqs_names . append ( "Beta1" ) elif freq <= 30 : freqs_names . append ( "Beta2" ) elif freq <= 40 : freqs_names . append ( "Gamma1" ) elif freq <= 50 : freqs_names . append ( "Gamma2" ) else : freqs_names . append ( "UltraHigh" ) return ( freqs_names ) | Name frequencies according to standart classifications . |
10,710 | def normal_range ( mean , sd , treshold = 1.28 ) : bottom = mean - sd * treshold top = mean + sd * treshold return ( bottom , top ) | Returns a bottom and a top limit on a normal distribution portion based on a treshold . |
10,711 | def find_following_duplicates ( array ) : array = array [ : ] uniques = [ ] for i in range ( len ( array ) ) : if i == 0 : uniques . append ( True ) else : if array [ i ] == array [ i - 1 ] : uniques . append ( False ) else : uniques . append ( True ) return ( uniques ) | Find the duplicates that are following themselves . |
10,712 | def find_closest_in_list ( number , array , direction = "both" , strictly = False ) : if direction == "both" : closest = min ( array , key = lambda x : abs ( x - number ) ) if direction == "smaller" : if strictly is True : closest = max ( x for x in array if x < number ) else : closest = max ( x for x in array if x <= number ) if direction == "greater" : if strictly is True : closest = min ( filter ( lambda x : x > number , array ) ) else : closest = min ( filter ( lambda x : x >= number , array ) ) return ( closest ) | Find the closest number in the array from x . |
10,713 | def emg_process ( emg , sampling_rate = 1000 , emg_names = None , envelope_freqs = [ 10 , 400 ] , envelope_lfreq = 4 , activation_treshold = "default" , activation_n_above = 0.25 , activation_n_below = 1 ) : if emg_names is None : if isinstance ( emg , pd . DataFrame ) : emg_names = emg . columns . values emg = np . array ( emg ) if len ( np . shape ( emg ) ) == 1 : emg = np . array ( pd . DataFrame ( emg ) ) if emg_names is None : if np . shape ( emg ) [ 1 ] > 1 : emg_names = [ ] for index in range ( np . shape ( emg ) [ 1 ] ) : emg_names . append ( "EMG_" + str ( index ) ) else : emg_names = [ "EMG" ] processed_emg = { "df" : pd . DataFrame ( ) } for index , emg_chan in enumerate ( emg . T ) : processed_emg [ "df" ] [ emg_names [ index ] + "_Raw" ] = emg_chan biosppy_emg = dict ( biosppy . emg . emg ( emg_chan , sampling_rate = sampling_rate , show = False ) ) pulse_onsets = np . array ( [ np . nan ] * len ( emg ) ) if len ( biosppy_emg [ 'onsets' ] ) > 0 : pulse_onsets [ biosppy_emg [ 'onsets' ] ] = 1 processed_emg [ "df" ] [ emg_names [ index ] + "_Pulse_Onsets" ] = pulse_onsets processed_emg [ "df" ] [ emg_names [ index ] + "_Filtered" ] = biosppy_emg [ "filtered" ] processed_emg [ emg_names [ index ] ] = { } processed_emg [ emg_names [ index ] ] [ "EMG_Pulse_Onsets" ] = biosppy_emg [ 'onsets' ] envelope = emg_linear_envelope ( biosppy_emg [ "filtered" ] , sampling_rate = sampling_rate , freqs = envelope_freqs , lfreq = envelope_lfreq ) processed_emg [ "df" ] [ emg_names [ index ] + "_Envelope" ] = envelope if activation_treshold == "default" : activation_treshold = 1 * np . std ( envelope ) processed_emg [ "df" ] [ emg_names [ index ] + "_Activation" ] = emg_find_activation ( envelope , sampling_rate = sampling_rate , threshold = 1 * np . std ( envelope ) , n_above = activation_n_above , n_below = activation_n_below ) return ( processed_emg ) | Automated processing of EMG signal . |
10,714 | def emg_linear_envelope ( emg , sampling_rate = 1000 , freqs = [ 10 , 400 ] , lfreq = 4 ) : r emg = emg_tkeo ( emg ) if np . size ( freqs ) == 2 : b , a = scipy . signal . butter ( 2 , np . array ( freqs ) / ( sampling_rate / 2. ) , btype = 'bandpass' ) emg = scipy . signal . filtfilt ( b , a , emg ) if np . size ( lfreq ) == 1 : envelope = abs ( emg ) b , a = scipy . signal . butter ( 2 , np . array ( lfreq ) / ( sampling_rate / 2. ) , btype = 'low' ) envelope = scipy . signal . filtfilt ( b , a , envelope ) return ( envelope ) | r Calculate the linear envelope of a signal . |
10,715 | def emg_find_activation ( envelope , sampling_rate = 1000 , threshold = 0 , n_above = 0.25 , n_below = 1 ) : n_above = n_above * sampling_rate n_below = n_below * sampling_rate envelope = np . atleast_1d ( envelope ) . astype ( 'float64' ) envelope [ np . isnan ( envelope ) ] = - np . inf inds = np . nonzero ( envelope >= threshold ) [ 0 ] if inds . size : inds = np . vstack ( ( inds [ np . diff ( np . hstack ( ( - np . inf , inds ) ) ) > n_below + 1 ] , inds [ np . diff ( np . hstack ( ( inds , np . inf ) ) ) > n_below + 1 ] ) ) . T inds = inds [ inds [ : , 1 ] - inds [ : , 0 ] >= n_above - 1 , : ] if not inds . size : inds = np . array ( [ ] ) inds = np . array ( inds ) activation = np . array ( [ 0 ] * len ( envelope ) ) for i in inds : activation [ i [ 0 ] : i [ 1 ] ] = 1 return ( activation ) | Detects onset in data based on amplitude threshold . |
10,716 | def ecg_find_peaks ( signal , sampling_rate = 1000 ) : rpeaks , = biosppy . ecg . hamilton_segmenter ( np . array ( signal ) , sampling_rate = sampling_rate ) rpeaks , = biosppy . ecg . correct_rpeaks ( signal = np . array ( signal ) , rpeaks = rpeaks , sampling_rate = sampling_rate , tol = 0.05 ) return ( rpeaks ) | Find R peaks indices on the ECG channel . |
10,717 | def ecg_wave_detector ( ecg , rpeaks ) : q_waves = [ ] p_waves = [ ] q_waves_starts = [ ] s_waves = [ ] t_waves = [ ] t_waves_starts = [ ] t_waves_ends = [ ] for index , rpeak in enumerate ( rpeaks [ : - 3 ] ) : try : epoch_before = np . array ( ecg ) [ int ( rpeaks [ index - 1 ] ) : int ( rpeak ) ] epoch_before = epoch_before [ int ( len ( epoch_before ) / 2 ) : len ( epoch_before ) ] epoch_before = list ( reversed ( epoch_before ) ) q_wave_index = np . min ( find_peaks ( epoch_before ) ) q_wave = rpeak - q_wave_index p_wave_index = q_wave_index + np . argmax ( epoch_before [ q_wave_index : ] ) p_wave = rpeak - p_wave_index inter_pq = epoch_before [ q_wave_index : p_wave_index ] inter_pq_derivative = np . gradient ( inter_pq , 2 ) q_start_index = find_closest_in_list ( len ( inter_pq_derivative ) / 2 , find_peaks ( inter_pq_derivative ) ) q_start = q_wave - q_start_index q_waves . append ( q_wave ) p_waves . append ( p_wave ) q_waves_starts . append ( q_start ) except ValueError : pass except IndexError : pass try : epoch_after = np . array ( ecg ) [ int ( rpeak ) : int ( rpeaks [ index + 1 ] ) ] epoch_after = epoch_after [ 0 : int ( len ( epoch_after ) / 2 ) ] s_wave_index = np . min ( find_peaks ( epoch_after ) ) s_wave = rpeak + s_wave_index t_wave_index = s_wave_index + np . argmax ( epoch_after [ s_wave_index : ] ) t_wave = rpeak + t_wave_index inter_st = epoch_after [ s_wave_index : t_wave_index ] inter_st_derivative = np . gradient ( inter_st , 2 ) t_start_index = find_closest_in_list ( len ( inter_st_derivative ) / 2 , find_peaks ( inter_st_derivative ) ) t_start = s_wave + t_start_index t_end = np . min ( find_peaks ( epoch_after [ t_wave_index : ] ) ) t_end = t_wave + t_end s_waves . append ( s_wave ) t_waves . append ( t_wave ) t_waves_starts . append ( t_start ) t_waves_ends . append ( t_end ) except ValueError : pass except IndexError : pass ecg_waves = { "T_Waves" : t_waves , "P_Waves" : p_waves , "Q_Waves" : q_waves , "S_Waves" : s_waves , "Q_Waves_Onsets" : q_waves_starts , "T_Waves_Onsets" : t_waves_starts , "T_Waves_Ends" : t_waves_ends } return ( ecg_waves ) | Returns the localization of the P Q T waves . This function needs massive help! |
10,718 | def ecg_systole ( ecg , rpeaks , t_waves_ends ) : waves = np . array ( [ "" ] * len ( ecg ) ) waves [ rpeaks ] = "R" waves [ t_waves_ends ] = "T" systole = [ 0 ] current = 0 for index , value in enumerate ( waves [ 1 : ] ) : if waves [ index - 1 ] == "R" : current = 1 if waves [ index - 1 ] == "T" : current = 0 systole . append ( current ) return ( systole ) | Returns the localization of systoles and diastoles . |
10,719 | def plot_eeg_erp_topo ( all_epochs , colors = None ) : all_evokeds = eeg_to_all_evokeds ( all_epochs ) data = { } for participant , epochs in all_evokeds . items ( ) : for cond , epoch in epochs . items ( ) : data [ cond ] = [ ] for participant , epochs in all_evokeds . items ( ) : for cond , epoch in epochs . items ( ) : data [ cond ] . append ( epoch ) if colors is not None : color_list = [ ] else : color_list = None evokeds = [ ] for condition , evoked in data . items ( ) : grand_average = mne . grand_average ( evoked ) grand_average . comment = condition evokeds += [ grand_average ] if colors is not None : color_list . append ( colors [ condition ] ) plot = mne . viz . plot_evoked_topo ( evokeds , background_color = "w" , color = color_list ) return ( plot ) | Plot butterfly plot . |
10,720 | def save_nk_object ( obj , filename = "file" , path = "" , extension = "nk" , compress = False , compatibility = - 1 ) : if compress is True : with gzip . open ( path + filename + "." + extension , 'wb' ) as name : pickle . dump ( obj , name , protocol = compatibility ) else : with open ( path + filename + "." + extension , 'wb' ) as name : pickle . dump ( obj , name , protocol = compatibility ) | Save whatever python object to a pickled file . |
10,721 | def read_nk_object ( filename , path = "" ) : filename = path + filename try : with open ( filename , 'rb' ) as name : file = pickle . load ( name ) except pickle . UnpicklingError : with gzip . open ( filename , 'rb' ) as name : file = pickle . load ( name ) except ModuleNotFoundError : try : file = pd . read_pickle ( filename ) except : pass return ( file ) | Read a pickled file . |
10,722 | def find_creation_date ( path ) : if platform . system ( ) == 'Windows' : return ( os . path . getctime ( path ) ) else : stat = os . stat ( path ) try : return ( stat . st_birthtime ) except AttributeError : print ( "Neuropsydia error: get_creation_date(): We're probably on Linux. No easy way to get creation dates here, so we'll settle for when its content was last modified." ) return ( stat . st_mtime ) | Try to get the date that a file was created falling back to when it was last modified if that s not possible . |
10,723 | def _register ( self , obj ) : session = None while session is None or session in self . sessions : session = random . randint ( 1000000 , 9999999 ) self . sessions [ session ] = obj return session | Creates a random but unique session handle for a session object register it in the sessions dictionary and return the value |
10,724 | def _return_handler ( self , ret_value , func , arguments ) : logger . debug ( '%s%s -> %r' , func . __name__ , _args_to_str ( arguments ) , ret_value , extra = self . _logging_extra ) try : ret_value = StatusCode ( ret_value ) except ValueError : pass self . _last_status = ret_value session = None if func . __name__ not in ( 'viFindNext' , ) : try : session = arguments [ 0 ] except KeyError : raise Exception ( 'Function %r does not seem to be a valid ' 'visa function (len args %d)' % ( func , len ( arguments ) ) ) if func . __name__ in ( 'viOpenDefaultRM' , ) : session = session . _obj . value if isinstance ( session , integer_types ) : self . _last_status_in_session [ session ] = ret_value else : if func . __name__ not in ( 'viClose' , 'viGetAttribute' , 'viSetAttribute' , 'viStatusDesc' ) : raise Exception ( 'Function %r does not seem to be a valid ' 'visa function (type args[0] %r)' % ( func , type ( session ) ) ) if ret_value < 0 : raise errors . VisaIOError ( ret_value ) if ret_value in self . issue_warning_on : if session and ret_value not in self . _ignore_warning_in_session [ session ] : warnings . warn ( errors . VisaIOWarning ( ret_value ) , stacklevel = 2 ) return ret_value | Check return values for errors and warnings . |
10,725 | def clear ( self , session ) : try : sess = self . sessions [ session ] except KeyError : return constants . StatusCode . error_invalid_object return sess . clear ( ) | Clears a device . |
10,726 | def gpib_command ( self , session , command_byte ) : try : return self . sessions [ session ] . gpib_command ( command_byte ) except KeyError : return constants . StatusCode . error_invalid_object | Write GPIB command byte on the bus . |
10,727 | def assert_trigger ( self , session , protocol ) : try : return self . sessions [ session ] . assert_trigger ( protocol ) except KeyError : return constants . StatusCode . error_invalid_object | Asserts software or hardware trigger . |
10,728 | def unlock ( self , session ) : try : sess = self . sessions [ session ] except KeyError : return StatusCode . error_invalid_object return sess . unlock ( ) | Relinquishes a lock for the specified resource . |
10,729 | def find_raw_devices ( vendor = None , product = None , serial_number = None , custom_match = None , ** kwargs ) : def is_usbraw ( dev ) : if custom_match and not custom_match ( dev ) : return False return bool ( find_interfaces ( dev , bInterfaceClass = 0xFF , bInterfaceSubClass = 0xFF ) ) return find_devices ( vendor , product , serial_number , is_usbraw , ** kwargs ) | Find connected USB RAW devices . See usbutil . find_devices for more info . |
10,730 | def write ( self , data ) : begin , end , size = 0 , 0 , len ( data ) bytes_sent = 0 raw_write = super ( USBRawDevice , self ) . write while not end > size : begin = end end = begin + self . RECV_CHUNK bytes_sent += raw_write ( data [ begin : end ] ) return bytes_sent | Send raw bytes to the instrument . |
10,731 | def read ( self , size ) : raw_read = super ( USBRawDevice , self ) . read received = bytearray ( ) while not len ( received ) >= size : resp = raw_read ( self . RECV_CHUNK ) received . extend ( resp ) return bytes ( received ) | Read raw bytes from the instrument . |
10,732 | def _find_listeners ( ) : for i in range ( 31 ) : try : if gpib . listener ( BOARD , i ) and gpib . ask ( BOARD , 1 ) != i : yield i except gpib . GpibError as e : logger . debug ( "GPIB error in _find_listeners(): %s" , repr ( e ) ) | Find GPIB listeners . |
10,733 | def find_devices ( vendor = None , product = None , serial_number = None , custom_match = None , ** kwargs ) : kwargs = kwargs or { } attrs = { } if isinstance ( vendor , str ) : attrs [ 'manufacturer' ] = vendor elif vendor is not None : kwargs [ 'idVendor' ] = vendor if isinstance ( product , str ) : attrs [ 'product' ] = product elif product is not None : kwargs [ 'idProduct' ] = product if serial_number : attrs [ 'serial_number' ] = str ( serial_number ) if attrs : def cm ( dev ) : if custom_match is not None and not custom_match ( dev ) : return False for attr , pattern in attrs . items ( ) : if not fnmatch ( getattr ( dev , attr ) . lower ( ) , pattern . lower ( ) ) : return False return True else : cm = custom_match return usb . core . find ( find_all = True , custom_match = cm , ** kwargs ) | Find connected USB devices matching certain keywords . |
10,734 | def get_referenced_object ( prev_obj , obj , dot_separated_name , desired_type = None ) : from textx . scoping import Postponed assert prev_obj or not type ( obj ) is list names = dot_separated_name . split ( "." ) match = re . match ( r'parent\((\w+)\)' , names [ 0 ] ) if match : next_obj = obj desired_parent_typename = match . group ( 1 ) next_obj = get_recursive_parent_with_typename ( next_obj , desired_parent_typename ) if next_obj : return get_referenced_object ( None , next_obj , "." . join ( names [ 1 : ] ) , desired_type ) else : return None elif type ( obj ) is list : next_obj = None for res in obj : if hasattr ( res , "name" ) and res . name == names [ 0 ] : if desired_type is None or textx_isinstance ( res , desired_type ) : next_obj = res else : raise TypeError ( "{} has type {} instead of {}." . format ( names [ 0 ] , type ( res ) . __name__ , desired_type . __name__ ) ) if not next_obj : if needs_to_be_resolved ( prev_obj , names [ 0 ] ) : return Postponed ( ) else : return None elif type ( obj ) is Postponed : return Postponed ( ) else : next_obj = getattr ( obj , names [ 0 ] ) if not next_obj : if needs_to_be_resolved ( obj , names [ 0 ] ) : return Postponed ( ) else : return None if len ( names ) > 1 : return get_referenced_object ( obj , next_obj , "." . join ( names [ 1 : ] ) , desired_type ) if type ( next_obj ) is list and needs_to_be_resolved ( obj , names [ 0 ] ) : return Postponed ( ) return next_obj | get objects based on a path |
10,735 | def get_referenced_object_as_list ( prev_obj , obj , dot_separated_name , desired_type = None ) : res = get_referenced_object ( prev_obj , obj , dot_separated_name , desired_type ) if res is None : return [ ] elif type ( res ) is list : return res else : return [ res ] | Same as get_referenced_object but always returns a list . |
10,736 | def load_model ( self , the_metamodel , filename , is_main_model , encoding = 'utf-8' , add_to_local_models = True ) : if not self . local_models . has_model ( filename ) : if self . all_models . has_model ( filename ) : new_model = self . all_models . filename_to_model [ filename ] else : new_model = the_metamodel . internal_model_from_file ( filename , pre_ref_resolution_callback = lambda other_model : self . pre_ref_resolution_callback ( other_model ) , is_main_model = is_main_model , encoding = encoding ) self . all_models . filename_to_model [ filename ] = new_model if add_to_local_models : self . local_models . filename_to_model [ filename ] = new_model assert self . all_models . has_model ( filename ) return self . all_models . filename_to_model [ filename ] | load a single model |
10,737 | def check ( ctx , meta_model_file , model_file , ignore_case ) : debug = ctx . obj [ 'debug' ] check_model ( meta_model_file , model_file , debug , ignore_case ) | Check validity of meta - model and optionally model . |
10,738 | def get_entity_mm ( ) : type_builtins = { 'integer' : SimpleType ( None , 'integer' ) , 'string' : SimpleType ( None , 'string' ) } entity_mm = metamodel_from_file ( join ( this_folder , 'entity.tx' ) , classes = [ SimpleType ] , builtins = type_builtins ) return entity_mm | Builds and returns a meta - model for Entity language . |
10,739 | def sm_to_dot ( model ) : dot_str = HEADER first = True for state in model . states : dot_str += '{}[label="{{{}{}|{}}}"]\n' . format ( id ( state ) , r"-\> " if first else "" , state . name , "\\n" . join ( action . name for action in state . actions ) ) first = False for transition in state . transitions : dot_str += '{} -> {} [label="{}"]\n' . format ( id ( state ) , id ( transition . to_state ) , transition . event . name ) if model . resetEvents : dot_str += 'reset_events [label="{{Reset Events|{}}}", style=""]\n' . format ( "\\n" . join ( event . name for event in model . resetEvents ) ) dot_str += '\n}\n' return dot_str | Transforms given state machine model to dot str . |
10,740 | def get_language ( language_name ) : langs = list ( pkg_resources . iter_entry_points ( group = LANG_EP , name = language_name ) ) if not langs : raise TextXError ( 'Language "{}" is not registered.' . format ( language_name ) ) if len ( langs ) > 1 : raise TextXError ( 'Language "{}" registered multiple times:\n{}' . format ( language_name , "\n" . join ( [ l . dist for l in langs ] ) ) ) return langs [ 0 ] . load ( ) ( ) | Returns a callable that instantiates meta - model for the given language . |
10,741 | def get_model ( obj ) : p = obj while hasattr ( p , 'parent' ) : p = p . parent return p | Finds model root element for the given object . |
10,742 | def get_parent_of_type ( typ , obj ) : if type ( typ ) is not text : typ = typ . __name__ while hasattr ( obj , 'parent' ) : obj = obj . parent if obj . __class__ . __name__ == typ : return obj | Finds first object up the parent chain of the given type . If no parent of the given type exists None is returned . |
10,743 | def get_model_parser ( top_rule , comments_model , ** kwargs ) : class TextXModelParser ( Parser ) : def __init__ ( self , * args , ** kwargs ) : super ( TextXModelParser , self ) . __init__ ( * args , ** kwargs ) self . parser_model = Sequence ( nodes = [ top_rule , EOF ( ) ] , rule_name = 'Model' , root = True ) self . comments_model = comments_model self . _inst_stack = [ ] self . _instances = { } self . _crossrefs = [ ] def clone ( self ) : import copy the_clone = copy . copy ( self ) the_clone . _inst_stack = [ ] the_clone . _instances = { } the_clone . _crossrefs = [ ] the_clone . comments = [ ] the_clone . comment_positions = { } the_clone . sem_actions = { } return the_clone def _parse ( self ) : try : return self . parser_model . parse ( self ) except NoMatch as e : line , col = e . parser . pos_to_linecol ( e . position ) raise TextXSyntaxError ( message = text ( e ) , line = line , col = col , expected_rules = e . rules ) def get_model_from_file ( self , file_name , encoding , debug , pre_ref_resolution_callback = None , is_main_model = True ) : with codecs . open ( file_name , 'r' , encoding ) as f : model_str = f . read ( ) model = self . get_model_from_str ( model_str , file_name = file_name , debug = debug , pre_ref_resolution_callback = pre_ref_resolution_callback , is_main_model = is_main_model , encoding = encoding ) return model def get_model_from_str ( self , model_str , file_name = None , debug = None , pre_ref_resolution_callback = None , is_main_model = True , encoding = 'utf-8' ) : old_debug_state = self . debug try : if debug is not None : self . debug = debug if self . debug : self . dprint ( "*** PARSING MODEL ***" ) self . parse ( model_str , file_name = file_name ) model = parse_tree_to_objgraph ( self , self . parse_tree [ 0 ] , file_name = file_name , pre_ref_resolution_callback = pre_ref_resolution_callback , is_main_model = is_main_model , encoding = encoding ) finally : if debug is not None : self . debug = old_debug_state try : model . _tx_metamodel = self . metamodel except AttributeError : pass return model return TextXModelParser ( ** kwargs ) | Creates model parser for the given language . |
10,744 | def resolve_one_step ( self ) : metamodel = self . parser . metamodel current_crossrefs = self . parser . _crossrefs new_crossrefs = [ ] self . delayed_crossrefs = [ ] resolved_crossref_count = 0 default_scope = DefaultScopeProvider ( ) for obj , attr , crossref in current_crossrefs : if ( get_model ( obj ) == self . model ) : attr_value = getattr ( obj , attr . name ) attr_refs = [ obj . __class__ . __name__ + "." + attr . name , "*." + attr . name , obj . __class__ . __name__ + ".*" , "*.*" ] for attr_ref in attr_refs : if attr_ref in metamodel . scope_providers : if self . parser . debug : self . parser . dprint ( " FOUND {}" . format ( attr_ref ) ) resolved = metamodel . scope_providers [ attr_ref ] ( obj , attr , crossref ) break else : resolved = default_scope ( obj , attr , crossref ) if resolved and not type ( resolved ) is Postponed : if metamodel . textx_tools_support : self . pos_crossref_list . append ( RefRulePosition ( name = crossref . obj_name , ref_pos_start = crossref . position , ref_pos_end = crossref . position + len ( resolved . name ) , def_pos_start = resolved . _tx_position , def_pos_end = resolved . _tx_position_end ) ) if not resolved : if metamodel . builtins : if crossref . obj_name in metamodel . builtins : resolved = metamodel . builtins [ crossref . obj_name ] if not resolved : line , col = self . parser . pos_to_linecol ( crossref . position ) raise TextXSemanticError ( message = 'Unknown object "{}" of class "{}"' . format ( crossref . obj_name , crossref . cls . __name__ ) , line = line , col = col , err_type = UNKNOWN_OBJ_ERROR , expected_obj_cls = crossref . cls , filename = self . model . _tx_filename ) if type ( resolved ) is Postponed : self . delayed_crossrefs . append ( ( obj , attr , crossref ) ) new_crossrefs . append ( ( obj , attr , crossref ) ) else : resolved_crossref_count += 1 if attr . mult in [ MULT_ONEORMORE , MULT_ZEROORMORE ] : attr_value . append ( resolved ) else : setattr ( obj , attr . name , resolved ) else : new_crossrefs . append ( ( obj , attr , crossref ) ) self . parser . _crossrefs = new_crossrefs return ( resolved_crossref_count , self . delayed_crossrefs ) | Resolves model references . |
10,745 | def python_type ( textx_type_name ) : return { 'ID' : text , 'BOOL' : bool , 'INT' : int , 'FLOAT' : float , 'STRICTFLOAT' : float , 'STRING' : text , 'NUMBER' : float , 'BASETYPE' : text , } . get ( textx_type_name , textx_type_name ) | Return Python type from the name of base textx type . |
10,746 | def language_from_str ( language_def , metamodel ) : if type ( language_def ) is not text : raise TextXError ( "textX accepts only unicode strings." ) if metamodel . debug : metamodel . dprint ( "*** PARSING LANGUAGE DEFINITION ***" ) if metamodel . debug in textX_parsers : parser = textX_parsers [ metamodel . debug ] else : parser = ParserPython ( textx_model , comment_def = comment , ignore_case = False , reduce_tree = False , memoization = metamodel . memoization , debug = metamodel . debug , file = metamodel . file ) textX_parsers [ metamodel . debug ] = parser try : parse_tree = parser . parse ( language_def ) except NoMatch as e : line , col = parser . pos_to_linecol ( e . position ) raise TextXSyntaxError ( text ( e ) , line , col ) lang_parser = visit_parse_tree ( parse_tree , TextXVisitor ( parser , metamodel ) ) metamodel . validate ( ) lang_parser . metamodel = metamodel metamodel . _parser_blueprint = lang_parser if metamodel . debug : PMDOTExporter ( ) . exportFile ( lang_parser . parser_model , "{}_parser_model.dot" . format ( metamodel . rootcls . __name__ ) ) return lang_parser | Constructs parser and initializes metamodel from language description given in textX language . |
10,747 | def second_textx_model ( self , model_parser ) : if self . grammar_parser . debug : self . grammar_parser . dprint ( "RESOLVING MODEL PARSER: second_pass" ) self . _resolve_rule_refs ( self . grammar_parser , model_parser ) self . _determine_rule_types ( model_parser . metamodel ) self . _resolve_cls_refs ( self . grammar_parser , model_parser ) return model_parser | Cross reference resolving for parser model . |
10,748 | def _resolve_rule_refs ( self , grammar_parser , model_parser ) : def _resolve_rule ( rule ) : if not isinstance ( rule , RuleCrossRef ) and rule in resolved_rules : return rule resolved_rules . add ( rule ) if grammar_parser . debug : grammar_parser . dprint ( "Resolving rule: {}" . format ( rule ) ) if type ( rule ) is RuleCrossRef : rule_name = rule . rule_name suppress = rule . suppress if rule_name in model_parser . metamodel : rule = model_parser . metamodel [ rule_name ] . _tx_peg_rule if type ( rule ) is RuleCrossRef : rule = _resolve_rule ( rule ) model_parser . metamodel [ rule_name ] . _tx_peg_rule = rule if suppress : _tx_class = rule . _tx_class rule = Sequence ( nodes = [ rule ] , rule_name = rule_name , suppress = suppress ) rule . _tx_class = _tx_class else : line , col = grammar_parser . pos_to_linecol ( rule . position ) raise TextXSemanticError ( 'Unexisting rule "{}" at position {}.' . format ( rule . rule_name , ( line , col ) ) , line , col ) assert isinstance ( rule , ParsingExpression ) , "{}:{}" . format ( type ( rule ) , text ( rule ) ) for idx , child in enumerate ( rule . nodes ) : if child not in resolved_rules : child = _resolve_rule ( child ) rule . nodes [ idx ] = child return rule for i in range ( 2 ) : if grammar_parser . debug : grammar_parser . dprint ( "RESOLVING RULE CROSS-REFS - PASS {}" . format ( i + 1 ) ) resolved_rules = set ( ) _resolve_rule ( model_parser . parser_model ) for cls in model_parser . metamodel : cls . _tx_peg_rule = _resolve_rule ( cls . _tx_peg_rule ) | Resolves parser ParsingExpression crossrefs . |
10,749 | def match_abstract_str ( cls ) : def r ( s ) : if s . root : if s in visited or s . rule_name in ALL_TYPE_NAMES or ( hasattr ( s , '_tx_class' ) and s . _tx_class . _tx_type is not RULE_MATCH ) : return s . rule_name visited . add ( s ) if isinstance ( s , Match ) : result = text ( s ) elif isinstance ( s , OrderedChoice ) : result = "|" . join ( [ r ( x ) for x in s . nodes ] ) elif isinstance ( s , Sequence ) : result = " " . join ( [ r ( x ) for x in s . nodes ] ) elif isinstance ( s , ZeroOrMore ) : result = "({})*" . format ( r ( s . nodes [ 0 ] ) ) elif isinstance ( s , OneOrMore ) : result = "({})+" . format ( r ( s . nodes [ 0 ] ) ) elif isinstance ( s , Optional ) : result = "{}?" . format ( r ( s . nodes [ 0 ] ) ) elif isinstance ( s , SyntaxPredicate ) : result = "" return "{}{}" . format ( result , "-" if s . suppress else "" ) mstr = "" if cls . __name__ not in ALL_TYPE_NAMES and not ( cls . _tx_type is RULE_ABSTRACT and cls . __name__ != cls . _tx_peg_rule . rule_name ) : e = cls . _tx_peg_rule visited = set ( ) if not isinstance ( e , Match ) : visited . add ( e ) if isinstance ( e , OrderedChoice ) : mstr = "|" . join ( [ r ( x ) for x in e . nodes if x . rule_name in BASE_TYPE_NAMES or not x . root ] ) elif isinstance ( e , Sequence ) : mstr = " " . join ( [ r ( x ) for x in e . nodes ] ) else : mstr = r ( e ) mstr = dot_escape ( mstr ) return mstr | For a given abstract or match rule meta - class returns a nice string representation for the body . |
10,750 | def metamodel_from_str ( lang_desc , metamodel = None , ** kwargs ) : if not metamodel : metamodel = TextXMetaModel ( ** kwargs ) language_from_str ( lang_desc , metamodel ) return metamodel | Creates a new metamodel from the textX description given as a string . |
10,751 | def metamodel_from_file ( file_name , ** kwargs ) : with codecs . open ( file_name , 'r' , 'utf-8' ) as f : lang_desc = f . read ( ) metamodel = metamodel_from_str ( lang_desc = lang_desc , file_name = file_name , ** kwargs ) return metamodel | Creates new metamodel from the given file . |
10,752 | def _init_class ( self , cls , peg_rule , position , position_end = None , inherits = None , root = False , rule_type = RULE_MATCH ) : cls . _tx_metamodel = self cls . _tx_attrs = OrderedDict ( ) cls . _tx_inh_by = inherits if inherits else [ ] cls . _tx_position = position cls . _tx_position_end = position if position_end is None else position_end cls . _tx_type = rule_type cls . _tx_peg_rule = peg_rule if peg_rule : peg_rule . _tx_class = cls current_namespace = self . namespaces [ self . _namespace_stack [ - 1 ] ] cls . _tx_fqn = self . _cls_fqn ( cls ) current_namespace [ cls . __name__ ] = cls if root : self . rootcls = cls | Setup meta - class special attributes namespaces etc . This is called both for textX created classes as well as user classes . |
10,753 | def _cls_fqn ( self , cls ) : ns = self . _namespace_stack [ - 1 ] if ns in [ '__base__' , None ] : return cls . __name__ else : return ns + '.' + cls . __name__ | Returns fully qualified name for the class based on current namespace and the class name . |
10,754 | def _new_cls_attr ( self , clazz , name , cls = None , mult = MULT_ONE , cont = True , ref = False , bool_assignment = False , position = 0 ) : attr = MetaAttr ( name , cls , mult , cont , ref , bool_assignment , position ) clazz . _tx_attrs [ name ] = attr return attr | Creates new meta attribute of this class . |
10,755 | def convert ( self , value , _type ) : return self . type_convertors . get ( _type , lambda x : x ) ( value ) | Convert instances of textx types and match rules to python types . |
10,756 | def register_obj_processors ( self , obj_processors ) : self . obj_processors = obj_processors self . type_convertors . update ( obj_processors ) | Object processors are callables that will be called after each successful model object construction . Those callables receive model object as its parameter . Registration of new object processors will replace previous . |
10,757 | def interpret ( self ) : self . print_menu ( ) while True : try : event = input ( ) if event == 'q' : return event = int ( event ) event = self . model . events [ event - 1 ] except Exception : print ( 'Invalid input' ) self . event ( event ) self . print_menu ( ) | Main interpreter loop . |
10,758 | def find_font ( font_name ) : if font_name in STANDARD_FONT_NAMES : return font_name , True elif font_name in _registered_fonts : return font_name , _registered_fonts [ font_name ] NOT_FOUND = ( None , False ) try : registerFont ( TTFont ( font_name , '%s.ttf' % font_name ) ) _registered_fonts [ font_name ] = True return font_name , True except TTFError : try : pipe = subprocess . Popen ( [ 'fc-match' , '-s' , '--format=%{file}\\n' , font_name ] , stdout = subprocess . PIPE , stderr = subprocess . PIPE , ) output = pipe . communicate ( ) [ 0 ] . decode ( sys . getfilesystemencoding ( ) ) font_path = output . split ( '\n' ) [ 0 ] except OSError : return NOT_FOUND try : registerFont ( TTFont ( font_name , font_path ) ) except TTFError : return NOT_FOUND exact = font_name . lower ( ) in os . path . basename ( font_path ) . lower ( ) _registered_fonts [ font_name ] = exact return font_name , exact | Return the font and a Boolean indicating if the match is exact . |
10,759 | def svg2rlg ( path , ** kwargs ) : "Convert an SVG file to an RLG Drawing object." unzipped = False if isinstance ( path , str ) and os . path . splitext ( path ) [ 1 ] . lower ( ) == ".svgz" : with gzip . open ( path , 'rb' ) as f_in , open ( path [ : - 1 ] , 'wb' ) as f_out : shutil . copyfileobj ( f_in , f_out ) path = path [ : - 1 ] unzipped = True svg_root = load_svg_file ( path ) if svg_root is None : return svgRenderer = SvgRenderer ( path , ** kwargs ) drawing = svgRenderer . render ( svg_root ) if unzipped : os . remove ( path ) return drawing | Convert an SVG file to an RLG Drawing object . |
10,760 | def parseMultiAttributes ( self , line ) : attrs = line . split ( ';' ) attrs = [ a . strip ( ) for a in attrs ] attrs = filter ( lambda a : len ( a ) > 0 , attrs ) new_attrs = { } for a in attrs : k , v = a . split ( ':' ) k , v = [ s . strip ( ) for s in ( k , v ) ] new_attrs [ k ] = v return new_attrs | Try parsing compound attribute string . |
10,761 | def findAttr ( self , svgNode , name ) : if self . css_rules is not None and not svgNode . attrib . get ( '__rules_applied' , False ) : if isinstance ( svgNode , NodeTracker ) : svgNode . apply_rules ( self . css_rules ) else : ElementWrapper ( svgNode ) . apply_rules ( self . css_rules ) attr_value = svgNode . attrib . get ( name , '' ) . strip ( ) if attr_value and attr_value != "inherit" : return attr_value elif svgNode . attrib . get ( "style" ) : dict = self . parseMultiAttributes ( svgNode . attrib . get ( "style" ) ) if name in dict : return dict [ name ] if svgNode . getparent ( ) is not None : return self . findAttr ( svgNode . getparent ( ) , name ) return '' | Search an attribute with some name in some node or above . |
10,762 | def getAllAttributes ( self , svgNode ) : "Return a dictionary of all attributes of svgNode or those inherited by it." dict = { } if node_name ( svgNode . getparent ( ) ) == 'g' : dict . update ( self . getAllAttributes ( svgNode . getparent ( ) ) ) style = svgNode . attrib . get ( "style" ) if style : d = self . parseMultiAttributes ( style ) dict . update ( d ) for key , value in svgNode . attrib . items ( ) : if key != "style" : dict [ key ] = value return dict | Return a dictionary of all attributes of svgNode or those inherited by it . |
10,763 | def convertTransform ( self , svgAttr ) : line = svgAttr . strip ( ) ops = line [ : ] brackets = [ ] indices = [ ] for i , lin in enumerate ( line ) : if lin in "()" : brackets . append ( i ) for i in range ( 0 , len ( brackets ) , 2 ) : bi , bj = brackets [ i ] , brackets [ i + 1 ] subline = line [ bi + 1 : bj ] subline = subline . strip ( ) subline = subline . replace ( ',' , ' ' ) subline = re . sub ( "[ ]+" , ',' , subline ) try : if ',' in subline : indices . append ( tuple ( float ( num ) for num in subline . split ( ',' ) ) ) else : indices . append ( float ( subline ) ) except ValueError : continue ops = ops [ : bi ] + ' ' * ( bj - bi + 1 ) + ops [ bj + 1 : ] ops = ops . replace ( ',' , ' ' ) . split ( ) if len ( ops ) != len ( indices ) : logger . warning ( "Unable to parse transform expression '%s'" % svgAttr ) return [ ] result = [ ] for i , op in enumerate ( ops ) : result . append ( ( op , indices [ i ] ) ) return result | Parse transform attribute string . |
10,764 | def convertLength ( self , svgAttr , percentOf = 100 , em_base = 12 ) : "Convert length to points." text = svgAttr if not text : return 0.0 if ' ' in text . replace ( ',' , ' ' ) . strip ( ) : logger . debug ( "Only getting first value of %s" % text ) text = text . replace ( ',' , ' ' ) . split ( ) [ 0 ] if text . endswith ( '%' ) : logger . debug ( "Fiddling length unit: %" ) return float ( text [ : - 1 ] ) / 100 * percentOf elif text . endswith ( "pc" ) : return float ( text [ : - 2 ] ) * pica elif text . endswith ( "pt" ) : return float ( text [ : - 2 ] ) * 1.25 elif text . endswith ( "em" ) : return float ( text [ : - 2 ] ) * em_base elif text . endswith ( "px" ) : return float ( text [ : - 2 ] ) if "ex" in text : logger . warning ( "Ignoring unit ex" ) text = text . replace ( "ex" , '' ) text = text . strip ( ) length = toLength ( text ) return length | Convert length to points . |
10,765 | def convertLengthList ( self , svgAttr ) : return [ self . convertLength ( a ) for a in self . split_attr_list ( svgAttr ) ] | Convert a list of lengths . |
10,766 | def convertColor ( self , svgAttr ) : "Convert string to a RL color object." predefined = "aqua black blue fuchsia gray green lime maroon navy " predefined = predefined + "olive orange purple red silver teal white yellow " predefined = predefined + "lawngreen indianred aquamarine lightgreen brown" text = svgAttr if not text or text == "none" : return None if text in predefined . split ( ) : return self . color_converter ( getattr ( colors , text ) ) elif text == "currentColor" : return "currentColor" elif len ( text ) == 7 and text [ 0 ] == '#' : return self . color_converter ( colors . HexColor ( text ) ) elif len ( text ) == 4 and text [ 0 ] == '#' : return self . color_converter ( colors . HexColor ( '#' + 2 * text [ 1 ] + 2 * text [ 2 ] + 2 * text [ 3 ] ) ) elif text . startswith ( 'rgb' ) and '%' not in text : t = text [ 3 : ] . strip ( '()' ) tup = [ h [ 2 : ] for h in [ hex ( int ( num ) ) for num in t . split ( ',' ) ] ] tup = [ ( 2 - len ( h ) ) * '0' + h for h in tup ] col = "#%s%s%s" % tuple ( tup ) return self . color_converter ( colors . HexColor ( col ) ) elif text . startswith ( 'rgb' ) and '%' in text : t = text [ 3 : ] . replace ( '%' , '' ) . strip ( '()' ) tup = ( float ( val ) / 100.0 for val in t . split ( ',' ) ) return self . color_converter ( colors . Color ( * tup ) ) logger . warning ( "Can't handle color: %s" % text ) return None | Convert string to a RL color object . |
10,767 | def get_clippath ( self , node ) : def get_path_from_node ( node ) : for child in node . getchildren ( ) : if node_name ( child ) == 'path' : group = self . shape_converter . convertShape ( 'path' , NodeTracker ( child ) ) return group . contents [ - 1 ] else : return get_path_from_node ( child ) clip_path = node . getAttribute ( 'clip-path' ) if clip_path : m = re . match ( r'url\(#([^\)]*)\)' , clip_path ) if m : ref = m . groups ( ) [ 0 ] if ref in self . definitions : path = get_path_from_node ( self . definitions [ ref ] ) if path : path = ClippingPath ( copy_from = path ) return path | Return the clipping Path object referenced by the node clip - path attribute if any . |
10,768 | def applyTransformOnGroup ( self , transform , group ) : tr = self . attrConverter . convertTransform ( transform ) for op , values in tr : if op == "scale" : if not isinstance ( values , tuple ) : values = ( values , values ) group . scale ( * values ) elif op == "translate" : if isinstance ( values , ( int , float ) ) : values = values , 0 group . translate ( * values ) elif op == "rotate" : if not isinstance ( values , tuple ) or len ( values ) == 1 : group . rotate ( values ) elif len ( values ) == 3 : angle , cx , cy = values group . translate ( cx , cy ) group . rotate ( angle ) group . translate ( - cx , - cy ) elif op == "skewX" : group . skew ( values , 0 ) elif op == "skewY" : group . skew ( 0 , values ) elif op == "matrix" : group . transform = values else : logger . debug ( "Ignoring transform: %s %s" % ( op , values ) ) | Apply an SVG transformation to a RL Group shape . |
10,769 | def applyStyleOnShape ( self , shape , node , only_explicit = False ) : "Apply style attributes of a sequence of nodes to an RL shape." mappingN = ( ( "fill" , "fillColor" , "convertColor" , "black" ) , ( "fill-opacity" , "fillOpacity" , "convertOpacity" , 1 ) , ( "fill-rule" , "_fillRule" , "convertFillRule" , "nonzero" ) , ( "stroke" , "strokeColor" , "convertColor" , "none" ) , ( "stroke-width" , "strokeWidth" , "convertLength" , "1" ) , ( "stroke-opacity" , "strokeOpacity" , "convertOpacity" , 1 ) , ( "stroke-linejoin" , "strokeLineJoin" , "convertLineJoin" , "0" ) , ( "stroke-linecap" , "strokeLineCap" , "convertLineCap" , "0" ) , ( "stroke-dasharray" , "strokeDashArray" , "convertDashArray" , "none" ) , ) mappingF = ( ( "font-family" , "fontName" , "convertFontFamily" , DEFAULT_FONT_NAME ) , ( "font-size" , "fontSize" , "convertLength" , "12" ) , ( "text-anchor" , "textAnchor" , "id" , "start" ) , ) if shape . __class__ == Group : for subshape in shape . contents : self . applyStyleOnShape ( subshape , node , only_explicit = only_explicit ) return ac = self . attrConverter for mapping in ( mappingN , mappingF ) : if shape . __class__ != String and mapping == mappingF : continue for ( svgAttrName , rlgAttr , func , default ) in mapping : svgAttrValue = ac . findAttr ( node , svgAttrName ) if svgAttrValue == '' : if only_explicit : continue else : svgAttrValue = default if svgAttrValue == "currentColor" : svgAttrValue = ac . findAttr ( node . getparent ( ) , "color" ) or default try : meth = getattr ( ac , func ) setattr ( shape , rlgAttr , meth ( svgAttrValue ) ) except ( AttributeError , KeyError , ValueError ) : pass if getattr ( shape , 'fillOpacity' , None ) is not None and shape . fillColor : shape . fillColor . alpha = shape . fillOpacity | Apply styles from an SVG element to an RLG shape . If only_explicit is True only attributes really present are applied . |
10,770 | def split_floats ( op , min_num , value ) : floats = [ float ( seq ) for seq in re . findall ( r'(-?\d*\.?\d*(?:e[+-]\d+)?)' , value ) if seq ] res = [ ] for i in range ( 0 , len ( floats ) , min_num ) : if i > 0 and op in { 'm' , 'M' } : op = 'l' if op == 'm' else 'L' res . extend ( [ op , floats [ i : i + min_num ] ] ) return res | Split value a list of numbers as a string to a list of float numbers . |
10,771 | def normalise_svg_path ( attr ) : ops = { 'A' : 7 , 'a' : 7 , 'Q' : 4 , 'q' : 4 , 'T' : 2 , 't' : 2 , 'S' : 4 , 's' : 4 , 'M' : 2 , 'L' : 2 , 'm' : 2 , 'l' : 2 , 'H' : 1 , 'V' : 1 , 'h' : 1 , 'v' : 1 , 'C' : 6 , 'c' : 6 , 'Z' : 0 , 'z' : 0 , } op_keys = ops . keys ( ) result = [ ] groups = re . split ( '([achlmqstvz])' , attr . strip ( ) , flags = re . I ) op = None for item in groups : if item . strip ( ) == '' : continue if item in op_keys : if item == 'M' and item == op : op = 'L' elif item == 'm' and item == op : op = 'l' else : op = item if ops [ op ] == 0 : result . extend ( [ op , [ ] ] ) else : result . extend ( split_floats ( op , ops [ op ] , item ) ) op = result [ - 2 ] return result | Normalise SVG path . |
10,772 | def convert_quadratic_to_cubic_path ( q0 , q1 , q2 ) : c0 = q0 c1 = ( q0 [ 0 ] + 2. / 3 * ( q1 [ 0 ] - q0 [ 0 ] ) , q0 [ 1 ] + 2. / 3 * ( q1 [ 1 ] - q0 [ 1 ] ) ) c2 = ( c1 [ 0 ] + 1. / 3 * ( q2 [ 0 ] - q0 [ 0 ] ) , c1 [ 1 ] + 1. / 3 * ( q2 [ 1 ] - q0 [ 1 ] ) ) c3 = q2 return c0 , c1 , c2 , c3 | Convert a quadratic Bezier curve through q0 q1 q2 to a cubic one . |
10,773 | def client_start ( request , socket , context ) : CLIENTS [ socket . session . session_id ] = ( request , socket , context ) | Adds the client triple to CLIENTS . |
10,774 | def client_end ( request , socket , context ) : for channel in socket . channels : events . on_unsubscribe . send ( request , socket , context , channel ) events . on_finish . send ( request , socket , context ) for channel in socket . channels [ : ] : socket . unsubscribe ( channel ) del CLIENTS [ socket . session . session_id ] | Handles cleanup when a session ends for the given client triple . Sends unsubscribe and finish events actually unsubscribes from any channels subscribed to and removes the client triple from CLIENTS . |
10,775 | def client_end_all ( ) : for request , socket , context in CLIENTS . values ( ) [ : ] : client_end ( request , socket , context ) | Performs cleanup on all clients - called by runserver_socketio when the server is shut down or reloaded . |
10,776 | def subscribe ( self , channel ) : if channel in self . channels : return False CHANNELS [ channel ] . append ( self . socket . session . session_id ) self . channels . append ( channel ) return True | Add the channel to this socket s channels and to the list of subscribed session IDs for the channel . Return False if already subscribed otherwise True . |
10,777 | def unsubscribe ( self , channel ) : try : CHANNELS [ channel ] . remove ( self . socket . session . session_id ) self . channels . remove ( channel ) except ValueError : return False return True | Remove the channel from this socket s channels and from the list of subscribed session IDs for the channel . Return False if not subscribed otherwise True . |
10,778 | def broadcast_channel ( self , message , channel = None ) : if channel is None : channels = self . channels else : channels = [ channel ] for channel in channels : for subscriber in CHANNELS [ channel ] : if subscriber != self . socket . session . session_id : session = self . socket . handler . server . sessions [ subscriber ] self . _write ( message , session ) | Send the given message to all subscribers for the channel given . If no channel is given send to the subscribers for all the channels that this socket is subscribed to . |
10,779 | def send_and_broadcast_channel ( self , message , channel = None ) : self . send ( message ) self . broadcast_channel ( message , channel ) | Shortcut for a socket to broadcast to all sockets subscribed to a channel and itself . |
10,780 | def message ( request , socket , context , message ) : room = get_object_or_404 ( ChatRoom , id = message [ "room" ] ) if message [ "action" ] == "start" : name = strip_tags ( message [ "name" ] ) user , created = room . users . get_or_create ( name = name ) if not created : socket . send ( { "action" : "in-use" } ) else : context [ "user" ] = user users = [ u . name for u in room . users . exclude ( id = user . id ) ] socket . send ( { "action" : "started" , "users" : users } ) user . session = socket . session . session_id user . save ( ) joined = { "action" : "join" , "name" : user . name , "id" : user . id } socket . send_and_broadcast_channel ( joined ) else : try : user = context [ "user" ] except KeyError : return if message [ "action" ] == "message" : message [ "message" ] = strip_tags ( message [ "message" ] ) message [ "name" ] = user . name socket . send_and_broadcast_channel ( message ) | Event handler for a room receiving a message . First validates a joining user s name and sends them the list of users . |
10,781 | def finish ( request , socket , context ) : try : user = context [ "user" ] except KeyError : return left = { "action" : "leave" , "name" : user . name , "id" : user . id } socket . broadcast_channel ( left ) user . delete ( ) | Event handler for a socket session ending in a room . Broadcast the user leaving and delete them from the DB . |
10,782 | def send ( session_id , message ) : try : socket = CLIENTS [ session_id ] [ 1 ] except KeyError : raise NoSocket ( "There is no socket with the session ID: " + session_id ) socket . send ( message ) | Send a message to the socket for the given session ID . |
10,783 | def broadcast ( message ) : try : socket = CLIENTS . values ( ) [ 0 ] [ 1 ] except IndexError : raise NoSocket ( "There are no clients." ) socket . send_and_broadcast ( message ) | Find the first socket and use it to broadcast to all sockets including the socket itself . |
10,784 | def broadcast_channel ( message , channel ) : try : socket = CLIENTS [ CHANNELS . get ( channel , [ ] ) [ 0 ] ] [ 1 ] except ( IndexError , KeyError ) : raise NoSocket ( "There are no clients on the channel: " + channel ) socket . send_and_broadcast_channel ( message , channel ) | Find the first socket for the given channel and use it to broadcast to the channel including the socket itself . |
10,785 | def format_log ( request , message_type , message ) : from django_socketio . settings import MESSAGE_LOG_FORMAT if MESSAGE_LOG_FORMAT is None : return None now = datetime . now ( ) . replace ( microsecond = 0 ) args = dict ( request . META , TYPE = message_type , MESSAGE = message , TIME = now ) return ( MESSAGE_LOG_FORMAT % args ) + "\n" | Formats a log message similar to gevent s pywsgi request logging . |
10,786 | def get_handler ( self , * args , ** options ) : handler = WSGIHandler ( ) try : from django . contrib . staticfiles . handlers import StaticFilesHandler except ImportError : return handler use_static_handler = options . get ( 'use_static_handler' , True ) insecure_serving = options . get ( 'insecure_serving' , False ) if ( settings . DEBUG and use_static_handler or ( use_static_handler and insecure_serving ) ) : handler = StaticFilesHandler ( handler ) return handler | Returns the django . contrib . staticfiles handler . |
10,787 | def send ( self , request , socket , context , * args ) : for handler , pattern in self . handlers : no_channel = not pattern and not socket . channels if self . name . endswith ( "subscribe" ) and pattern : matches = [ pattern . match ( args [ 0 ] ) ] else : matches = [ pattern . match ( c ) for c in socket . channels if pattern ] if no_channel or filter ( None , matches ) : handler ( request , socket , context , * args ) | When an event is sent run all relevant handlers . Relevant handlers are those without a channel pattern when the given socket is not subscribed to any particular channel or the handlers with a channel pattern that matches any of the channels that the given socket is subscribed to . |
10,788 | def rooms ( request , template = "rooms.html" ) : context = { "rooms" : ChatRoom . objects . all ( ) } return render ( request , template , context ) | Homepage - lists all rooms . |
10,789 | def room ( request , slug , template = "room.html" ) : context = { "room" : get_object_or_404 ( ChatRoom , slug = slug ) } return render ( request , template , context ) | Show a room . |
10,790 | def create ( request ) : name = request . POST . get ( "name" ) if name : room , created = ChatRoom . objects . get_or_create ( name = name ) return redirect ( room ) return redirect ( rooms ) | Handles post from the Add room form on the homepage and redirects to the new room . |
10,791 | def add_outer_solar_system ( sim ) : Gfac = 1. / 0.01720209895 if sim . G is not None : Gfac *= math . sqrt ( sim . G ) sim . add ( m = 1.00000597682 , x = - 4.06428567034226e-3 , y = - 6.08813756435987e-3 , z = - 1.66162304225834e-6 , vx = + 6.69048890636161e-6 * Gfac , vy = - 6.33922479583593e-6 * Gfac , vz = - 3.13202145590767e-9 * Gfac ) sim . add ( m = 1. / 1047.355 , x = + 3.40546614227466e+0 , y = + 3.62978190075864e+0 , z = + 3.42386261766577e-2 , vx = - 5.59797969310664e-3 * Gfac , vy = + 5.51815399480116e-3 * Gfac , vz = - 2.66711392865591e-6 * Gfac ) sim . add ( m = 1. / 3501.6 , x = + 6.60801554403466e+0 , y = + 6.38084674585064e+0 , z = - 1.36145963724542e-1 , vx = - 4.17354020307064e-3 * Gfac , vy = + 3.99723751748116e-3 * Gfac , vz = + 1.67206320571441e-5 * Gfac ) sim . add ( m = 1. / 22869. , x = + 1.11636331405597e+1 , y = + 1.60373479057256e+1 , z = + 3.61783279369958e-1 , vx = - 3.25884806151064e-3 * Gfac , vy = + 2.06438412905916e-3 * Gfac , vz = - 2.17699042180559e-5 * Gfac ) sim . add ( m = 1. / 19314. , x = - 3.01777243405203e+1 , y = + 1.91155314998064e+0 , z = - 1.53887595621042e-1 , vx = - 2.17471785045538e-4 * Gfac , vy = - 3.11361111025884e-3 * Gfac , vz = + 3.58344705491441e-5 * Gfac ) sim . add ( m = 7.4074074e-09 , x = - 2.13858977531573e+1 , y = + 3.20719104739886e+1 , z = + 2.49245689556096e+0 , vx = - 1.76936577252484e-3 * Gfac , vy = - 2.06720938381724e-3 * Gfac , vz = + 6.58091931493844e-4 * Gfac ) | Add the planet of the outer Solar System as a test problem . Data taken from NASA Horizons . |
10,792 | def get_color ( color ) : if isinstance ( color , tuple ) and len ( color ) == 3 : return color try : import matplotlib . colors as mplcolors except : raise ImportError ( "Error importing matplotlib. If running from within a jupyter notebook, try calling '%matplotlib inline' beforehand." ) try : hexcolor = mplcolors . cnames [ color ] except KeyError : raise AttributeError ( "Color not recognized in matplotlib." ) hexcolor = hexcolor . lstrip ( '#' ) lv = len ( hexcolor ) return tuple ( int ( hexcolor [ i : i + lv // 3 ] , 16 ) / 255. for i in range ( 0 , lv , lv // 3 ) ) | Takes a string for a color name defined in matplotlib and returns of a 3 - tuple of RGB values . Will simply return passed value if it s a tuple of length three . |
10,793 | def fading_line ( x , y , color = 'black' , alpha_initial = 1. , alpha_final = 0. , glow = False , ** kwargs ) : try : from matplotlib . collections import LineCollection from matplotlib . colors import LinearSegmentedColormap import numpy as np except : raise ImportError ( "Error importing matplotlib and/or numpy. Plotting functions not available. If running from within a jupyter notebook, try calling '%matplotlib inline' beforehand." ) if glow : glow = False kwargs [ "lw" ] = 1 fl1 = fading_line ( x , y , color , alpha_initial , alpha_final , glow = False , ** kwargs ) kwargs [ "lw" ] = 2 alpha_initial *= 0.5 alpha_final *= 0.5 fl2 = fading_line ( x , y , color , alpha_initial , alpha_final , glow = False , ** kwargs ) kwargs [ "lw" ] = 6 alpha_initial *= 0.5 alpha_final *= 0.5 fl3 = fading_line ( x , y , color , alpha_initial , alpha_final , glow = False , ** kwargs ) return [ fl3 , fl2 , fl1 ] color = get_color ( color ) cdict = { 'red' : ( ( 0. , color [ 0 ] , color [ 0 ] ) , ( 1. , color [ 0 ] , color [ 0 ] ) ) , 'green' : ( ( 0. , color [ 1 ] , color [ 1 ] ) , ( 1. , color [ 1 ] , color [ 1 ] ) ) , 'blue' : ( ( 0. , color [ 2 ] , color [ 2 ] ) , ( 1. , color [ 2 ] , color [ 2 ] ) ) , 'alpha' : ( ( 0. , alpha_initial , alpha_initial ) , ( 1. , alpha_final , alpha_final ) ) } Npts = len ( x ) if len ( y ) != Npts : raise AttributeError ( "x and y must have same dimension." ) segments = np . zeros ( ( Npts - 1 , 2 , 2 ) ) segments [ 0 ] [ 0 ] = [ x [ 0 ] , y [ 0 ] ] for i in range ( 1 , Npts - 1 ) : pt = [ x [ i ] , y [ i ] ] segments [ i - 1 ] [ 1 ] = pt segments [ i ] [ 0 ] = pt segments [ - 1 ] [ 1 ] = [ x [ - 1 ] , y [ - 1 ] ] individual_cm = LinearSegmentedColormap ( 'indv1' , cdict ) lc = LineCollection ( segments , cmap = individual_cm , ** kwargs ) lc . set_array ( np . linspace ( 0. , 1. , len ( segments ) ) ) return lc | Returns a matplotlib LineCollection connecting the points in the x and y lists with a single color and alpha varying from alpha_initial to alpha_final along the line . Can pass any kwargs you can pass to LineCollection like linewidgth . |
10,794 | def _getSnapshotIndex ( self , t ) : if t > self . tmax or t < self . tmin : raise ValueError ( "Requested time outside of baseline stored in binary file." ) l = 0 r = len ( self ) while True : bi = l + ( r - l ) // 2 if self . t [ bi ] > t : r = bi else : l = bi if r - 1 <= l : bi = l break return bi , self . t [ bi ] | Return the index for the snapshot just before t |
10,795 | def getSimulations ( self , times , ** kwargs ) : for t in times : yield self . getSimulation ( t , ** kwargs ) | A generator to quickly access many simulations . The arguments are the same as for getSimulation . |
10,796 | def copy ( self ) : np = Particle ( ) memmove ( byref ( np ) , byref ( self ) , sizeof ( self ) ) return np | Returns a deep copy of the particle . The particle is not added to any simulation by default . |
10,797 | def takeScreenshot ( self , times = None , prefix = "./screenshot" , resetCounter = False , archive = None , mode = "snapshot" ) : self . archive = archive if resetCounter : self . screenshotcountall = 0 self . screenshotprefix = prefix self . screenshotcount = 0 self . overlay = "REBOUND" self . screenshot = "" if archive is None : if times is None : times = self . simp . contents . t try : len ( times ) except : times = [ times ] self . times = times self . observe ( savescreenshot , names = "screenshot" ) self . simp . contents . integrate ( times [ 0 ] ) self . screenshotcount += 1 else : if times is None : raise ValueError ( "Need times argument for archive mode." ) try : len ( times ) except : raise ValueError ( "Need a list of times for archive mode." ) self . times = times self . mode = mode self . observe ( savescreenshot , names = "screenshot" ) sim = archive . getSimulation ( times [ 0 ] , mode = mode ) self . refresh ( pointer ( sim ) ) self . screenshotcount += 1 | Take one or more screenshots of the widget and save the images to a file . The images can be used to create a video . |
10,798 | def coordinates ( self ) : i = self . _coordinates for name , _i in COORDINATES . items ( ) : if i == _i : return name return i | Get or set the internal coordinate system . |
10,799 | def getWidget ( self , ** kwargs ) : from . widget import Widget from ipywidgets import DOMWidget from IPython . display import display , HTML if not hasattr ( self , '_widgets' ) : self . _widgets = [ ] def display_heartbeat ( simp ) : for w in self . _widgets : w . refresh ( simp , isauto = 1 ) self . visualization = VISUALIZATIONS [ "webgl" ] clibrebound . reb_display_init_data ( byref ( self ) ) self . _dhbf = AFF ( display_heartbeat ) self . _display_heartbeat = self . _dhbf display ( HTML ( Widget . getClientCode ( ) ) ) newWidget = Widget ( self , ** kwargs ) self . _widgets . append ( newWidget ) newWidget . refresh ( isauto = 0 ) return newWidget | Wrapper function that returns a new widget attached to this simulation . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.