idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
15,900 | def maxRange ( self ) : try : x , freqs = self . datafile . get_calibration ( str ( self . ui . calChoiceCmbbx . currentText ( ) ) , self . calf ) self . ui . frangeLowSpnbx . setValue ( freqs [ 0 ] ) self . ui . frangeHighSpnbx . setValue ( freqs [ - 1 ] ) print 'set freq range' , freqs [ 0 ] , freqs [ - 1 ] , freqs [ 0 ] , freqs [ - 1 ] except IOError : QtGui . QMessageBox . warning ( self , "File Read Error" , "Unable to read calibration file" ) except KeyError : QtGui . QMessageBox . warning ( self , "File Data Error" , "Unable to find data in file" ) | Sets the maximum range for the currently selection calibration determined from its range of values store on file | 188 | 19 |
15,901 | def plotCurve ( self ) : try : attenuations , freqs = self . datafile . get_calibration ( str ( self . ui . calChoiceCmbbx . currentText ( ) ) , self . calf ) self . pw = SimplePlotWidget ( freqs , attenuations , parent = self ) self . pw . setWindowFlags ( QtCore . Qt . Window ) self . pw . setLabels ( 'Frequency' , 'Attenuation' , 'Calibration Curve' ) self . pw . show ( ) except IOError : QtGui . QMessageBox . warning ( self , "File Read Error" , "Unable to read calibration file" ) except KeyError : QtGui . QMessageBox . warning ( self , "File Data Error" , "Unable to find data in file" ) | Shows a calibration curve in a separate window of the currently selected calibration | 184 | 14 |
15,902 | def values ( self ) : results = { } results [ 'use_calfile' ] = self . ui . calfileRadio . isChecked ( ) results [ 'calname' ] = str ( self . ui . calChoiceCmbbx . currentText ( ) ) results [ 'frange' ] = ( self . ui . frangeLowSpnbx . value ( ) , self . ui . frangeHighSpnbx . value ( ) ) return results | Gets the values the user input to this dialog | 105 | 10 |
15,903 | def conditional_accept ( self ) : if self . ui . calfileRadio . isChecked ( ) and str ( self . ui . calChoiceCmbbx . currentText ( ) ) == '' : self . ui . noneRadio . setChecked ( True ) if self . ui . calfileRadio . isChecked ( ) : try : x , freqs = self . datafile . get_calibration ( str ( self . ui . calChoiceCmbbx . currentText ( ) ) , self . calf ) except IOError : QtGui . QMessageBox . warning ( self , "File Read Error" , "Unable to read calibration file" ) return except KeyError : QtGui . QMessageBox . warning ( self , "File Data Error" , "Unable to find data in file" ) return if self . ui . frangeLowSpnbx . value ( ) < freqs [ 0 ] or self . ui . frangeHighSpnbx . value ( ) > freqs [ - 1 ] : QtGui . QMessageBox . warning ( self , "Invalid Frequency Range" , "Provided frequencys outside of calibration file range of {} - {} Hz" . format ( freqs [ 0 ] , freqs [ - 1 ] ) ) return self . accept ( ) | Accepts the inputs if all values are valid and congruent . i . e . Valid datafile and frequency range within the given calibration dataset . | 287 | 30 |
15,904 | def customized_warning ( message , category = UserWarning , filename = '' , lineno = - 1 , file = None , line = None ) : print ( "WARNING: {0}" . format ( message ) ) | Customized function to display warnings . Monkey patch for warnings . showwarning . | 45 | 15 |
15,905 | def read_cmdline ( ) : info = { "prog" : "Ellis" , "description" : "%(prog)s version {0}" . format ( __version__ ) , "epilog" : "For further help please head over to {0}" . format ( __url__ ) , "usage" : argparse . SUPPRESS , } argp = argparse . ArgumentParser ( * * info ) # Add an optional string argument 'config': argp . add_argument ( "-c" , "--config" , dest = 'config_file' , metavar = 'FILE' , help = "read configuration from FILE" , type = str ) # Parse command line: args = argp . parse_args ( ) return vars ( args ) | Parses optional command line arguments . | 168 | 8 |
15,906 | def main ( ) : # Monkey patch warnings.showwarning: warnings . showwarning = customized_warning # Read command line args, if any: args = read_cmdline ( ) # Configuration file, if given on the command line: config_file = args [ 'config_file' ] try : ellis = Ellis ( config_file ) except NoRuleError : msg = ( "There are no valid rules in the config file. " "Ellis can not run without rules." ) print_err ( msg ) else : ellis . start ( ) | Entry point for Ellis . | 116 | 5 |
15,907 | def shape ( self , shape = None ) : if shape is None : return self . _shape data , color = self . renderer . manager . set_shape ( self . model . id , shape ) self . model . data = data self . color = color self . _shape = shape | We need to shift buffers in order to change shape | 61 | 10 |
15,908 | def reply ( self , timeout = None ) : self . _wait_on_signal ( self . _response_received ) if self . _response_exception is not None : msg = self . _response_exception . message raise YamcsError ( msg ) return self . _response_reply | Returns the initial reply . This is emitted before any subscription data is emitted . This function raises an exception if the subscription attempt failed . | 64 | 26 |
15,909 | async def stop_bridges ( self ) : for task in self . sleep_tasks : task . cancel ( ) for bridge in self . bridges : bridge . stop ( ) | Stop all sleep tasks to allow bridges to end . | 38 | 10 |
15,910 | def str_to_date ( date : str ) -> datetime . datetime : date = date . split ( '.' ) date . reverse ( ) y , m , d = date return datetime . datetime ( int ( y ) , int ( m ) , int ( d ) ) | Convert cbr . ru API date ste to python datetime | 61 | 13 |
15,911 | def load ( self , data , size = None ) : self . bind ( ) if size is None : # ffi's sizeof understands arrays size = sizeof ( data ) if size == self . buffer_size : # same size - no need to allocate new buffer, just copy glBufferSubData ( self . array_type , 0 , size , to_raw_pointer ( data ) ) else : # buffer size has changed - need to allocate new buffer in the GPU glBufferData ( self . array_type , size , to_raw_pointer ( data ) , self . draw_type ) self . buffer_size = size self . unbind ( ) | Data is cffi array | 137 | 6 |
15,912 | def init ( ) : main . init_environment ( ) pluginpath = os . pathsep . join ( ( os . environ . get ( 'JUKEBOX_PLUGIN_PATH' , '' ) , BUILTIN_PLUGIN_PATH ) ) os . environ [ 'JUKEBOX_PLUGIN_PATH' ] = pluginpath try : maya . standalone . initialize ( ) jukeboxmaya . STANDALONE_INITIALIZED = True except RuntimeError as e : jukeboxmaya . STANDALONE_INITIALIZED = False if str ( e ) == "maya.standalone may only be used from an external Python interpreter" : mm = MenuManager . get ( ) mainmenu = mm . create_menu ( "Jukebox" , tearOff = True ) mm . create_menu ( "Help" , parent = mainmenu , command = show_help ) # load plugins pmanager = MayaPluginManager . get ( ) pmanager . load_plugins ( ) load_mayaplugins ( ) | Initialize the pipeline in maya so everything works | 230 | 10 |
15,913 | def all_jobs ( self ) : return list ( set ( self . complete + self . failed + self . queue + self . running ) ) | Returns a list of all jobs submitted to the queue complete in - progess or failed . | 30 | 18 |
15,914 | def progress ( self ) : total = len ( self . all_jobs ) remaining = total - len ( self . active_jobs ) if total > 0 else 0 percent = int ( 100 * ( float ( remaining ) / total ) ) if total > 0 else 0 return percent | Returns the percentage current and total number of jobs in the queue . | 57 | 13 |
15,915 | def ready ( self , job ) : no_deps = len ( job . depends_on ) == 0 all_complete = all ( j . is_complete ( ) for j in self . active_jobs if j . alias in job . depends_on ) none_failed = not any ( True for j in self . failed if j . alias in job . depends_on ) queue_is_open = len ( self . running ) < self . MAX_CONCURRENT_JOBS return queue_is_open and ( no_deps or ( all_complete and none_failed ) ) | Determines if the job is ready to be sumitted to the queue . It checks if the job depends on any currently running or queued operations . | 126 | 31 |
15,916 | def locked ( self ) : if len ( self . failed ) == 0 : return False for fail in self . failed : for job in self . active_jobs : if fail . alias in job . depends_on : return True | Determines if the queue is locked . | 47 | 9 |
15,917 | def read_args ( * * kwargs ) : if kwargs . get ( "control" ) : args = Namespace ( control = kwargs [ "control" ] ) elif config . CONTROLFILE : args = Namespace ( control = config . CONTROLFILE ) elif config . DB . get ( "control_table_name" ) : args = Namespace ( control = "sql" ) elif config . AWS . get ( "control_table_name" ) : args = Namespace ( control = "dynamodb" ) else : # read cli args parser = argparse . ArgumentParser ( ) parser . add_argument ( "--control" , required = True , help = "Control file, can be path." ) args = parser . parse_args ( ) return args | Read controlfile parameter . | 171 | 5 |
15,918 | def best_assemblyfile ( self ) : for sample in self . metadata : # Set the name of the unfiltered spades assembly output file assembly_file = os . path . join ( sample . general . spadesoutput , 'contigs.fasta' ) if os . path . isfile ( assembly_file ) : sample . general . bestassemblyfile = assembly_file else : sample . general . bestassemblyfile = 'NA' # Set the name of the filtered assembly file filteredfile = os . path . join ( sample . general . outputdirectory , '{}.fasta' . format ( sample . name ) ) # Add the name and path of the filtered file to the metadata sample . general . filteredfile = filteredfile | Determine whether the contigs . fasta output file from SPAdes is present . If not set the . bestassembly attribute to NA | 154 | 29 |
15,919 | def assemble ( self ) : threadlock = threading . Lock ( ) while True : ( sample , command ) = self . assemblequeue . get ( ) if command and not os . path . isfile ( os . path . join ( sample . general . spadesoutput , 'contigs.fasta' ) ) : # execute(command) out , err = run_subprocess ( command ) threadlock . acquire ( ) write_to_logfile ( command , command , self . logfile , sample . general . logout , sample . general . logerr , None , None ) write_to_logfile ( out , err , self . logfile , sample . general . logout , sample . general . logerr , None , None ) threadlock . release ( ) # call ( command , shell = True , stdout = open ( os . devnull , 'wb' ) , stderr = open ( os . devnull , 'wb' ) ) dotter ( ) # Signal to the queue that the job is done self . assemblequeue . task_done ( ) | Run the assembly command in a multi - threaded fashion | 227 | 10 |
15,920 | def get_diff_amounts ( self ) : diffs = [ ] last_commit = None for commit in self . repo . iter_commits ( ) : if last_commit is not None : diff = self . get_diff ( commit . hexsha , last_commit . hexsha ) total_changed = diff [ Diff . ADD ] + diff [ Diff . DEL ] diffs . append ( total_changed ) last_commit = commit return diffs | Gets list of total diff | 97 | 6 |
15,921 | def get_new_version ( self , last_version , last_commit , diff_to_increase_ratio ) : version = Version ( last_version ) diff = self . get_diff ( last_commit , self . get_last_commit_hash ( ) ) total_changed = diff [ Diff . ADD ] + diff [ Diff . DEL ] version . increase_by_changes ( total_changed , diff_to_increase_ratio ) return version | Gets new version | 101 | 4 |
15,922 | def get_mime_message ( subject , text ) : message = MIMEText ( "<html>" + str ( text ) . replace ( "\n" , "<br>" ) + "</html>" , "html" ) message [ "subject" ] = str ( subject ) return message | Creates MIME message | 62 | 5 |
15,923 | def send_email ( sender , msg , driver ) : driver . users ( ) . messages ( ) . send ( userId = sender , body = msg ) . execute ( ) | Sends email to me with this message | 37 | 8 |
15,924 | def get_readme ( ) : try : import pypandoc description = pypandoc . convert ( 'README.md' , 'rst' ) except ( IOError , ImportError ) : description = open ( 'README.md' ) . read ( ) return description | Get the contents of the README . rst file as a Unicode string . | 62 | 16 |
15,925 | def get_absolute_path ( * args ) : directory = os . path . dirname ( os . path . abspath ( __file__ ) ) return os . path . join ( directory , * args ) | Transform relative pathnames into absolute pathnames . | 44 | 9 |
15,926 | def trim ( self , key ) : current_index = self . meta [ key ] [ 'cursor' ] self . hdf5 [ key ] . resize ( current_index , axis = 0 ) | Removes empty rows from dataset ... I am still wanting to use this??? | 43 | 15 |
15,927 | def get_channel_page ( self ) : channel_url = YOUTUBE_USER_BASE_URL + self . channel_name # url source_page = Webpage ( channel_url ) . get_html_source ( ) # get source page of channel return source_page | Fetches source page | 62 | 5 |
15,928 | def get_feed_url_from_video ( video_url ) : web_page = Webpage ( video_url ) web_page . get_html_source ( ) channel_id = web_page . soup . find_all ( "div" , { "class" : "yt-user-info" } ) [ 0 ] . a [ "href" ] channel_id = str ( channel_id ) . strip ( ) . replace ( "/channel/" , "" ) # get channel id return YoutubeChannel . get_feed_url_from_id ( channel_id ) | Gets channel id and then creates feed url | 125 | 9 |
15,929 | def process_file ( path ) : info = dict ( ) with fits . open ( path ) as hdu : head = hdu [ 0 ] . header data = hdu [ 0 ] . data labels = { theme : value for value , theme in list ( hdu [ 1 ] . data ) } info [ 'filename' ] = os . path . basename ( path ) info [ 'trainer' ] = head [ 'expert' ] info [ 'date-label' ] = dateparser . parse ( head [ 'date-lab' ] ) info [ 'date-observation' ] = dateparser . parse ( head [ 'date-end' ] ) for theme in themes : info [ theme + "_count" ] = np . sum ( data == labels [ theme ] ) return info | Open a single labeled image at path and get needed information return as a dictionary | 170 | 15 |
15,930 | def plot_counts ( df , theme ) : dates , counts = df [ 'date-observation' ] , df [ theme + "_count" ] fig , ax = plt . subplots ( ) ax . set_ylabel ( "{} pixel counts" . format ( " " . join ( theme . split ( "_" ) ) ) ) ax . set_xlabel ( "observation date" ) ax . plot ( dates , counts , '.' ) fig . autofmt_xdate ( ) plt . show ( ) | plot the counts of a given theme from a created database over time | 117 | 13 |
15,931 | def deformat ( value ) : output = [ ] for c in value : if c in delchars : continue output . append ( c ) return "" . join ( output ) | REMOVE NON - ALPHANUMERIC CHARACTERS | 37 | 14 |
15,932 | def _expand ( template , seq ) : if is_text ( template ) : return _simple_expand ( template , seq ) elif is_data ( template ) : # EXPAND LISTS OF ITEMS USING THIS FORM # {"from":from, "template":template, "separator":separator} template = wrap ( template ) assert template [ "from" ] , "Expecting template to have 'from' attribute" assert template . template , "Expecting template to have 'template' attribute" data = seq [ - 1 ] [ template [ "from" ] ] output = [ ] for d in data : s = seq + ( d , ) output . append ( _expand ( template . template , s ) ) return coalesce ( template . separator , "" ) . join ( output ) elif is_list ( template ) : return "" . join ( _expand ( t , seq ) for t in template ) else : if not _Log : _late_import ( ) _Log . error ( "can not handle" ) | seq IS TUPLE OF OBJECTS IN PATH ORDER INTO THE DATA TREE | 224 | 18 |
15,933 | def utf82unicode ( value ) : try : return value . decode ( "utf8" ) except Exception as e : if not _Log : _late_import ( ) if not is_binary ( value ) : _Log . error ( "Can not convert {{type}} to unicode because it's not bytes" , type = type ( value ) . __name__ ) e = _Except . wrap ( e ) for i , c in enumerate ( value ) : try : c . decode ( "utf8" ) except Exception as f : _Log . error ( "Can not convert charcode {{c}} in string index {{i}}" , i = i , c = ord ( c ) , cause = [ e , _Except . wrap ( f ) ] ) try : latin1 = text_type ( value . decode ( "latin1" ) ) _Log . error ( "Can not explain conversion failure, but seems to be latin1" , e ) except Exception : pass try : a = text_type ( value . decode ( "latin1" ) ) _Log . error ( "Can not explain conversion failure, but seems to be latin1" , e ) except Exception : pass _Log . error ( "Can not explain conversion failure of " + type ( value ) . __name__ + "!" , e ) | WITH EXPLANATION FOR FAILURE | 285 | 10 |
15,934 | def setModel ( self , model ) : self . stimModel = model self . parameterModel = model . autoParams ( ) tone = self . stimModel . data ( self . stimModel . index ( 0 , 0 ) , QtCore . Qt . UserRole + 1 ) info = tone . auto_details ( ) # set max/mins fmax = info [ 'frequency' ] [ 'max' ] self . ui . freqStartSpnbx . setMaximum ( fmax ) self . ui . freqStopSpnbx . setMaximum ( fmax ) self . ui . freqStepSpnbx . setMaximum ( 500000 ) dbmax = info [ 'intensity' ] [ 'max' ] self . ui . dbStartSpnbx . setMaximum ( dbmax ) self . ui . dbStopSpnbx . setMaximum ( dbmax ) self . ui . dbStepSpnbx . setMaximum ( 500000 ) self . ui . durSpnbx . setMaximum ( info [ 'duration' ] [ 'max' ] ) self . ui . risefallSpnbx . setMaximum ( info [ 'risefall' ] [ 'max' ] ) self . fmapper . setModel ( self . parameterModel ) self . dbmapper . setModel ( self . parameterModel ) self . fmapper . addMapping ( self . ui . freqStartSpnbx , 1 ) self . fmapper . addMapping ( self . ui . freqStopSpnbx , 2 ) self . fmapper . addMapping ( self . ui . freqStepSpnbx , 3 ) self . fmapper . addMapping ( self . ui . freqNstepsLbl , 4 , 'text' ) self . dbmapper . addMapping ( self . ui . dbStartSpnbx , 1 ) self . dbmapper . addMapping ( self . ui . dbStopSpnbx , 2 ) self . dbmapper . addMapping ( self . ui . dbStepSpnbx , 3 ) self . dbmapper . addMapping ( self . ui . dbNstepsLbl , 4 , 'text' ) self . fmapper . toFirst ( ) self . dbmapper . setCurrentIndex ( 1 ) self . ui . durSpnbx . setValue ( tone . duration ( ) ) self . ui . nrepsSpnbx . setValue ( self . stimModel . repCount ( ) ) self . ui . risefallSpnbx . setValue ( tone . risefall ( ) ) self . tone = tone | Sets the QStimulusModel for this editor | 573 | 11 |
15,935 | def setStimDuration ( self ) : duration = self . ui . durSpnbx . value ( ) self . tone . setDuration ( duration ) | Sets the duration of the StimulusModel from values pulled from this widget | 33 | 15 |
15,936 | def setStimReps ( self ) : reps = self . ui . nrepsSpnbx . value ( ) self . stimModel . setRepCount ( reps ) | Sets the reps of the StimulusModel from values pulled from this widget | 38 | 15 |
15,937 | def setStimRisefall ( self ) : rf = self . ui . risefallSpnbx . value ( ) self . tone . setRisefall ( rf ) | Sets the Risefall of the StimulusModel s tone from values pulled from this widget | 40 | 18 |
15,938 | def add_arguments ( self , parser , bootstrap = False ) : [ item . add_argument ( parser , bootstrap ) for item in self . _get_items ( bootstrap = False ) ] | Adds all items to the parser passed in . | 44 | 9 |
15,939 | def add_source ( self , label , source_type , * * kwargs ) : self . _sources [ label ] = get_source ( label , source_type , * * kwargs ) | Add a source to the spec . | 45 | 7 |
15,940 | def find_item ( self , fq_name ) : names = fq_name . split ( self . _separator ) current = self . _yapconf_items for name in names : if isinstance ( current , ( YapconfDictItem , YapconfListItem ) ) : current = current . children if name not in current : return None current = current [ name ] return current | Find an item in the specification by fully qualified name . | 86 | 11 |
15,941 | def get_item ( self , name , bootstrap = False ) : for item in self . _get_items ( bootstrap ) : if item . name == name : return item return None | Get a particular item in the specification . | 40 | 8 |
15,942 | def update_defaults ( self , new_defaults , respect_none = False ) : for key , value in six . iteritems ( new_defaults ) : item = self . get_item ( key ) if item is None : raise YapconfItemNotFound ( "Cannot update default for {0}, " "there is no config item by the " "name of {1}" . format ( key , key ) , None ) item . update_default ( value , respect_none ) | Update items defaults to the values in the new_defaults dict . | 106 | 14 |
15,943 | def generate_documentation ( self , app_name , * * kwargs ) : output_file = kwargs . get ( 'output_file_name' ) encoding = kwargs . get ( 'encoding' , 'utf-8' ) doc_string = generate_markdown_doc ( app_name , self ) if output_file : with open ( output_file , 'w' , encoding = encoding ) as doc_file : doc_file . write ( doc_string ) return doc_string | Generate documentation for this specification . | 112 | 7 |
15,944 | def load_config ( self , * args , * * kwargs ) : bootstrap = kwargs . get ( 'bootstrap' , False ) overrides = self . _generate_overrides ( * args ) config = self . _generate_config_from_overrides ( overrides , bootstrap ) return Box ( config ) | Load a config based on the arguments passed in . | 76 | 10 |
15,945 | def spawn_watcher ( self , label , target = None , eternal = False ) : if label not in self . _sources : raise YapconfSourceError ( 'Cannot watch %s no source named %s' % ( label , label ) ) current_config = self . _sources [ label ] . get_data ( ) handler = ConfigChangeHandler ( current_config , self , target ) return self . _sources [ label ] . watch ( handler , eternal ) | Spawns a config watcher in a separate daemon thread . | 103 | 12 |
15,946 | def migrate_config_file ( self , config_file_path , always_update = False , current_file_type = None , output_file_name = None , output_file_type = None , create = True , update_defaults = True , dump_kwargs = None , include_bootstrap = True , ) : current_file_type = current_file_type or self . _file_type output_file_type = output_file_type or self . _file_type output_file_name = output_file_name or config_file_path current_config = self . _get_config_if_exists ( config_file_path , create , current_file_type ) migrated_config = { } if include_bootstrap : items = self . _yapconf_items . values ( ) else : items = [ item for item in self . _yapconf_items . values ( ) if not item . bootstrap ] for item in items : item . migrate_config ( current_config , migrated_config , always_update , update_defaults ) if create : yapconf . dump_data ( migrated_config , filename = output_file_name , file_type = output_file_type , klazz = YapconfLoadError , dump_kwargs = dump_kwargs ) return Box ( migrated_config ) | Migrates a configuration file . | 297 | 7 |
15,947 | def refractory ( times , refract = 0.002 ) : times_refract = [ ] times_refract . append ( times [ 0 ] ) for i in range ( 1 , len ( times ) ) : if times_refract [ - 1 ] + refract <= times [ i ] : times_refract . append ( times [ i ] ) return times_refract | Removes spikes in times list that do not satisfy refractor period | 82 | 13 |
15,948 | def spike_times ( signal , threshold , fs , absval = True ) : times = [ ] if absval : signal = np . abs ( signal ) over , = np . where ( signal > threshold ) segments , = np . where ( np . diff ( over ) > 1 ) if len ( over ) > 1 : if len ( segments ) == 0 : segments = [ 0 , len ( over ) - 1 ] else : # add end points to sections for looping if segments [ 0 ] != 0 : segments = np . insert ( segments , [ 0 ] , [ 0 ] ) else : #first point in singleton times . append ( float ( over [ 0 ] ) / fs ) if 1 not in segments : # make sure that first point is in there segments [ 0 ] = 1 if segments [ - 1 ] != len ( over ) - 1 : segments = np . insert ( segments , [ len ( segments ) ] , [ len ( over ) - 1 ] ) else : times . append ( float ( over [ - 1 ] ) / fs ) for iseg in range ( 1 , len ( segments ) ) : if segments [ iseg ] - segments [ iseg - 1 ] == 1 : # only single point over threshold idx = over [ segments [ iseg ] ] else : segments [ 0 ] = segments [ 0 ] - 1 # find maximum of continuous set over max idx = over [ segments [ iseg - 1 ] + 1 ] + np . argmax ( signal [ over [ segments [ iseg - 1 ] + 1 ] : over [ segments [ iseg ] ] ] ) times . append ( float ( idx ) / fs ) elif len ( over ) == 1 : times . append ( float ( over [ 0 ] ) / fs ) if len ( times ) > 0 : return refractory ( times ) else : return times | Detect spikes from a given signal | 390 | 6 |
15,949 | def bin_spikes ( spike_times , binsz ) : bins = np . empty ( ( len ( spike_times ) , ) , dtype = int ) for i , stime in enumerate ( spike_times ) : # around to fix rounding errors bins [ i ] = np . floor ( np . around ( stime / binsz , 5 ) ) return bins | Sort spike times into bins | 79 | 5 |
15,950 | def spike_latency ( signal , threshold , fs ) : over , = np . where ( signal > threshold ) segments , = np . where ( np . diff ( over ) > 1 ) if len ( over ) > 1 : if len ( segments ) == 0 : # only signal peak idx = over [ 0 ] + np . argmax ( signal [ over [ 0 ] : over [ - 1 ] ] ) latency = float ( idx ) / fs elif segments [ 0 ] == 0 : #first point in singleton latency = float ( over [ 0 ] ) / fs else : idx = over [ 0 ] + np . argmax ( signal [ over [ 0 ] : over [ segments [ 0 ] ] ] ) latency = float ( idx ) / fs elif len ( over ) > 0 : latency = float ( over [ 0 ] ) / fs else : latency = np . nan return latency | Find the latency of the first spike over threshold | 191 | 9 |
15,951 | def firing_rate ( spike_times , window_size = None ) : if len ( spike_times ) == 0 : return 0 if window_size is None : if len ( spike_times ) > 1 : window_size = spike_times [ - 1 ] - spike_times [ 0 ] elif len ( spike_times ) > 0 : # Only one spike, and no window - what to do? window_size = 1 else : window_size = 0 rate = window_size / len ( spike_times ) return rate | Calculate the firing rate of spikes | 113 | 8 |
15,952 | def evaluate_rules ( self ) : outputs = defaultdict ( list ) total_rules = len ( self . _rules ) for rule in self . _rules : res = rule . evaluate ( self . _variables ) outputs [ res [ 'term' ] ] . append ( [ res [ 'weight' ] , res [ 'output' ] ] ) return_values = { } for k , v in outputs . items ( ) : num = sum ( map ( lambda ( x , y ) : x * y , v ) ) den = sum ( [ i for i , j in v ] ) if den == 0 : return_values [ k ] = 0 else : return_values [ k ] = num / den return return_values | Perform Sugeno inference . | 154 | 6 |
15,953 | def is_complete ( self ) : qstat = self . _grep_qstat ( 'complete' ) comp = self . _grep_status ( 'complete' ) if qstat and comp : return True return False | Checks the job s output or log file to determing if the completion criteria was met . | 48 | 19 |
15,954 | def initiate ( mw_uri , consumer_token , callback = 'oob' , user_agent = defaults . USER_AGENT ) : auth = OAuth1 ( consumer_token . key , client_secret = consumer_token . secret , callback_uri = callback ) r = requests . post ( url = mw_uri , params = { 'title' : "Special:OAuth/initiate" } , auth = auth , headers = { 'User-Agent' : user_agent } ) credentials = parse_qs ( r . content ) if credentials is None or credentials == { } : raise OAuthException ( "Expected x-www-form-urlencoded response from " + "MediaWiki, but got something else: " + "{0}" . format ( repr ( r . content ) ) ) elif b ( 'oauth_token' ) not in credentials or b ( 'oauth_token_secret' ) not in credentials : raise OAuthException ( "MediaWiki response lacks token information: " "{0}" . format ( repr ( credentials ) ) ) else : request_token = RequestToken ( credentials . get ( b ( 'oauth_token' ) ) [ 0 ] , credentials . get ( b ( 'oauth_token_secret' ) ) [ 0 ] ) params = { 'title' : "Special:OAuth/authenticate" , 'oauth_token' : request_token . key , 'oauth_consumer_key' : consumer_token . key } return ( mw_uri + "?" + urlencode ( params ) , request_token ) | Initiate an oauth handshake with MediaWiki . | 345 | 11 |
15,955 | def configure ( * args , * * kwargs ) : global _stats_client log . debug ( 'statsd.configure(%s)' % kwargs ) _config . update ( kwargs ) _stats_client = _create_client ( * * _config ) | Configure the module level statsd client that will be used in all library operations . | 61 | 17 |
15,956 | def incr ( name , value = 1 , rate = 1 , tags = None ) : client ( ) . incr ( name , value , rate , tags ) | Increment a metric by value . | 34 | 7 |
15,957 | def decr ( name , value = 1 , rate = 1 , tags = None ) : client ( ) . decr ( name , value , rate , tags ) | Decrement a metric by value . | 34 | 7 |
15,958 | def gauge ( name , value , rate = 1 , tags = None ) : client ( ) . gauge ( name , value , rate , tags ) | Set the value for a gauge . | 30 | 7 |
15,959 | def timing ( name , delta , rate = 1 , tags = None ) : return client ( ) . timing ( name , delta , rate = rate , tags = tags ) | Sends new timing information . delta is in milliseconds . | 35 | 11 |
15,960 | def list_pages ( self , request , template_name = None , extra_context = None ) : if not self . admin_site . has_permission ( request ) : return self . admin_site . login ( request ) language = get_language_from_request ( request ) query = request . POST . get ( 'q' , '' ) . strip ( ) if query : page_ids = list ( set ( [ c . page . pk for c in Content . objects . filter ( body__icontains = query ) ] ) ) pages = Page . objects . filter ( pk__in = page_ids ) else : pages = Page . objects . root ( ) if settings . PAGE_HIDE_SITES : pages = pages . filter ( sites = settings . SITE_ID ) context = { 'can_publish' : request . user . has_perm ( 'pages.can_publish' ) , 'language' : language , 'name' : _ ( "page" ) , 'pages' : pages , 'opts' : self . model . _meta , 'q' : query } context . update ( extra_context or { } ) change_list = self . changelist_view ( request , context ) return change_list | List root pages | 271 | 3 |
15,961 | def codingthreads ( self ) : printtime ( 'Extracting CDS features' , self . start ) # Create and start threads for i in range ( self . cpus ) : # Send the threads to the appropriate destination function threads = Thread ( target = self . codingsequences , args = ( ) ) # Set the daemon to true - something to do with thread management threads . setDaemon ( True ) # Start the threading threads . start ( ) for sample in self . runmetadata . samples : self . codingqueue . put ( sample ) self . codingqueue . join ( ) # Create CDS files and determine gene presence/absence self . corethreads ( ) | Find CDS features in . gff files to filter out non - coding sequences from the analysis | 143 | 19 |
15,962 | def corethreads ( self ) : printtime ( 'Creating CDS files and finding core genes' , self . start ) # Create and start threads for i in range ( self . cpus ) : # Send the threads to the appropriate destination function threads = Thread ( target = self . coregroups , args = ( ) ) # Set the daemon to true - something to do with thread management threads . setDaemon ( True ) # Start the threading threads . start ( ) for sample in self . runmetadata . samples : # Define the name of the file to store the CDS nucleotide sequences sample . prokka . cds = os . path . join ( sample . prokka . outputdir , '{}.cds' . format ( sample . name ) ) self . corequeue . put ( sample ) self . corequeue . join ( ) # Write the core .fasta files for each gene self . corewriter ( ) | Create a . cds file consisting of fasta records of CDS features for each strain | 196 | 18 |
15,963 | def corewriter ( self ) : printtime ( 'Creating core allele files' , self . start ) for gene in sorted ( self . genesequence ) : self . geneset . add ( gene ) # Set the name of the allele file genefile = os . path . join ( self . coregenelocation , '{}.fasta' . format ( gene ) ) # If the file doesn't exist, create it if not os . path . isfile ( genefile ) : with open ( genefile , 'w' ) as core : for count , sequence in enumerate ( self . genesequence [ gene ] ) : # The definition line is the gene name, and the allele number (count (+ 1 to compensate for # base zero)) definitionline = '{}-{}' . format ( gene , count + 1 ) # Create a sequence record using BioPython fasta = SeqRecord ( Seq ( sequence ) , # Without this, the header will be improperly formatted description = '' , # Use >:definitionline as the header id = definitionline ) # Use the SeqIO module to properly format the new sequence record SeqIO . write ( fasta , core , 'fasta' ) for strain in self . coresequence [ sequence ] : # Record the strain name, the gene name, and the allele number. # [:-6] removes the contig number: 2014-SEQ-0276_00001 becomes 2014-SEQ-0276 try : self . corealleles [ strain [ : - 6 ] ] . update ( { gene : count + 1 } ) except KeyError : self . corealleles [ strain [ : - 6 ] ] = { gene : count + 1 } else : # If the file exists, don't recreate it; only iterate through the dictionary of gene sequences for count , sequence in enumerate ( self . genesequence [ gene ] ) : for strain in self . coresequence [ sequence ] : # Populate the dictionary as above try : self . corealleles [ strain [ : - 6 ] ] . update ( { gene : count + 1 } ) except KeyError : self . corealleles [ strain [ : - 6 ] ] = { gene : count + 1 } # Create a combined file of all the core genes to be used in typing strain(s) of interest if not os . path . isfile ( os . path . join ( self . coregenelocation , 'core_combined.fasta' ) ) : fastafiles = glob ( os . path . join ( self . coregenelocation , '*.fasta' ) ) # Run the method for each allele self . combinealleles ( fastafiles ) # Run the profiler self . profiler ( ) | Creates . fasta files containing all alleles for each gene | 584 | 13 |
15,964 | def profiler ( self ) : printtime ( 'Calculating core profiles' , self . start ) # Only create the profile if it doesn't exist already # if not os.path.isfile('{}/profile.txt'.format(self.profilelocation)): for strain in self . corealleles : # Add the gene name and allele number pair for each core gene in each strain self . coreset . add ( tuple ( sorted ( self . corealleles [ strain ] . items ( ) ) ) ) # Set the header to be similar to an MLST profile - ST,gene1,gene2,etc header = 'ST,{}\n' . format ( ',' . join ( sorted ( self . geneset ) ) ) data = '' for count , core in sorted ( enumerate ( self . coreset ) ) : # Increment count now to account for 0-based numbering count += 1 # Add the sequence type number to the profile data += '{}' . format ( count ) # Store the sequence type for each strain for strain in self . corealleles : if tuple ( sorted ( self . corealleles [ strain ] . items ( ) ) ) == core : self . profiles [ strain ] = count # Add the allele number for each gene for gene in sorted ( core ) : data += ',{}' . format ( gene [ 1 ] ) data += '\n' # Write the profile with open ( os . path . join ( self . profilelocation , 'profile.txt' ) , 'w' ) as profile : profile . write ( header ) profile . write ( data ) # Create a list of which strains correspond to the sequence types self . linker ( ) | Calculates the core profile for each strain | 359 | 9 |
15,965 | def linker ( self ) : strainprofile = os . path . join ( self . profilelocation , 'strainprofiles.txt' ) if not os . path . isfile ( strainprofile ) : header = 'Strain,SequenceType\n' data = '' # Sort the profiles based on sequence type sortedprofiles = sorted ( self . profiles . items ( ) , key = operator . itemgetter ( 1 ) ) # Associate the sequence type with each strain for strain , seqtype in sortedprofiles : for sample in self . runmetadata . samples : if sample . name == strain : sample . general . coretype = seqtype data += '{},{}\n' . format ( strain , seqtype ) # Write the results to file with open ( strainprofile , 'w' ) as profile : profile . write ( header ) profile . write ( data ) | Link the sequence types to the strains . Create a . csv file of the linkages | 183 | 18 |
15,966 | def get ( self , index ) : assert index <= self . count assert index < self . size offset = index * self . chunk_size return self . data [ offset : offset + self . chunk_size ] | Get a chunk by index | 44 | 5 |
15,967 | def new ( self , init = None ) : if self . count >= self . size : self . resize ( self . count * 2 ) chunk = self . get ( self . count ) if init is not None : assert len ( init ) == self . chunk_size chunk [ 0 : self . chunk_size ] = init self . count += 1 return chunk | Return the last currently unused chunk resizing if needed . | 75 | 11 |
15,968 | def resize ( self , new_size ) : assert new_size > self . size new_data = self . _allocate ( new_size ) # copy new_data [ 0 : self . size * self . chunk_size ] = self . data self . size = new_size self . data = new_data | Create a new larger array and copy data over | 68 | 9 |
15,969 | def remove ( self , index ) : assert index < self . count last_index = self . count - 1 data = self . get ( index ) if index == last_index : # easy case - nothing to do except zero last chunk last_data = data moved = None else : last_data = self . get ( last_index ) # copy the last chunk's data over the data to be deleted data [ 0 : self . chunk_size ] = last_data moved = last_index # zero last chunk's data last_data [ 0 : self . chunk_size ] = [ 0 ] * self . chunk_size self . count -= 1 # provide which index has now moved return moved | Remove chunk at index . | 145 | 5 |
15,970 | def create_turtle ( self , id , shape , model_init , color_init ) : assert id not in self . id_to_shape data = self . _create_turtle ( id , shape , model_init , color_init ) self . id_to_shape [ id ] = shape return data | Create a slice of memory for turtle data storage | 68 | 9 |
15,971 | def set_shape ( self , id , new_shape ) : old_shape = self . id_to_shape [ id ] old_buffer = self . get_buffer ( old_shape ) model , color = old_buffer . get ( id ) new_data = self . _create_turtle ( id , new_shape , model , color ) old_buffer . remove ( id ) self . id_to_shape [ id ] = new_shape return new_data | Copies the turtle data from the old shape buffer to the new | 102 | 13 |
15,972 | def get_checksum_by_target ( self , target ) : for csum in self . checksums : if csum . target == target : return csum return None | returns a checksum of a specific kind | 37 | 9 |
15,973 | def add_checksum ( self , csum ) : for csum_tmp in self . checksums : if csum_tmp . target == csum . target : self . checksums . remove ( csum_tmp ) break self . checksums . append ( csum ) | Add a checksum to a release object | 59 | 8 |
15,974 | def get_image_by_kind ( self , kind ) : for ss in self . images : if ss . kind == kind : return ss return None | returns a image of a specific kind | 32 | 8 |
15,975 | def add_image ( self , im ) : for im_tmp in self . images : if im_tmp . kind == im . kind : self . images . remove ( im_tmp ) break self . images . append ( im ) | Add a image to a screenshot object | 49 | 7 |
15,976 | def add_screenshot ( self , screenshot ) : if screenshot in self . screenshots : return self . screenshots . append ( screenshot ) | Add a screenshot object if it does not already exist | 27 | 10 |
15,977 | def add_provide ( self , provide ) : for p in self . provides : if p . value == provide . value : return self . provides . append ( provide ) | Add a provide object if it does not already exist | 36 | 10 |
15,978 | def get_provides_by_kind ( self , kind ) : provs = [ ] for p in self . provides : if p . kind == kind : provs . append ( p ) return provs | Returns an array of provides of a certain kind | 44 | 9 |
15,979 | def add_require ( self , require ) : for p in self . requires : if p . value == require . value : return self . requires . append ( require ) | Add a require object if it does not already exist | 35 | 10 |
15,980 | def get_require_by_kind ( self , kind , value ) : for r in self . requires : if r . kind == kind and r . value == value : return r return None | Returns a requires object of a specific value | 40 | 8 |
15,981 | def to_file ( self , filename ) : # save compressed file xml = self . to_xml ( ) f = gzip . open ( filename , 'wb' ) try : f . write ( xml . encode ( 'utf-8' ) ) finally : f . close ( ) | Save the store to disk | 60 | 5 |
15,982 | def from_file ( self , filename ) : with gzip . open ( filename , 'rb' ) as f : self . parse ( f . read ( ) ) | Open the store from disk | 35 | 5 |
15,983 | def get_components ( self ) : components = [ ] for app_id in self . components : components . append ( self . components [ app_id ] ) return components | Returns all the applications from the store | 37 | 7 |
15,984 | def add ( self , component ) : # if already exists, just add the release objects old = self . get_component ( component . id ) if old : old . releases . extend ( component . releases ) return self . components [ component . id ] = component | Add component to the store | 54 | 5 |
15,985 | def row2dict ( row , depth = None , exclude = None , exclude_pk = None , exclude_underscore = None , only = None , fk_suffix = None ) : if depth == 0 : return None d , mapper = { } , get_mapper ( row ) if depth is None : depth = getattr ( row , ATTR_DEPTH , DEFAULT_DEPTH ) - 1 else : depth -= 1 if exclude is None : exclude = getattr ( row , ATTR_EXCLUDE , DEFAULT_EXCLUDE ) if exclude_pk is None : exclude_pk = getattr ( row , ATTR_EXCLUDE_PK , DEFAULT_EXCLUDE_PK ) if exclude_underscore is None : exclude_underscore = getattr ( row , ATTR_EXCLUDE_UNDERSCORE , DEFAULT_EXCLUDE_UNDERSCORE ) if only is None : only = getattr ( row , ATTR_ONLY , DEFAULT_ONLY ) if fk_suffix is None : fk_suffix = getattr ( row , ATTR_FK_SUFFIX , DEFAULT_FK_SUFFIX ) for c in mapper . columns . keys ( ) + mapper . synonyms . keys ( ) : if c in exclude or check_exclude_pk ( c , exclude_pk , fk_suffix = fk_suffix ) or check_exclude_underscore ( c , exclude_underscore ) or check_only ( c , only ) : continue d [ c ] = getattr ( row , c ) for r in mapper . relationships . keys ( ) : if r in exclude or check_only ( r , only ) : continue attr = getattr ( row , r ) backref = get_backref ( mapper . relationships [ r ] ) if backref : exclude . add ( backref ) kwargs = dict ( depth = depth , exclude = exclude , exclude_pk = exclude_pk , exclude_underscore = exclude_underscore , only = only , fk_suffix = fk_suffix ) if isinstance ( attr , collections . InstrumentedList ) : d [ r ] = [ row2dict ( i , * * kwargs ) for i in attr if depth ] else : d [ r ] = row2dict ( attr , * * kwargs ) return d | Recursively walk row attributes to serialize ones into a dict . | 538 | 14 |
15,986 | def dict2row ( d , model , rel = None , exclude = None , exclude_pk = None , exclude_underscore = None , only = None , fk_suffix = None ) : if not isinstance ( d , dict ) : raise TypeError ( 'Source must be instance of dict, got %s instead' % type ( d ) . __name__ ) row = model ( ) mapper = get_mapper ( row ) if rel is None : rel = getattr ( row , ATTR_REL , DEFAULT_REL ) if exclude is None : exclude = getattr ( row , ATTR_EXCLUDE , DEFAULT_EXCLUDE ) if exclude_pk is None : exclude_pk = getattr ( row , ATTR_EXCLUDE_PK , DEFAULT_EXCLUDE_PK ) if exclude_underscore is None : exclude_underscore = getattr ( row , ATTR_EXCLUDE_UNDERSCORE , DEFAULT_EXCLUDE_UNDERSCORE ) if only is None : only = getattr ( row , ATTR_ONLY , DEFAULT_ONLY ) if fk_suffix is None : fk_suffix = getattr ( row , ATTR_FK_SUFFIX , DEFAULT_FK_SUFFIX ) for c in mapper . columns . keys ( ) + mapper . synonyms . keys ( ) : if c not in d or c in exclude or check_exclude_pk ( c , exclude_pk , fk_suffix = fk_suffix ) or check_exclude_underscore ( c , exclude_underscore ) or check_only ( c , only ) : continue setattr ( row , c , d [ c ] ) for r in mapper . relationships . keys ( ) : if r not in d or r not in rel or check_only ( r , only ) : continue kwargs = dict ( rel = rel , exclude = exclude , exclude_pk = exclude_pk , exclude_underscore = exclude_underscore , only = only , fk_suffix = fk_suffix ) if isinstance ( d [ r ] , list ) : setattr ( row , r , collections . InstrumentedList ( ) ) for i in d [ r ] : getattr ( row , r ) . append ( dict2row ( i , rel [ r ] , * * kwargs ) ) else : if not exclude_pk : rpk = d [ r ] . get ( 'id' ) if isinstance ( d [ r ] , dict ) else None setattr ( row , r + fk_suffix , rpk ) setattr ( row , r , dict2row ( d [ r ] , rel [ r ] , * * kwargs ) ) return row | Recursively walk dict attributes to serialize ones into a row . | 620 | 14 |
15,987 | def copy_file ( source , destination , follow_symlinks = True , template : arg ( type = bool_or ( str ) , choices = ( 'format' , 'string' ) ) = False , context = None ) : if not template : # Fast path for non-templates. return shutil . copy ( source , destination , follow_symlinks = follow_symlinks ) if os . path . isdir ( destination ) : destination = os . path . join ( destination , os . path . basename ( source ) ) with open ( source ) as source : contents = source . read ( ) if template is True or template == 'format' : contents = contents . format_map ( context ) elif template == 'string' : string_template = string . Template ( contents ) contents = string_template . substitute ( context ) else : raise ValueError ( 'Unknown template type: %s' % template ) with tempfile . NamedTemporaryFile ( 'w' , delete = False ) as temp_file : temp_file . write ( contents ) path = shutil . copy ( temp_file . name , destination ) os . remove ( temp_file . name ) return path | Copy source file to destination . | 251 | 6 |
15,988 | def git_version ( short : 'Get short hash' = True , show : 'Print version to stdout' = False ) : result = local ( [ 'git' , 'rev-parse' , '--is-inside-work-tree' ] , stdout = 'hide' , stderr = 'hide' , echo = False , raise_on_error = False ) if not result : # Not a git directory return None # Return a tag if possible result = local ( [ 'git' , 'describe' , '--exact-match' ] , stdout = 'capture' , stderr = 'hide' , echo = False , raise_on_error = False ) if result : return result . stdout # Fall back to hash result = local ( [ 'git' , 'rev-parse' , '--short' if short else None , 'HEAD' ] , stdout = 'capture' , stderr = 'hide' , echo = False , raise_on_error = False ) if result : version = result . stdout . strip ( ) if show : print ( version ) return version return None | Get tag associated with HEAD ; fall back to SHA1 . | 244 | 12 |
15,989 | def remote ( cmd : arg ( container = list ) , host , user = None , port = None , sudo = False , run_as = None , shell = '/bin/sh' , cd = None , environ : arg ( container = dict ) = None , paths = ( ) , # Args passed through to local command: stdout : arg ( type = StreamOptions ) = None , stderr : arg ( type = StreamOptions ) = None , echo = False , raise_on_error = True , dry_run = False , ) -> Result : if not isinstance ( cmd , str ) : cmd = flatten_args ( cmd , join = True ) ssh_options = [ '-q' ] if isatty ( sys . stdin ) : ssh_options . append ( '-t' ) if port is not None : ssh_options . extend ( ( '-p' , port ) ) ssh_connection_str = '{user}@{host}' . format_map ( locals ( ) ) if user else host remote_cmd = [ ] if sudo : remote_cmd . extend ( ( 'sudo' , '-H' ) ) elif run_as : remote_cmd . extend ( ( 'sudo' , '-H' , '-u' , run_as ) ) remote_cmd . extend ( ( shell , '-c' ) ) inner_cmd = [ ] if cd : inner_cmd . append ( 'cd {cd}' . format_map ( locals ( ) ) ) if environ : inner_cmd . extend ( 'export {k}="{v}"' . format_map ( locals ( ) ) for k , v in environ . items ( ) ) if paths : inner_cmd . append ( 'export PATH="{path}:$PATH"' . format ( path = ':' . join ( paths ) ) ) inner_cmd . append ( cmd ) inner_cmd = ' &&\n ' . join ( inner_cmd ) inner_cmd = '\n {inner_cmd}\n' . format_map ( locals ( ) ) inner_cmd = shlex . quote ( inner_cmd ) remote_cmd . append ( inner_cmd ) remote_cmd = ' ' . join ( remote_cmd ) args = ( 'ssh' , ssh_options , ssh_connection_str , remote_cmd ) return local ( args , stdout = stdout , stderr = stderr , echo = echo , raise_on_error = raise_on_error , dry_run = dry_run ) | Run a remote command via SSH . | 548 | 7 |
15,990 | def sync ( source , destination , host , user = None , sudo = False , run_as = None , options = ( '-rltvz' , '--no-perms' , '--no-group' ) , excludes = ( ) , exclude_from = None , delete = False , dry_run = False , mode = 'u=rwX,g=rwX,o=' , quiet = True , pull = False , # Args passed through to local command: stdout : arg ( type = StreamOptions ) = None , stderr : arg ( type = StreamOptions ) = None , echo = False , raise_on_error = True , ) -> Result : source = abs_path ( source , keep_slash = True ) destination = abs_path ( destination , keep_slash = True ) connection_str = '{user}@{host}' . format_map ( locals ( ) ) if user else host push = not pull if sudo : rsync_path = ( '--rsync-path' , 'sudo rsync' ) elif run_as : rsync_path = ( '--rsync-path' , 'sudo -u {run_as} rsync' . format_map ( locals ( ) ) ) else : rsync_path = None if push : destination = '{connection_str}:{destination}' . format_map ( locals ( ) ) else : source = '{connection_str}:{source}' . format_map ( locals ( ) ) args = ( 'rsync' , rsync_path , options , ( '--chmod' , mode ) if mode else None , tuple ( ( '--exclude' , exclude ) for exclude in excludes ) , ( '--exclude-from' , exclude_from ) if exclude_from else None , '--delete' if delete else None , '--dry-run' if dry_run else None , '--quiet' if quiet else None , source , destination , ) return local ( args , stdout = stdout , stderr = stderr , echo = echo , raise_on_error = raise_on_error ) | Sync files using rsync . | 465 | 6 |
15,991 | def _get_mean_and_median ( hist : Hist ) -> Tuple [ float , float ] : # Median # See: https://root-forum.cern.ch/t/median-of-histogram/7626/5 x = ctypes . c_double ( 0 ) q = ctypes . c_double ( 0.5 ) # Apparently needed to be safe(?) hist . ComputeIntegral ( ) hist . GetQuantiles ( 1 , x , q ) mean = hist . GetMean ( ) return ( mean , x . value ) | Retrieve the mean and median from a ROOT histogram . | 122 | 13 |
15,992 | def _project_to_part_level ( hist : Hist , outliers_removal_axis : OutliersRemovalAxis ) -> Hist : # Setup the projector import ROOT if isinstance ( hist , ( ROOT . TH2 , ROOT . TH3 ) ) : projection_information : Dict [ str , Any ] = { } output_object = _OutputObject ( None ) projector = projectors . HistProjector ( observable_to_project_from = hist , output_observable = output_object , output_attribute_name = "output" , projection_name_format = "outliers_removal_hist" , projection_information = projection_information , ) # No additional_axis_cuts or projection_dependent_cut_axes # Projection axis projector . projection_axes . append ( projectors . HistAxisRange ( axis_type = outliers_removal_axis , axis_range_name = "outliers_removal_axis" , min_val = projectors . HistAxisRange . apply_func_to_find_bin ( None , 1 ) , max_val = projectors . HistAxisRange . apply_func_to_find_bin ( ROOT . TAxis . GetNbins ) , ) ) # Perform the actual projection and return the output. projector . project ( ) return output_object . output # If we already have a 1D hist, just return that existing hist. return hist | Project the input histogram to the particle level axis . | 319 | 11 |
15,993 | def _determine_outliers_index ( hist : Hist , moving_average_threshold : float = 1.0 , number_of_values_to_search_ahead : int = 5 , limit_of_number_of_values_below_threshold : int = None ) -> int : # Validation import ROOT if isinstance ( hist , ( ROOT . TH2 , ROOT . TH3 , ROOT . THnBase ) ) : raise ValueError ( f"Given histogram '{hist.GetName()}' of type {type(hist)}, but can only" " determine the outlier location of a 1D histogram. Please project to" " the particle level axis first." ) if limit_of_number_of_values_below_threshold is None : # In principle, this could be another value. However, this is what was used in the previous outliers # removal implementation. limit_of_number_of_values_below_threshold = number_of_values_to_search_ahead - 1 # It is much more convenient to work with a numpy array. hist_to_check = histogram . Histogram1D . from_existing_hist ( hist ) # Calculate the moving average for the entire axis, looking ahead including the current bin + 4 = 5 ahead. number_of_values_to_search_ahead = 5 moving_average = utils . moving_average ( hist_to_check . y , n = number_of_values_to_search_ahead ) #logger.debug(f"y: {hist_to_check.y}") #logger.debug(f"moving_average: {moving_average}") cut_index = _determine_outliers_for_moving_average ( moving_average = moving_average , moving_average_threshold = moving_average_threshold , number_of_values_to_search_ahead = number_of_values_to_search_ahead , limit_of_number_of_values_below_threshold = limit_of_number_of_values_below_threshold , ) if cut_index != - 1 : # ROOT histograms are 1 indexed, so we add another 1. cut_index += 1 return cut_index | Determine the location of where outliers begin in a 1D histogram . | 499 | 17 |
15,994 | def _determine_outliers_for_moving_average ( moving_average : np . ndarray , moving_average_threshold : float , number_of_values_to_search_ahead : int , limit_of_number_of_values_below_threshold : int ) -> int : below_threshold = moving_average < moving_average_threshold # Build up a list of values to check if they are below threshold. This list allows us to easily look # forward in the below_threshold array. values_to_check = [ ] for i in range ( limit_of_number_of_values_below_threshold ) : # Basically, this gives us (for limit_of_number_of_values_below_threshold = 4): # below_threshold[0:-3], below_threshold[1:-2], below_threshold[2:-1], below_threshold[3:None] values_to_check . append ( below_threshold [ i : - ( limit_of_number_of_values_below_threshold - 1 - i ) or None ] ) # Some helpful logging information. #logger.debug(f"values_to_check: {values_to_check}") #logger.debug(f"moving avg length: {len(moving_average)}, length of values_to_check entries: {[len(v) for v in values_to_check]}") # Must have at least one bin above the specified threshold. found_at_least_one_bin_above_threshold = False # Index we will search for from which outliers will be cut. cut_index = - 1 # Determine the index where the limit_of_number_of_values_below_threshold bins are consequentially below the threshold. for i , values in enumerate ( zip ( * values_to_check ) ) : # Skip the first bin because some old pt hard bin trains had a large number of erroneous entries # in the first bin (regardless of the actual pt hard bin). This should be resolved in the embedding # helper now. In any case, it doesn't make sense to encounter outliers in the first bin, so this is a # fine bin to skip. if i == 0 : continue # True if below threshold, so check if not True. above_threshold = [ not value for value in values ] # We require the values to go above the moving average threshold at least once. if any ( above_threshold ) : #logger.debug(f"Found bin i {i} above threshold with moving average: {moving_average[i]}") found_at_least_one_bin_above_threshold = True # All values from which we are looking ahead must be below the threshold to consider the index # as below threshold. if found_at_least_one_bin_above_threshold and all ( np . invert ( above_threshold ) ) : # The previous outlier removal implementation used a moving average centered on a value # (ie. it checked ``arr[-2 + current_index:current_index + 3]``). Thus, we need to # shift the cut_index that we assign by limit_of_number_of_values_below_threshold // 2 for # the index where we have found all values below the threshold. logger . debug ( f"i at found cut_index: {i} with moving_average: {moving_average[i]}" ) cut_index = i + limit_of_number_of_values_below_threshold // 2 break return cut_index | Determine outliers to remove from a given moving average . | 787 | 13 |
15,995 | def _remove_outliers_from_hist ( hist : Hist , outliers_start_index : int , outliers_removal_axis : OutliersRemovalAxis ) -> None : # Use on TH1, TH2, and TH3 since we don't start removing immediately, but instead only after the limit if outliers_start_index > 0 : #logger.debug("Removing outliers") # Check for values above which they should be removed by translating the global index x = ctypes . c_int ( 0 ) y = ctypes . c_int ( 0 ) z = ctypes . c_int ( 0 ) # Maps axis to valaues # This is kind of dumb, but it works. outliers_removal_axis_values : Dict [ OutliersRemovalAxis , ctypes . c_int ] = { projectors . TH1AxisType . x_axis : x , projectors . TH1AxisType . y_axis : y , projectors . TH1AxisType . z_axis : z , } for index in range ( 0 , hist . GetNcells ( ) ) : # Get the bin x, y, z from the global bin hist . GetBinXYZ ( index , x , y , z ) # Watch out for any problems if hist . GetBinContent ( index ) < hist . GetBinError ( index ) : logger . warning ( f"Bin content < error. Name: {hist.GetName()}, Bin content: {hist.GetBinContent(index)}, Bin error: {hist.GetBinError(index)}, index: {index}, ({x.value}, {y.value})" ) if outliers_removal_axis_values [ outliers_removal_axis ] . value >= outliers_start_index : #logger.debug("Cutting for index {}. x bin {}. Cut index: {}".format(index, x, cutIndex)) hist . SetBinContent ( index , 0 ) hist . SetBinError ( index , 0 ) else : logger . info ( f"Hist {hist.GetName()} did not have any outliers to cut" ) | Remove outliers from a given histogram . | 478 | 9 |
15,996 | def shapefile ( self , file ) : driver = ogr . GetDriverByName ( 'ESRI Shapefile' ) dataset = driver . Open ( file ) if dataset is not None : # from Layer layer = dataset . GetLayer ( ) spatialRef = layer . GetSpatialRef ( ) # from Geometry feature = layer . GetNextFeature ( ) geom = feature . GetGeometryRef ( ) spatialRef = geom . GetSpatialReference ( ) #WGS84 outSpatialRef = osr . SpatialReference ( ) outSpatialRef . ImportFromEPSG ( 4326 ) coordTrans = osr . CoordinateTransformation ( spatialRef , outSpatialRef ) env = geom . GetEnvelope ( ) xmin = env [ 0 ] ymin = env [ 2 ] xmax = env [ 1 ] ymax = env [ 3 ] pointMAX = ogr . Geometry ( ogr . wkbPoint ) pointMAX . AddPoint ( env [ 1 ] , env [ 3 ] ) pointMAX . Transform ( coordTrans ) pointMIN = ogr . Geometry ( ogr . wkbPoint ) pointMIN . AddPoint ( env [ 0 ] , env [ 2 ] ) pointMIN . Transform ( coordTrans ) self . bbox = str ( pointMIN . GetPoint ( ) [ 0 ] ) + ',' + str ( pointMIN . GetPoint ( ) [ 1 ] ) + ',' + str ( pointMAX . GetPoint ( ) [ 0 ] ) + ',' + str ( pointMAX . GetPoint ( ) [ 1 ] ) self . query = None else : exit ( " shapefile not found. Please verify your path to the shapefile" ) | reprojette en WGS84 et recupere l extend | 361 | 14 |
15,997 | def set_comment ( self , cellid , comment ) : info = { 'cellid' : cellid , 'comment' : comment } self . datafile . set_metadata ( self . current_dataset_name , info ) | Saves the provided comment to the current dataset . | 51 | 10 |
15,998 | def main ( argument , sets , big_endian , optimal , output , clipboard , quiet , verbose ) : logger = logging . getLogger ( ) handler = logging . StreamHandler ( sys . stderr ) handler . setFormatter ( LevelFormatter ( ) ) logger . addHandler ( handler ) logger . setLevel ( logging . WARNING + ( quiet - verbose ) * 10 ) if sets and optimal : pat = Pat . from_chars ( '' . join ( sets ) , optimal ) elif optimal : pat = Pat . from_chars ( optimal = optimal ) elif sets : pat = Pat ( sets ) else : pat = Pat ( ) if argument . isdigit ( ) : count = int ( argument ) try : pattern = pat . create ( count ) except IndexError : logging . exception ( _ ( 'Failed to create the pattern.' ) ) sys . exit ( 1 ) else : if output : output . write ( pattern ) elif clipboard : copy ( pattern ) else : print ( pattern ) else : target = argument try : index = pat . locate ( target , big_endian ) except KeyError : logging . exception ( _ ( 'Failed to locate the pattern.' ) ) sys . exit ( 1 ) else : print ( index ) sys . exit ( 0 ) | Customizable Lazy Exploit Pattern Utility . | 273 | 9 |
15,999 | def mousePressEvent ( self , event ) : if event . x ( ) < 50 : super ( PlotMenuBar , self ) . mousePressEvent ( event ) else : # ignore to allow proper functioning of float event . ignore ( ) | Marshalls behaviour depending on location of the mouse click | 49 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.