idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
8,400 | def mac_to_ipv6_linklocal ( mac , prefix = "fe80::" ) : # Remove the most common delimiters; dots, dashes, etc. mac_value = int ( mac . translate ( str . maketrans ( dict ( [ ( x , None ) for x in [ " " , "." , ":" , "-" ] ] ) ) ) , 16 ) # Split out the bytes that slot into the IPv6 address # XOR the most significant byte with 0x02, inverting the # Universal / Local bit high2 = mac_value >> 32 & 0xffff ^ 0x0200 high1 = mac_value >> 24 & 0xff low1 = mac_value >> 16 & 0xff low2 = mac_value & 0xffff return prefix + ':{:04x}:{:02x}ff:fe{:02x}:{:04x}' . format ( high2 , high1 , low1 , low2 ) | Translate a MAC address into an IPv6 address in the prefixed network . | 210 | 16 |
8,401 | def datagram_received ( self , data , addr ) : self . register ( ) response = unpack_lifx_message ( data ) self . lastmsg = datetime . datetime . now ( ) if response . seq_num in self . message : response_type , myevent , callb = self . message [ response . seq_num ] if type ( response ) == response_type : if response . source_id == self . source_id : if "State" in response . __class__ . __name__ : setmethod = "resp_set_" + response . __class__ . __name__ . replace ( "State" , "" ) . lower ( ) if setmethod in dir ( self ) and callable ( getattr ( self , setmethod ) ) : getattr ( self , setmethod ) ( response ) if callb : callb ( self , response ) myevent . set ( ) del ( self . message [ response . seq_num ] ) elif type ( response ) == Acknowledgement : pass else : del ( self . message [ response . seq_num ] ) elif self . default_callb : self . default_callb ( response ) | Method run when data is received from the device | 253 | 9 |
8,402 | def register ( self ) : if not self . registered : self . registered = True if self . parent : self . parent . register ( self ) | Proxy method to register the device with the parent . | 30 | 10 |
8,403 | def unregister ( self ) : if self . registered : #Only if we have not received any message recently. if datetime . datetime . now ( ) - datetime . timedelta ( seconds = self . unregister_timeout ) > self . lastmsg : self . registered = False if self . parent : self . parent . unregister ( self ) | Proxy method to unregister the device with the parent . | 74 | 11 |
8,404 | async def fire_sending ( self , msg , num_repeats ) : if num_repeats is None : num_repeats = self . retry_count sent_msg_count = 0 sleep_interval = 0.05 while ( sent_msg_count < num_repeats ) : if self . transport : self . transport . sendto ( msg . packed_message ) sent_msg_count += 1 await aio . sleep ( sleep_interval ) | Coroutine used to send message to the device when no response is needed . | 102 | 15 |
8,405 | async def try_sending ( self , msg , timeout_secs , max_attempts ) : if timeout_secs is None : timeout_secs = self . timeout if max_attempts is None : max_attempts = self . retry_count attempts = 0 while attempts < max_attempts : if msg . seq_num not in self . message : return event = aio . Event ( ) self . message [ msg . seq_num ] [ 1 ] = event attempts += 1 if self . transport : self . transport . sendto ( msg . packed_message ) try : myresult = await aio . wait_for ( event . wait ( ) , timeout_secs ) break except Exception as inst : if attempts >= max_attempts : if msg . seq_num in self . message : callb = self . message [ msg . seq_num ] [ 2 ] if callb : callb ( self , None ) del ( self . message [ msg . seq_num ] ) #It's dead Jim self . unregister ( ) | Coroutine used to send message to the device when a response or ack is needed . | 231 | 18 |
8,406 | def req_with_ack ( self , msg_type , payload , callb = None , timeout_secs = None , max_attempts = None ) : msg = msg_type ( self . mac_addr , self . source_id , seq_num = self . seq_next ( ) , payload = payload , ack_requested = True , response_requested = False ) self . message [ msg . seq_num ] = [ Acknowledgement , None , callb ] xx = self . loop . create_task ( self . try_sending ( msg , timeout_secs , max_attempts ) ) return True | Method to send a message expecting to receive an ACK . | 139 | 12 |
8,407 | def get_label ( self , callb = None ) : if self . label is None : mypartial = partial ( self . resp_set_label ) if callb : mycallb = lambda x , y : ( mypartial ( y ) , callb ( x , y ) ) else : mycallb = lambda x , y : mypartial ( y ) response = self . req_with_resp ( GetLabel , StateLabel , callb = mycallb ) return self . label | Convenience method to request the label from the device | 104 | 11 |
8,408 | def set_label ( self , value , callb = None ) : if len ( value ) > 32 : value = value [ : 32 ] mypartial = partial ( self . resp_set_label , label = value ) if callb : self . req_with_ack ( SetLabel , { "label" : value } , lambda x , y : ( mypartial ( y ) , callb ( x , y ) ) ) else : self . req_with_ack ( SetLabel , { "label" : value } , lambda x , y : mypartial ( y ) ) | Convenience method to set the label of the device | 123 | 11 |
8,409 | def get_location ( self , callb = None ) : if self . location is None : mypartial = partial ( self . resp_set_location ) if callb : mycallb = lambda x , y : ( mypartial ( y ) , callb ( x , y ) ) else : mycallb = lambda x , y : mypartial ( y ) response = self . req_with_resp ( GetLocation , StateLocation , callb = mycallb ) return self . location | Convenience method to request the location from the device | 104 | 11 |
8,410 | def get_group ( self , callb = None ) : if self . group is None : mypartial = partial ( self . resp_set_group ) if callb : mycallb = lambda x , y : ( mypartial ( y ) , callb ( x , y ) ) else : mycallb = lambda x , y : mypartial ( y ) response = self . req_with_resp ( GetGroup , StateGroup , callb = callb ) return self . group | Convenience method to request the group from the device | 103 | 11 |
8,411 | def get_wififirmware ( self , callb = None ) : if self . wifi_firmware_version is None : mypartial = partial ( self . resp_set_wififirmware ) if callb : mycallb = lambda x , y : ( mypartial ( y ) , callb ( x , y ) ) else : mycallb = lambda x , y : mypartial ( y ) response = self . req_with_resp ( GetWifiFirmware , StateWifiFirmware , mycallb ) return ( self . wifi_firmware_version , self . wifi_firmware_build_timestamp ) | Convenience method to request the wifi firmware info from the device | 144 | 13 |
8,412 | def resp_set_wififirmware ( self , resp ) : if resp : self . wifi_firmware_version = float ( str ( str ( resp . version >> 16 ) + "." + str ( resp . version & 0xff ) ) ) self . wifi_firmware_build_timestamp = resp . build | Default callback for get_wififirmware | 72 | 10 |
8,413 | def get_wifiinfo ( self , callb = None ) : response = self . req_with_resp ( GetWifiInfo , StateWifiInfo , callb = callb ) return None | Convenience method to request the wifi info from the device | 43 | 12 |
8,414 | def get_hostfirmware ( self , callb = None ) : if self . host_firmware_version is None : mypartial = partial ( self . resp_set_hostfirmware ) if callb : mycallb = lambda x , y : ( mypartial ( y ) , callb ( x , y ) ) else : mycallb = lambda x , y : mypartial ( y ) response = self . req_with_resp ( GetHostFirmware , StateHostFirmware , mycallb ) return ( self . host_firmware_version , self . host_firmware_build_timestamp ) | Convenience method to request the device firmware info from the device | 140 | 13 |
8,415 | def resp_set_hostfirmware ( self , resp ) : if resp : self . host_firmware_version = float ( str ( str ( resp . version >> 16 ) + "." + str ( resp . version & 0xff ) ) ) self . host_firmware_build_timestamp = resp . build | Default callback for get_hostfirmware | 71 | 9 |
8,416 | def get_hostinfo ( self , callb = None ) : response = self . req_with_resp ( GetInfo , StateInfo , callb = callb ) return None | Convenience method to request the device info from the device | 38 | 12 |
8,417 | def get_version ( self , callb = None ) : if self . vendor is None : mypartial = partial ( self . resp_set_version ) if callb : mycallb = lambda x , y : ( mypartial ( y ) , callb ( x , y ) ) else : mycallb = lambda x , y : mypartial ( y ) response = self . req_with_resp ( GetVersion , StateVersion , callb = mycallb ) return ( self . host_firmware_version , self . host_firmware_build_timestamp ) | Convenience method to request the version from the device | 125 | 11 |
8,418 | def resp_set_version ( self , resp ) : if resp : self . vendor = resp . vendor self . product = resp . product self . version = resp . version | Default callback for get_version | 36 | 6 |
8,419 | def resp_set_lightpower ( self , resp , power_level = None ) : if power_level is not None : self . power_level = power_level elif resp : self . power_level = resp . power_level | Default callback for set_power | 51 | 6 |
8,420 | def get_color ( self , callb = None ) : response = self . req_with_resp ( LightGet , LightState , callb = callb ) return self . color | Convenience method to request the colour status from the device | 39 | 12 |
8,421 | def set_color ( self , value , callb = None , duration = 0 , rapid = False ) : if len ( value ) == 4 : mypartial = partial ( self . resp_set_light , color = value ) if callb : mycallb = lambda x , y : ( mypartial ( y ) , callb ( x , y ) ) else : mycallb = lambda x , y : mypartial ( y ) #try: if rapid : self . fire_and_forget ( LightSetColor , { "color" : value , "duration" : duration } , num_repeats = 1 ) self . resp_set_light ( None , color = value ) if callb : callb ( self , None ) else : self . req_with_ack ( LightSetColor , { "color" : value , "duration" : duration } , callb = mycallb ) | Convenience method to set the colour status of the device | 192 | 12 |
8,422 | def resp_set_light ( self , resp , color = None ) : if color : self . color = color elif resp : self . power_level = resp . power_level self . color = resp . color self . label = resp . label . decode ( ) . replace ( "\x00" , "" ) | Default callback for set_color | 67 | 6 |
8,423 | def get_color_zones ( self , start_index , end_index = None , callb = None ) : if end_index is None : end_index = start_index + 7 args = { "start_index" : start_index , "end_index" : end_index , } self . req_with_resp ( MultiZoneGetColorZones , MultiZoneStateMultiZone , payload = args , callb = callb ) | Convenience method to request the state of colour by zones from the device | 97 | 15 |
8,424 | def set_color_zones ( self , start_index , end_index , color , duration = 0 , apply = 1 , callb = None , rapid = False ) : if len ( color ) == 4 : args = { "start_index" : start_index , "end_index" : end_index , "color" : color , "duration" : duration , "apply" : apply , } mypartial = partial ( self . resp_set_multizonemultizone , args = args ) if callb : mycallb = lambda x , y : ( mypartial ( y ) , callb ( x , y ) ) else : mycallb = lambda x , y : mypartial ( y ) if rapid : self . fire_and_forget ( MultiZoneSetColorZones , args , num_repeats = 1 ) mycallb ( self , None ) else : self . req_with_ack ( MultiZoneSetColorZones , args , callb = mycallb ) | Convenience method to set the colour status zone of the device | 216 | 13 |
8,425 | def get_infrared ( self , callb = None ) : response = self . req_with_resp ( LightGetInfrared , LightStateInfrared , callb = callb ) return self . infrared_brightness | Convenience method to request the infrared brightness from the device | 47 | 12 |
8,426 | def set_infrared ( self , infrared_brightness , callb = None , rapid = False ) : mypartial = partial ( self . resp_set_infrared , infrared_brightness = infrared_brightness ) if callb : mycallb = lambda x , y : ( mypartial ( y ) , callb ( x , y ) ) else : mycallb = lambda x , y : mypartial ( y ) if rapid : self . fire_and_forget ( LightSetInfrared , { "infrared_brightness" : infrared_brightness } , num_repeats = 1 ) self . resp_set_infrared ( None , infrared_brightness = infrared_brightness ) if callb : callb ( self , None ) else : self . req_with_ack ( LightSetInfrared , { "infrared_brightness" : infrared_brightness } , callb = mycallb ) | Convenience method to set the infrared status of the device | 199 | 12 |
8,427 | def start ( self , listen_ip = LISTEN_IP , listen_port = 0 ) : coro = self . loop . create_datagram_endpoint ( lambda : self , local_addr = ( listen_ip , listen_port ) ) self . task = self . loop . create_task ( coro ) return self . task | Start discovery task . | 73 | 4 |
8,428 | def connection_made ( self , transport ) : #print('started') self . transport = transport sock = self . transport . get_extra_info ( "socket" ) sock . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 ) sock . setsockopt ( socket . SOL_SOCKET , socket . SO_BROADCAST , 1 ) self . loop . call_soon ( self . discover ) | Method run when the UDP broadcast server is started | 97 | 9 |
8,429 | def datagram_received ( self , data , addr ) : response = unpack_lifx_message ( data ) response . ip_addr = addr [ 0 ] mac_addr = response . target_addr if mac_addr == BROADCAST_MAC : return if type ( response ) == StateService and response . service == 1 : # only look for UDP services # discovered remote_port = response . port elif type ( response ) == LightState : # looks like the lights are volunteering LigthState after booting remote_port = UDP_BROADCAST_PORT else : return if self . ipv6prefix : family = socket . AF_INET6 remote_ip = mac_to_ipv6_linklocal ( mac_addr , self . ipv6prefix ) else : family = socket . AF_INET remote_ip = response . ip_addr if mac_addr in self . lights : # rediscovered light = self . lights [ mac_addr ] # nothing to do if light . registered : return light . cleanup ( ) light . ip_addr = remote_ip light . port = remote_port else : # newly discovered light = Light ( self . loop , mac_addr , remote_ip , remote_port , parent = self ) self . lights [ mac_addr ] = light coro = self . loop . create_datagram_endpoint ( lambda : light , family = family , remote_addr = ( remote_ip , remote_port ) ) light . task = self . loop . create_task ( coro ) | Method run when data is received from the devices | 330 | 9 |
8,430 | def discover ( self ) : if self . transport : if self . discovery_countdown <= 0 : self . discovery_countdown = self . discovery_interval msg = GetService ( BROADCAST_MAC , self . source_id , seq_num = 0 , payload = { } , ack_requested = False , response_requested = True ) self . transport . sendto ( msg . generate_packed_message ( ) , ( self . broadcast_ip , UDP_BROADCAST_PORT ) ) else : self . discovery_countdown -= self . discovery_step self . loop . call_later ( self . discovery_step , self . discover ) | Method to send a discovery message | 142 | 6 |
8,431 | async def scan ( self , timeout = 1 ) : adapters = await self . loop . run_in_executor ( None , ifaddr . get_adapters ) ips = [ ip . ip for adapter in ifaddr . get_adapters ( ) for ip in adapter . ips if ip . is_IPv4 ] if not ips : return [ ] tasks = [ ] discoveries = [ ] for ip in ips : manager = ScanManager ( ip ) lifx_discovery = LifxDiscovery ( self . loop , manager ) discoveries . append ( lifx_discovery ) lifx_discovery . start ( listen_ip = ip ) tasks . append ( self . loop . create_task ( manager . lifx_ip ( ) ) ) ( done , pending ) = await aio . wait ( tasks , timeout = timeout ) for discovery in discoveries : discovery . cleanup ( ) for task in pending : task . cancel ( ) return [ task . result ( ) for task in done ] | Return a list of local IP addresses on interfaces with LIFX bulbs . | 213 | 15 |
8,432 | def _get_file_version ( filename ) : mat = sio . loadmat ( filename , squeeze_me = True ) version = mat [ 'MP' ] [ 'Version' ] . item ( ) del ( mat ) return version | High level import function that tries to determine the specific version of the data format used . | 50 | 17 |
8,433 | def MD_ConfigsPermutate ( df_md ) : g_current_injections = df_md . groupby ( [ 'a' , 'b' ] ) ab = np . array ( list ( g_current_injections . groups . keys ( ) ) ) config_mgr = ConfigManager ( nr_of_electrodes = ab . max ( ) ) config_mgr . gen_configs_permutate ( ab , silent = True ) return config_mgr . configs | Given a MD DataFrame return a Nx4 array which permutes the current injection dipoles . | 113 | 20 |
8,434 | def apply_correction_factors ( df , correction_file ) : if isinstance ( correction_file , ( list , tuple ) ) : corr_data_raw = np . vstack ( [ np . loadtxt ( x ) for x in correction_file ] ) else : corr_data_raw = np . loadtxt ( correction_file ) if corr_data_raw . shape [ 1 ] == 3 : A = ( corr_data_raw [ : , 0 ] / 1e4 ) . astype ( int ) B = ( corr_data_raw [ : , 0 ] % 1e4 ) . astype ( int ) M = ( corr_data_raw [ : , 1 ] / 1e4 ) . astype ( int ) N = ( corr_data_raw [ : , 1 ] % 1e4 ) . astype ( int ) corr_data = np . vstack ( ( A , B , M , N , corr_data_raw [ : , 2 ] ) ) . T elif corr_data_raw . shape [ 1 ] == 5 : corr_data = corr_data_raw else : raise Exception ( 'error' ) corr_data [ : , 0 : 2 ] = np . sort ( corr_data [ : , 0 : 2 ] , axis = 1 ) corr_data [ : , 2 : 4 ] = np . sort ( corr_data [ : , 2 : 4 ] , axis = 1 ) if 'frequency' not in df . columns : raise Exception ( 'No frequency data found. Are you sure this is a seit data set?' ) df = df . reset_index ( ) gf = df . groupby ( [ 'a' , 'b' , 'm' , 'n' ] ) for key , item in gf . indices . items ( ) : # print('key', key) # print(item) item_norm = np . hstack ( ( np . sort ( key [ 0 : 2 ] ) , np . sort ( key [ 2 : 4 ] ) ) ) # print(item_norm) index = np . where ( ( corr_data [ : , 0 ] == item_norm [ 0 ] ) & ( corr_data [ : , 1 ] == item_norm [ 1 ] ) & ( corr_data [ : , 2 ] == item_norm [ 2 ] ) & ( corr_data [ : , 3 ] == item_norm [ 3 ] ) ) [ 0 ] # print(index, corr_data[index]) if len ( index ) == 0 : print ( key ) import IPython IPython . embed ( ) raise Exception ( 'No correction factor found for this configuration' ) factor = corr_data [ index , 4 ] # if key == (1, 4, 2, 3): # print(key) # print(factor) # print(df['R']) # print(df['k']) # import IPython # IPython.embed() # exit() # apply correction factor for col in ( 'r' , 'Zt' , 'Vmn' , 'rho_a' ) : if col in df . columns : df . ix [ item , col ] *= factor df . ix [ item , 'corr_fac' ] = factor return df , corr_data | Apply correction factors for a pseudo - 2D measurement setup . See Weigand and Kemna 2017 Biogeosciences for detailed information . | 726 | 29 |
8,435 | def get_pij_method ( model = F81 , frequencies = None , kappa = None ) : if is_f81_like ( model ) : mu = get_mu ( frequencies ) return lambda t : get_f81_pij ( t , frequencies , mu ) if JTT == model : return get_jtt_pij if HKY == model : return lambda t : get_hky_pij ( t , frequencies , kappa ) | Returns a function for calculation of probability matrix of substitutions i - > j over time t . | 99 | 19 |
8,436 | def initialize_allowed_states ( tree , feature , states ) : allowed_states_feature = get_personalized_feature_name ( feature , ALLOWED_STATES ) state2index = dict ( zip ( states , range ( len ( states ) ) ) ) for node in tree . traverse ( ) : node_states = getattr ( node , feature , set ( ) ) if not node_states : allowed_states = np . ones ( len ( state2index ) , dtype = np . int ) else : allowed_states = np . zeros ( len ( state2index ) , dtype = np . int ) for state in node_states : allowed_states [ state2index [ state ] ] = 1 node . add_feature ( allowed_states_feature , allowed_states ) | Initializes the allowed state arrays for tips based on their states given by the feature . | 170 | 17 |
8,437 | def alter_zero_tip_allowed_states ( tree , feature ) : zero_parent2tips = defaultdict ( list ) allowed_state_feature = get_personalized_feature_name ( feature , ALLOWED_STATES ) for tip in tree : if tip . dist == 0 : state = getattr ( tip , feature , None ) if state is not None and state != '' : zero_parent2tips [ tip . up ] . append ( tip ) # adjust zero tips to contain all the zero tip options as states for parent , zero_tips in zero_parent2tips . items ( ) : # If there is a common state do nothing counts = None for tip in zero_tips : if counts is None : counts = getattr ( tip , allowed_state_feature ) . copy ( ) else : counts += getattr ( tip , allowed_state_feature ) if counts . max ( ) == len ( zero_tips ) : continue # Otherwise set all tip states to state union allowed_states = None for tip in zero_tips : if allowed_states is None : allowed_states = getattr ( tip , allowed_state_feature ) . copy ( ) else : tip_allowed_states = getattr ( tip , allowed_state_feature ) allowed_states [ np . nonzero ( tip_allowed_states ) ] = 1 tip . add_feature ( allowed_state_feature , allowed_states ) | Alters the bottom - up likelihood arrays for zero - distance tips to make sure they do not contradict with other zero - distance tip siblings . | 300 | 28 |
8,438 | def unalter_zero_tip_allowed_states ( tree , feature , state2index ) : allowed_state_feature = get_personalized_feature_name ( feature , ALLOWED_STATES ) for tip in tree : if tip . dist > 0 : continue state = getattr ( tip , feature , set ( ) ) if state : initial_allowed_states = np . zeros ( len ( state2index ) , np . int ) for _ in state : initial_allowed_states [ state2index [ _ ] ] = 1 allowed_states = getattr ( tip , allowed_state_feature ) & initial_allowed_states tip . add_feature ( allowed_state_feature , ( allowed_states if np . any ( allowed_states > 0 ) else initial_allowed_states ) ) | Unalters the bottom - up likelihood arrays for zero - distance tips to contain ones only in their states . | 172 | 22 |
8,439 | def unalter_zero_tip_joint_states ( tree , feature , state2index ) : lh_joint_state_feature = get_personalized_feature_name ( feature , BU_LH_JOINT_STATES ) for tip in tree : if tip . dist > 0 : continue state = getattr ( tip , feature , set ( ) ) if len ( state ) > 1 : allowed_indices = { state2index [ _ ] for _ in state } allowed_index = next ( iter ( allowed_indices ) ) joint_states = getattr ( tip , lh_joint_state_feature ) for i in range ( len ( state2index ) ) : if joint_states [ i ] not in allowed_indices : joint_states [ i ] = allowed_index elif len ( state ) == 1 : tip . add_feature ( lh_joint_state_feature , np . ones ( len ( state2index ) , np . int ) * state2index [ next ( iter ( state ) ) ] ) | Unalters the joint tip states for zero - distance tips to contain only their states . | 229 | 18 |
8,440 | def calculate_marginal_likelihoods ( tree , feature , frequencies ) : bu_lh_feature = get_personalized_feature_name ( feature , BU_LH ) bu_lh_sf_feature = get_personalized_feature_name ( feature , BU_LH_SF ) td_lh_feature = get_personalized_feature_name ( feature , TD_LH ) td_lh_sf_feature = get_personalized_feature_name ( feature , TD_LH_SF ) lh_feature = get_personalized_feature_name ( feature , LH ) lh_sf_feature = get_personalized_feature_name ( feature , LH_SF ) allowed_state_feature = get_personalized_feature_name ( feature , ALLOWED_STATES ) for node in tree . traverse ( 'preorder' ) : likelihood = getattr ( node , bu_lh_feature ) * getattr ( node , td_lh_feature ) * frequencies * getattr ( node , allowed_state_feature ) node . add_feature ( lh_feature , likelihood ) node . add_feature ( lh_sf_feature , getattr ( node , td_lh_sf_feature ) + getattr ( node , bu_lh_sf_feature ) ) node . del_feature ( bu_lh_feature ) node . del_feature ( bu_lh_sf_feature ) node . del_feature ( td_lh_feature ) node . del_feature ( td_lh_sf_feature ) | Calculates marginal likelihoods for each tree node by multiplying state frequencies with their bottom - up and top - down likelihoods . | 347 | 26 |
8,441 | def convert_likelihoods_to_probabilities ( tree , feature , states ) : lh_feature = get_personalized_feature_name ( feature , LH ) name2probs = { } for node in tree . traverse ( ) : lh = getattr ( node , lh_feature ) name2probs [ node . name ] = lh / lh . sum ( ) return pd . DataFrame . from_dict ( name2probs , orient = 'index' , columns = states ) | Normalizes each node marginal likelihoods to convert them to marginal probabilities . | 112 | 14 |
8,442 | def choose_ancestral_states_mppa ( tree , feature , states , force_joint = True ) : lh_feature = get_personalized_feature_name ( feature , LH ) allowed_state_feature = get_personalized_feature_name ( feature , ALLOWED_STATES ) joint_state_feature = get_personalized_feature_name ( feature , JOINT_STATE ) n = len ( states ) _ , state2array = get_state2allowed_states ( states , False ) num_scenarios = 1 unresolved_nodes = 0 num_states = 0 # If force_joint == True, # we make sure that the joint state is always chosen, # for this we sort the marginal probabilities array as [lowest_non_joint_mp, ..., highest_non_joint_mp, joint_mp] # select k in 1:n such as the correction between choosing 0, 0, ..., 1/k, ..., 1/k and our sorted array is min # and return the corresponding states for node in tree . traverse ( ) : marginal_likelihoods = getattr ( node , lh_feature ) marginal_probs = marginal_likelihoods / marginal_likelihoods . sum ( ) if force_joint : joint_index = getattr ( node , joint_state_feature ) joint_prob = marginal_probs [ joint_index ] marginal_probs = np . hstack ( ( np . sort ( np . delete ( marginal_probs , joint_index ) ) , [ joint_prob ] ) ) else : marginal_probs = np . sort ( marginal_probs ) best_k = n best_correstion = np . inf for k in range ( 1 , n + 1 ) : correction = np . hstack ( ( np . zeros ( n - k ) , np . ones ( k ) / k ) ) - marginal_probs correction = correction . dot ( correction ) if correction < best_correstion : best_correstion = correction best_k = k num_scenarios *= best_k num_states += best_k if force_joint : indices_selected = sorted ( range ( n ) , key = lambda _ : ( 0 if n == joint_index else 1 , - marginal_likelihoods [ _ ] ) ) [ : best_k ] else : indices_selected = sorted ( range ( n ) , key = lambda _ : - marginal_likelihoods [ _ ] ) [ : best_k ] if best_k == 1 : allowed_states = state2array [ indices_selected [ 0 ] ] else : allowed_states = np . zeros ( len ( states ) , dtype = np . int ) allowed_states [ indices_selected ] = 1 unresolved_nodes += 1 node . add_feature ( allowed_state_feature , allowed_states ) return num_scenarios , unresolved_nodes , num_states | Chooses node ancestral states based on their marginal probabilities using MPPA method . | 644 | 15 |
8,443 | def choose_ancestral_states_map ( tree , feature , states ) : lh_feature = get_personalized_feature_name ( feature , LH ) allowed_state_feature = get_personalized_feature_name ( feature , ALLOWED_STATES ) _ , state2array = get_state2allowed_states ( states , False ) for node in tree . traverse ( ) : marginal_likelihoods = getattr ( node , lh_feature ) node . add_feature ( allowed_state_feature , state2array [ marginal_likelihoods . argmax ( ) ] ) | Chooses node ancestral states based on their marginal probabilities using MAP method . | 131 | 14 |
8,444 | def choose_ancestral_states_joint ( tree , feature , states , frequencies ) : lh_feature = get_personalized_feature_name ( feature , BU_LH ) lh_state_feature = get_personalized_feature_name ( feature , BU_LH_JOINT_STATES ) allowed_state_feature = get_personalized_feature_name ( feature , ALLOWED_STATES ) joint_state_feature = get_personalized_feature_name ( feature , JOINT_STATE ) _ , state2array = get_state2allowed_states ( states , False ) def chose_consistent_state ( node , state_index ) : node . add_feature ( joint_state_feature , state_index ) node . add_feature ( allowed_state_feature , state2array [ state_index ] ) for child in node . children : chose_consistent_state ( child , getattr ( child , lh_state_feature ) [ state_index ] ) chose_consistent_state ( tree , ( getattr ( tree , lh_feature ) * frequencies ) . argmax ( ) ) | Chooses node ancestral states based on their marginal probabilities using joint method . | 250 | 14 |
8,445 | def col_name2cat ( column ) : column_string = '' . join ( s for s in column . replace ( ' ' , '_' ) if s . isalnum ( ) or '_' == s ) return column_string | Reformats the column string to make sure it contains only numerical letter characters or underscore . | 52 | 18 |
8,446 | def get_user_config_filename ( appname = 'notify' ) : import platform system = platform . system ( ) if system == 'Windows' : rootname = os . path . join ( os . environ [ 'APPDATA' ] , appname ) filename = appname + ".cfg" prefix = '' elif system == 'Linux' : XDG_CONFIG_HOME = os . environ . get ( 'XDG_CONFIG_HOME' , None ) rootname = XDG_CONFIG_HOME or os . path . join ( '~' , '.config' ) rootname = os . path . expanduser ( rootname ) # check if XDG_CONFIG_HOME exists if not os . path . exists ( rootname ) and XDG_CONFIG_HOME is None : # XDG_CONFIG_HOME is not used rootname = os . path . expanduser ( '~' ) filename = appname + ".cfg" prefix = '.' else : rootname = os . path . join ( rootname , appname ) filename = appname + ".cfg" prefix = '' elif system == 'Darwin' : rootname = os . path . expanduser ( '~' ) filename = appname + ".cfg" prefix = '.' else : # Unknown rootname = os . path . expanduser ( '~' ) filename = appname + ".cfg" prefix = '' return os . path . join ( rootname , prefix + filename ) | Get user config filename . | 319 | 5 |
8,447 | def config_to_options ( config ) : class Options : host = config . get ( 'smtp' , 'host' , raw = True ) port = config . getint ( 'smtp' , 'port' ) to_addr = config . get ( 'mail' , 'to_addr' , raw = True ) from_addr = config . get ( 'mail' , 'from_addr' , raw = True ) subject = config . get ( 'mail' , 'subject' , raw = True ) encoding = config . get ( 'mail' , 'encoding' , raw = True ) username = config . get ( 'auth' , 'username' ) opts = Options ( ) # format opts . from_addr % { 'host' : opts . host , 'prog' : 'notify' } opts . to_addr % { 'host' : opts . host , 'prog' : 'notify' } return opts | Convert ConfigParser instance to argparse . Namespace | 208 | 11 |
8,448 | def create_default_config ( ) : import codecs config = ConfigParser . SafeConfigParser ( ) config . readfp ( StringIO ( DEFAULT_CONFIG ) ) # Load user settings filename = get_user_config_filename ( ) if not os . path . exists ( filename ) : from wizard import setup_wizard setup_wizard ( config ) else : try : fi = codecs . open ( filename , 'r' , encoding = 'utf-8' ) config . readfp ( fi ) finally : fi . close ( ) return config | Create default ConfigParser instance | 118 | 5 |
8,449 | def has_multiple_timesteps ( data ) : if "timestep" in data . keys ( ) : if len ( np . unique ( data [ "timestep" ] ) ) > 1 : return True return False | Return True if data container has multiple timesteps . | 49 | 11 |
8,450 | def split_timesteps ( data , consistent_abmn = False ) : if has_multiple_timesteps ( data ) : grouped = data . groupby ( "timestep" ) return [ group [ 1 ] for group in grouped ] else : return data | Split data into multiple timesteps . | 57 | 8 |
8,451 | def parse ( text ) : # Sanitize text case to meet phonetic comparison standards fixed_text = validate . fix_string_case ( utf ( text ) ) # prepare output list output = [ ] # cursor end point cur_end = 0 # iterate through input text for cur , i in enumerate ( fixed_text ) : # Trap characters with unicode encoding errors try : i . encode ( 'utf-8' ) except UnicodeDecodeError : uni_pass = False else : uni_pass = True # Default value for match match = { 'matched' : False } # Check cur is greater than or equals cur_end. If cursor is in # a position that has alread been processed/replaced, we don't # process anything at all if not uni_pass : cur_end = cur + 1 output . append ( i ) elif cur >= cur_end and uni_pass : # Try looking in non rule patterns with current string portion match = match_non_rule_patterns ( fixed_text , cur ) # Check if non rule patterns have matched if match [ "matched" ] : output . append ( match [ "replaced" ] ) cur_end = cur + len ( match [ "found" ] ) else : # if non rule patterns have not matched, try rule patterns match = match_rule_patterns ( fixed_text , cur ) # Check if rule patterns have matched if match [ "matched" ] : # Update cur_end as cursor + length of match found cur_end = cur + len ( match [ "found" ] ) # Process its rules replaced = process_rules ( rules = match [ "rules" ] , fixed_text = fixed_text , cur = cur , cur_end = cur_end ) # If any rules match, output replacement from the # rule, else output it's default top-level/default # replacement if replaced is not None : # Rule has matched output . append ( replaced ) else : # No rules have matched # output common match output . append ( match [ "replaced" ] ) # If none matched, append present cursor value if not match [ "matched" ] : cur_end = cur + 1 output . append ( i ) # End looping through input text and produce output return '' . join ( output ) | Parses input text matches and replaces using avrodict | 489 | 12 |
8,452 | def match_non_rule_patterns ( fixed_text , cur = 0 ) : pattern = exact_find_in_pattern ( fixed_text , cur , NON_RULE_PATTERNS ) if len ( pattern ) > 0 : return { "matched" : True , "found" : pattern [ 0 ] [ 'find' ] , "replaced" : pattern [ 0 ] [ 'replace' ] } else : return { "matched" : False , "found" : None , "replaced" : fixed_text [ cur ] } | Matches given text at cursor position with non rule patterns | 118 | 11 |
8,453 | def match_rule_patterns ( fixed_text , cur = 0 ) : pattern = exact_find_in_pattern ( fixed_text , cur , RULE_PATTERNS ) # if len(pattern) == 1: if len ( pattern ) > 0 : return { "matched" : True , "found" : pattern [ 0 ] [ 'find' ] , "replaced" : pattern [ 0 ] [ 'replace' ] , "rules" : pattern [ 0 ] [ 'rules' ] } else : return { "matched" : False , "found" : None , "replaced" : fixed_text [ cur ] , "rules" : None } | Matches given text at cursor position with rule patterns | 143 | 10 |
8,454 | def exact_find_in_pattern ( fixed_text , cur = 0 , patterns = PATTERNS ) : return [ x for x in patterns if ( cur + len ( x [ 'find' ] ) <= len ( fixed_text ) ) and x [ 'find' ] == fixed_text [ cur : ( cur + len ( x [ 'find' ] ) ) ] ] | Returns pattern items that match given text cur position and pattern | 81 | 11 |
8,455 | def process_rules ( rules , fixed_text , cur = 0 , cur_end = 1 ) : replaced = '' # iterate through rules for rule in rules : matched = False # iterate through matches for match in rule [ 'matches' ] : matched = process_match ( match , fixed_text , cur , cur_end ) # Break out of loop if we dont' have a match. Here we are # trusting avrodict to have listed matches sequentially if not matched : break # If a match is found, stop looping through rules any further if matched : replaced = rule [ 'replace' ] break # if any match has been found return replace value if matched : return replaced else : return None | Process rules matched in pattern and returns suitable replacement | 149 | 9 |
8,456 | def process_match ( match , fixed_text , cur , cur_end ) : # Set our tools # -- Initial/default value for replace replace = True # -- Set check cursor depending on match['type'] if match [ 'type' ] == 'prefix' : chk = cur - 1 else : # suffix chk = cur_end # -- Set scope based on whether scope is negative if match [ 'scope' ] . startswith ( '!' ) : scope = match [ 'scope' ] [ 1 : ] negative = True else : scope = match [ 'scope' ] negative = False # Let the matching begin # -- Punctuations if scope == 'punctuation' : # Conditions: XORd with negative if ( not ( ( chk < 0 and match [ 'type' ] == 'prefix' ) or ( chk >= len ( fixed_text ) and match [ 'type' ] == 'suffix' ) or validate . is_punctuation ( fixed_text [ chk ] ) ) ^ negative ) : replace = False # -- Vowels -- Checks: 1. Cursor should not be at first character # -- if prefix or last character if suffix, 2. Character at chk # -- should be a vowel. 3. 'negative' will invert the value of 1 # -- AND 2 elif scope == 'vowel' : if ( not ( ( ( chk >= 0 and match [ 'type' ] == 'prefix' ) or ( chk < len ( fixed_text ) and match [ 'type' ] == 'suffix' ) ) and validate . is_vowel ( fixed_text [ chk ] ) ) ^ negative ) : replace = False # -- Consonants -- Checks: 1. Cursor should not be at first # -- character if prefix or last character if suffix, 2. Character # -- at chk should be a consonant. 3. 'negative' will invert the # -- value of 1 AND 2 elif scope == 'consonant' : if ( not ( ( ( chk >= 0 and match [ 'type' ] == 'prefix' ) or ( chk < len ( fixed_text ) and match [ 'type' ] == 'suffix' ) ) and validate . is_consonant ( fixed_text [ chk ] ) ) ^ negative ) : replace = False # -- Exacts elif scope == 'exact' : # Prepare cursor for exact search if match [ 'type' ] == 'prefix' : exact_start = cur - len ( match [ 'value' ] ) exact_end = cur else : # suffix exact_start = cur_end exact_end = cur_end + len ( match [ 'value' ] ) # Validate exact find. if not validate . is_exact ( match [ 'value' ] , fixed_text , exact_start , exact_end , negative ) : replace = False # Return replace, which will be true if none of the checks above match return replace | Processes a single match in rules | 638 | 7 |
8,457 | def cli ( ctx , hostname , username , password , config_dir , https ) : ctx . is_root = True ctx . user_values_entered = False ctx . config_dir = os . path . abspath ( os . path . expanduser ( config_dir ) ) ctx . config = load_config ( ctx ) ctx . hostname = hostname ctx . username = username ctx . password = password ctx . https = https # Creating the WVA object is deferred as some commands like clearconfig # should not require a username/password to perform them ctx . wva = None | Command - line interface for interacting with a WVA device | 136 | 11 |
8,458 | def get ( ctx , uri ) : http_client = get_wva ( ctx ) . get_http_client ( ) cli_pprint ( http_client . get ( uri ) ) | Perform an HTTP GET of the provided URI | 46 | 9 |
8,459 | def delete ( ctx , uri ) : http_client = get_wva ( ctx ) . get_http_client ( ) cli_pprint ( http_client . delete ( uri ) ) | DELETE the specified URI | 46 | 6 |
8,460 | def post ( ctx , uri , input_file ) : http_client = get_wva ( ctx ) . get_http_client ( ) cli_pprint ( http_client . post ( uri , input_file . read ( ) ) ) | POST file data to a specific URI | 58 | 7 |
8,461 | def sample ( ctx , element , timestamp , repeat , delay ) : element = get_wva ( ctx ) . get_vehicle_data_element ( element ) for i in xrange ( repeat ) : curval = element . sample ( ) if timestamp : print ( "{} at {}" . format ( curval . value , curval . timestamp . ctime ( ) ) ) else : print ( "{}" . format ( curval . value ) ) if i + 1 < repeat : # do not delay on last iteration time . sleep ( delay ) | Sample the value of a vehicle data element | 118 | 8 |
8,462 | def list ( ctx ) : wva = get_wva ( ctx ) for subscription in wva . get_subscriptions ( ) : print ( subscription . short_name ) | List short name of all current subscriptions | 40 | 7 |
8,463 | def delete ( ctx , short_name ) : wva = get_wva ( ctx ) subscription = wva . get_subscription ( short_name ) subscription . delete ( ) | Delete a specific subscription by short name | 41 | 7 |
8,464 | def clear ( ctx ) : wva = get_wva ( ctx ) for subscription in wva . get_subscriptions ( ) : sys . stdout . write ( "Deleting {}... " . format ( subscription . short_name ) ) sys . stdout . flush ( ) subscription . delete ( ) print ( "Done" ) | Remove all registered subscriptions | 75 | 4 |
8,465 | def show ( ctx , short_name ) : wva = get_wva ( ctx ) subscription = wva . get_subscription ( short_name ) cli_pprint ( subscription . get_metadata ( ) ) | Show metadata for a specific subscription | 50 | 6 |
8,466 | def add ( ctx , short_name , uri , interval , buffer ) : wva = get_wva ( ctx ) subscription = wva . get_subscription ( short_name ) subscription . create ( uri , buffer , interval ) | Add a subscription with a given short_name for a given uri | 54 | 14 |
8,467 | def listen ( ctx ) : wva = get_wva ( ctx ) es = wva . get_event_stream ( ) def cb ( event ) : cli_pprint ( event ) es . add_event_listener ( cb ) es . enable ( ) while True : time . sleep ( 5 ) | Output the contents of the WVA event stream | 71 | 9 |
8,468 | def graph ( ctx , items , seconds , ylim ) : wva = get_wva ( ctx ) es = wva . get_event_stream ( ) try : from wva import grapher except ImportError : print ( "Unable to graph... you must have matplotlib installed" ) else : stream_grapher = grapher . WVAStreamGrapher ( wva , items , seconds = seconds , ylim = ylim ) es . enable ( ) stream_grapher . run ( ) | Present a live graph of the incoming streaming data | 113 | 9 |
8,469 | def authorize ( ctx , public_key , append ) : wva = get_wva ( ctx ) http_client = wva . get_http_client ( ) authorized_keys_uri = "/files/userfs/WEB/python/.ssh/authorized_keys" authorized_key_contents = public_key if append : try : existing_contents = http_client . get ( authorized_keys_uri ) authorized_key_contents = "{}\n{}" . format ( existing_contents , public_key ) except WVAHttpNotFoundError : pass # file doesn't exist, just write the public key http_client . put ( authorized_keys_uri , authorized_key_contents ) print ( "Public key written to authorized_keys for python user." ) print ( "You should now be able to ssh to the device by doing the following:" ) print ( "" ) print ( " $ ssh python@{}" . format ( get_root_ctx ( ctx ) . hostname ) ) | Enable ssh login as the Python user for the current user | 220 | 11 |
8,470 | def name_tree ( tree ) : existing_names = Counter ( ( _ . name for _ in tree . traverse ( ) if _ . name ) ) if sum ( 1 for _ in tree . traverse ( ) ) == len ( existing_names ) : return i = 0 existing_names = Counter ( ) for node in tree . traverse ( 'preorder' ) : name = node . name if node . is_leaf ( ) else ( 'root' if node . is_root ( ) else None ) while name is None or name in existing_names : name = '{}{}' . format ( 't' if node . is_leaf ( ) else 'n' , i ) i += 1 node . name = name existing_names [ name ] += 1 | Names all the tree nodes that are not named or have non - unique names with unique names . | 161 | 19 |
8,471 | def enable_result_transforms ( func ) : @ functools . wraps ( func ) def wrapper ( * args , * * kwargs ) : func_transformator = kwargs . pop ( 'electrode_transformator' , None ) data , electrodes , topography = func ( * args , * * kwargs ) if func_transformator is not None : data_transformed , electrodes_transformed , topography_transformed = func_transformator . transform ( data , electrodes , topography ) return data_transformed , electrodes_transformed , topography_transformed else : return data , electrodes , topography return wrapper | Decorator that tries to use the object provided using a kwarg called electrode_transformator to transform the return values of an import function . It is intended to be used to transform electrode numbers and locations i . e . for use in roll - along - measurement schemes . | 139 | 56 |
8,472 | def record_path ( self ) : if self . record_button . get_property ( 'active' ) and ( self . record_path_selector . selected_path ) : return self . record_path_selector . selected_path else : return None | If recording is not enabled return None as record path . | 56 | 11 |
8,473 | def _write_crmod_file ( filename ) : crmod_lines = [ '***FILES***' , '../grid/elem.dat' , '../grid/elec.dat' , '../rho/rho.dat' , '../config/config.dat' , 'F ! potentials ?' , '../mod/pot/pot.dat' , 'T ! measurements ?' , '../mod/volt.dat' , 'F ! sensitivities ?' , '../mod/sens/sens.dat' , 'F ! another dataset ?' , '1 ! 2D (=0) or 2.5D (=1)' , 'F ! fictitious sink ?' , '1660 ! fictitious sink node number' , 'F ! boundary values ?' , 'boundary.dat' , ] with open ( filename , 'w' ) as fid : [ fid . write ( line + '\n' ) for line in crmod_lines ] | Write a valid crmod configuration file to filename . | 212 | 10 |
8,474 | def utf ( text ) : try : output = unicode ( text , encoding = 'utf-8' ) except UnicodeDecodeError : output = text except TypeError : output = text return output | Shortcut funnction for encoding given text with utf - 8 | 42 | 13 |
8,475 | def check_bom ( file ) : # try to read first three bytes lead = file . read ( 3 ) if len ( lead ) == 3 and lead == codecs . BOM_UTF8 : # UTF-8, position is already OK, use canonical name return codecs . lookup ( 'utf-8' ) . name elif len ( lead ) >= 2 and lead [ : 2 ] == codecs . BOM_UTF16_BE : # need to backup one character if len ( lead ) == 3 : file . seek ( - 1 , os . SEEK_CUR ) return codecs . lookup ( 'utf-16-be' ) . name elif len ( lead ) >= 2 and lead [ : 2 ] == codecs . BOM_UTF16_LE : # need to backup one character if len ( lead ) == 3 : file . seek ( - 1 , os . SEEK_CUR ) return codecs . lookup ( 'utf-16-le' ) . name else : # no BOM, rewind file . seek ( - len ( lead ) , os . SEEK_CUR ) return None | Determines file codec from from its BOM record . | 241 | 12 |
8,476 | def guess_lineno ( file ) : offset = file . tell ( ) file . seek ( 0 ) startpos = 0 lineno = 1 # looks like file.read() return bytes in python3 # so I need more complicated algorithm here while True : line = file . readline ( ) if not line : break endpos = file . tell ( ) if startpos <= offset < endpos : break lineno += 1 file . seek ( offset ) return lineno | Guess current line number in a file . | 97 | 9 |
8,477 | def search ( query ) : params = { 's.cmd' : 'setTextQuery(%s)setPageSize(50)setHoldingsOnly(true)' % query } return requests . get ( BASE_URL , params = params , timeout = 10 ) . json ( ) | Search Penn Libraries Franklin for documents The maximum pagesize currently is 50 . | 60 | 14 |
8,478 | def make_record ( level , xref_id , tag , value , sub_records , offset , dialect , parser = None ) : # value can be bytes or string so we check for both, 64 is code for '@' if value and len ( value ) > 2 and ( ( value [ 0 ] == '@' and value [ - 1 ] == '@' ) or ( value [ 0 ] == 64 and value [ - 1 ] == 64 ) ) : # this looks like a <pointer>, make a Pointer record klass = Pointer rec = klass ( parser ) else : klass = _tag_class . get ( tag , Record ) rec = klass ( ) rec . level = level rec . xref_id = xref_id rec . tag = tag rec . value = value rec . sub_records = sub_records rec . offset = offset rec . dialect = dialect return rec | Create Record instance based on parameters . | 196 | 7 |
8,479 | def sub_tag ( self , path , follow = True ) : tags = path . split ( '/' ) rec = self for tag in tags : recs = [ x for x in ( rec . sub_records or [ ] ) if x . tag == tag ] if not recs : return None rec = recs [ 0 ] if follow and isinstance ( rec , Pointer ) : rec = rec . ref return rec | Returns direct sub - record with given tag name or None . | 90 | 12 |
8,480 | def sub_tag_value ( self , path , follow = True ) : rec = self . sub_tag ( path , follow ) if rec : return rec . value return None | Returns value of a direct sub - record or None . | 37 | 11 |
8,481 | def sub_tags ( self , * tags , * * kw ) : records = [ x for x in self . sub_records if x . tag in tags ] if kw . get ( 'follow' , True ) : records = [ rec . ref if isinstance ( rec , Pointer ) else rec for rec in records ] return records | Returns list of direct sub - records matching any tag name . | 73 | 12 |
8,482 | def freeze ( self ) : # None is the same as empty string if self . value is None : self . value = "" if self . dialect in [ DIALECT_ALTREE ] : name_tuple = parse_name_altree ( self ) elif self . dialect in [ DIALECT_MYHERITAGE ] : name_tuple = parse_name_myher ( self ) elif self . dialect in [ DIALECT_ANCESTRIS ] : name_tuple = parse_name_ancestris ( self ) else : name_tuple = split_name ( self . value ) self . value = name_tuple return self | Method called by parser when updates to this record finish . | 142 | 11 |
8,483 | def given ( self ) : if self . _primary . value [ 0 ] and self . _primary . value [ 2 ] : return self . _primary . value [ 0 ] + ' ' + self . _primary . value [ 2 ] return self . _primary . value [ 0 ] or self . _primary . value [ 2 ] | Given name could include both first and middle name | 70 | 9 |
8,484 | def maiden ( self ) : if self . _dialect == DIALECT_DEFAULT : # for default/unknown dialect try "maiden" name record first for name in self . _names : if name . type == "maiden" : return name . value [ 1 ] # rely on NameRec extracting it from other source if self . _primary and len ( self . _primary . value ) > 3 : return self . _primary . value [ 3 ] return None | Maiden last name can be None | 99 | 7 |
8,485 | def order ( self , order ) : given = self . given surname = self . surname if order in ( ORDER_MAIDEN_GIVEN , ORDER_GIVEN_MAIDEN ) : surname = self . maiden or self . surname # We are collating empty names to come after non-empty, # so instead of empty we return "2" and add "1" as prefix to others given = ( "1" + given ) if given else "2" surname = ( "1" + surname ) if surname else "2" if order in ( ORDER_SURNAME_GIVEN , ORDER_MAIDEN_GIVEN ) : return ( surname , given ) elif order in ( ORDER_GIVEN_SURNAME , ORDER_GIVEN_MAIDEN ) : return ( given , surname ) else : raise ValueError ( "unexpected order: {}" . format ( order ) ) | Returns name order key . | 197 | 5 |
8,486 | def format ( self ) : name = self . _primary . value [ 0 ] if self . surname : if name : name += ' ' name += self . surname if self . _primary . value [ 2 ] : if name : name += ' ' name += self . _primary . value [ 2 ] return name | Format name for output . | 65 | 5 |
8,487 | def match ( self , xn ) : if all ( map ( lambda x : x . match ( xn ) , self . conditions ) ) : return self . outcomes return None | Processes a transaction against this rule | 37 | 7 |
8,488 | def import_sip04_data_all ( data_filename ) : filename , fformat = os . path . splitext ( data_filename ) if fformat == '.csv' : print ( 'Import SIP04 data from .csv file' ) df_all = _import_csv_file ( data_filename ) elif fformat == '.mat' : print ( 'Import SIP04 data from .mat file' ) df_all = _import_mat_file ( data_filename ) else : print ( 'Please use .csv or .mat format.' ) df_all = None return df_all | Import ALL data from the result files | 132 | 7 |
8,489 | def init_session ( db_url = None , echo = False , engine = None , settings = None ) : if engine is None : engine = init_engine ( db_url = db_url , echo = echo , settings = settings ) return sessionmaker ( bind = engine ) | A SQLAlchemy Session requires that an engine be initialized if one isn t provided . | 59 | 17 |
8,490 | def import_sip256c ( self , filename , settings = None , reciprocal = None , * * kwargs ) : if settings is None : settings = { } # we get not electrode positions (dummy1) and no topography data # (dummy2) df , dummy1 , dummy2 = reda_sip256c . parse_radic_file ( filename , settings , reciprocal = reciprocal , * * kwargs ) self . _add_to_container ( df ) print ( 'Summary:' ) self . _describe_data ( df ) | Radic SIP256c data import | 122 | 8 |
8,491 | def import_eit_fzj ( self , filename , configfile , correction_file = None , timestep = None , * * kwargs ) : # we get not electrode positions (dummy1) and no topography data # (dummy2) df_emd , dummy1 , dummy2 = eit_fzj . read_3p_data ( filename , configfile , * * kwargs ) if correction_file is not None : eit_fzj_utils . apply_correction_factors ( df_emd , correction_file ) if timestep is not None : df_emd [ 'timestep' ] = timestep self . _add_to_container ( df_emd ) print ( 'Summary:' ) self . _describe_data ( df_emd ) | EIT data import for FZJ Medusa systems | 184 | 11 |
8,492 | def check_dataframe ( self , dataframe ) : required_columns = ( 'a' , 'b' , 'm' , 'n' , 'r' , ) for column in required_columns : if column not in dataframe : raise Exception ( 'Required column not in dataframe: {0}' . format ( column ) ) | Check the given dataframe for the required columns | 75 | 9 |
8,493 | def query ( self , query , inplace = True ) : # TODO: add to queue result = self . data . query ( query , inplace = inplace ) return result | State what you want to keep | 38 | 6 |
8,494 | def remove_frequencies ( self , fmin , fmax ) : self . data . query ( 'frequency > {0} and frequency < {1}' . format ( fmin , fmax ) , inplace = True ) g = self . data . groupby ( 'frequency' ) print ( 'Remaining frequencies:' ) print ( sorted ( g . groups . keys ( ) ) ) | Remove frequencies from the dataset | 84 | 5 |
8,495 | def compute_K_analytical ( self , spacing ) : assert isinstance ( spacing , Number ) K = geometric_factors . compute_K_analytical ( self . data , spacing ) self . data = geometric_factors . apply_K ( self . data , K ) fix_sign_with_K ( self . data ) | Assuming an equal electrode spacing compute the K - factor over a homogeneous half - space . | 72 | 18 |
8,496 | def scatter_norrec ( self , filename = None , individual = False ) : # if not otherwise specified, use these column pairs: std_diff_labels = { 'r' : 'rdiff' , 'rpha' : 'rphadiff' , } diff_labels = std_diff_labels # check which columns are present in the data labels_to_use = { } for key , item in diff_labels . items ( ) : # only use if BOTH columns are present if key in self . data . columns and item in self . data . columns : labels_to_use [ key ] = item g_freq = self . data . groupby ( 'frequency' ) frequencies = list ( sorted ( g_freq . groups . keys ( ) ) ) if individual : figures = { } axes_all = { } else : Nx = len ( labels_to_use . keys ( ) ) Ny = len ( frequencies ) fig , axes = plt . subplots ( Ny , Nx , figsize = ( Nx * 2.5 , Ny * 2.5 ) ) for row , ( name , item ) in enumerate ( g_freq ) : if individual : fig , axes_row = plt . subplots ( 1 , 2 , figsize = ( 16 / 2.54 , 6 / 2.54 ) ) else : axes_row = axes [ row , : ] # loop over the various columns for col_nr , ( key , diff_column ) in enumerate ( sorted ( labels_to_use . items ( ) ) ) : indices = np . where ( ~ np . isnan ( item [ diff_column ] ) ) [ 0 ] ax = axes_row [ col_nr ] ax . scatter ( item [ key ] , item [ diff_column ] , ) ax . set_xlabel ( key ) ax . set_ylabel ( diff_column ) ax . set_title ( 'N: {}' . format ( len ( indices ) ) ) if individual : fig . tight_layout ( ) figures [ name ] = fig axes_all [ name ] = axes_row if individual : return figures , axes_all else : fig . tight_layout ( ) return fig , axes | Create a scatter plot for all diff pairs | 481 | 8 |
8,497 | def get_spectrum ( self , nr_id = None , abmn = None , plot_filename = None ) : assert nr_id is None or abmn is None # determine nr_id for given abmn tuple if abmn is not None : subdata = self . data . query ( 'a == {} and b == {} and m == {} and n == {}' . format ( * abmn ) ) . sort_values ( 'frequency' ) if subdata . shape [ 0 ] == 0 : return None , None # determine the norrec-id of this spectrum nr_id = subdata [ 'id' ] . iloc [ 0 ] # get spectra subdata_nor = self . data . query ( 'id == {} and norrec=="nor"' . format ( nr_id ) ) . sort_values ( 'frequency' ) subdata_rec = self . data . query ( 'id == {} and norrec=="rec"' . format ( nr_id ) ) . sort_values ( 'frequency' ) # create spectrum objects spectrum_nor = None spectrum_rec = None if subdata_nor . shape [ 0 ] > 0 : spectrum_nor = eis_plot . sip_response ( frequencies = subdata_nor [ 'frequency' ] . values , rmag = subdata_nor [ 'r' ] , rpha = subdata_nor [ 'rpha' ] , ) if subdata_rec . shape [ 0 ] > 0 : spectrum_rec = eis_plot . sip_response ( frequencies = subdata_rec [ 'frequency' ] . values , rmag = subdata_rec [ 'r' ] , rpha = subdata_rec [ 'rpha' ] , ) if plot_filename is not None : if spectrum_nor is not None : fig = spectrum_nor . plot ( plot_filename , reciprocal = spectrum_rec , return_fig = True , title = 'a: {} b: {} m: {}: n: {}' . format ( * subdata_nor [ [ 'a' , 'b' , 'm' , 'n' ] ] . values [ 0 , : ] ) ) return spectrum_nor , spectrum_rec , fig return spectrum_nor , spectrum_rec | Return a spectrum and its reciprocal counter part if present in the dataset . Optimally refer to the spectrum by its normal - reciprocal id . | 488 | 27 |
8,498 | def plot_all_spectra ( self , outdir ) : os . makedirs ( outdir , exist_ok = True ) g = self . data . groupby ( 'id' ) for nr , ( name , item ) in enumerate ( g ) : print ( 'Plotting spectrum with id {} ({} / {})' . format ( name , nr , len ( g . groups . keys ( ) ) ) ) plot_filename = '' . join ( ( outdir + os . sep , '{:04}_spectrum_id_{}.png' . format ( nr , name ) ) ) spec_nor , spec_rec , spec_fig = self . get_spectrum ( nr_id = name , plot_filename = plot_filename ) plt . close ( spec_fig ) | This is a convenience function to plot ALL spectra currently stored in the container . It is useful to asses whether data filters do perform correctly . | 175 | 28 |
8,499 | def plot_pseudosections ( self , column , filename = None , return_fig = False ) : assert column in self . data . columns g = self . data . groupby ( 'frequency' ) fig , axes = plt . subplots ( 4 , 2 , figsize = ( 15 / 2.54 , 20 / 2.54 ) , sharex = True , sharey = True ) for ax , ( key , item ) in zip ( axes . flat , g ) : fig , ax , cb = PS . plot_pseudosection_type2 ( item , ax = ax , column = column ) ax . set_title ( 'f: {} Hz' . format ( key ) ) fig . tight_layout ( ) if filename is not None : fig . savefig ( filename , dpi = 300 ) if return_fig : return fig else : plt . close ( fig ) | Create a multi - plot with one pseudosection for each frequency . | 192 | 14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.