idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
16,700 | def delete ( self , refobj ) : refobjinter = self . get_refobjinter ( ) reference = refobjinter . get_reference ( refobj ) if reference : fullns = cmds . referenceQuery ( reference , namespace = True ) cmds . file ( removeReference = True , referenceNode = reference ) else : parentns = common . get_namespace ( refobj ) ns = cmds . getAttr ( "%s.namespace" % refobj ) fullns = ":" . join ( ( parentns . rstrip ( ":" ) , ns . lstrip ( ":" ) ) ) cmds . namespace ( removeNamespace = fullns , deleteNamespaceContent = True ) | Delete the content of the given refobj |
16,701 | def import_reference ( self , refobj , reference ) : cmds . file ( importReference = True , referenceNode = reference ) | Import the given reference |
16,702 | def create_options_model ( self , taskfileinfos ) : rootdata = ListItemData ( [ "Asset/Shot" , "Task" , "Descriptor" , "Version" , "Releasetype" ] ) rootitem = TreeItem ( rootdata ) tasks = defaultdict ( list ) for tfi in taskfileinfos : tasks [ tfi . task ] . append ( tfi ) for task in reversed ( sorted ( tasks . keys ( ) , key = lambda t : t . department . ordervalue ) ) : tfis = tasks [ task ] taskdata = djitemdata . TaskItemData ( task ) taskitem = TreeItem ( taskdata , rootitem ) for tfi in reversed ( tfis ) : tfidata = TaskFileInfoItemData ( tfi ) TreeItem ( tfidata , taskitem ) return TreeModel ( rootitem ) | Create a new treemodel that has the taskfileinfos as internal_data of the leaves . |
16,703 | def get_scene_suggestions ( self , current ) : l = [ ] if isinstance ( current , djadapter . models . Asset ) : l . append ( current ) l . extend ( list ( current . assets . all ( ) ) ) return l | Return a list with elements for reftracks for the current scene with this type . |
16,704 | def init_ui ( self , ) : self . mm = MenuManager . get ( ) p = self . mm . menus [ 'Jukebox' ] self . menu = self . mm . create_menu ( "Preferences" , p , command = self . run ) | Create the menu \ Preferences \ under \ Jukebox \ to start the plugin |
16,705 | def setupArgparse ( ) : parser = argparse . ArgumentParser ( ) parser . add_argument ( "callsign" , help = "Callsign of radio" ) parser . add_argument ( "id" , type = int , help = "ID number radio" ) parser . add_argument ( "-l" , "--loopback" , action = "store_true" , help = "Use software loopback serial port" ) parser . add_argument ( "-p" , "--port" , default = "/dev/ttyUSB0" , help = "Physical serial port of radio" ) return parser . parse_args ( ) | Sets up argparse module to create command line options and parse them . |
16,706 | def setupSerialPort ( loopback , port ) : if loopback : testSerial = SerialTestClass ( ) serialPort = testSerial . serialPort else : serialPort = serial . Serial ( port , 115200 , timeout = 0 ) return serialPort | Sets up serial port by connecting to phsyical or software port . |
16,707 | def main ( ) : print ( "Executing faradayio-cli version {0}" . format ( __version__ ) ) try : args = setupArgparse ( ) except argparse . ArgumentError as error : raise SystemExit ( error ) try : serialPort = setupSerialPort ( args . loopback , args . port ) except serial . SerialException as error : raise SystemExit ( error ) tunName = "{0}-{1}" . format ( args . callsign . upper ( ) , args . id ) isRunning = threading . Event ( ) isRunning . set ( ) try : tun = Monitor ( serialPort = serialPort , name = tunName , isRunning = isRunning ) tun . start ( ) except pytun . Error as error : print ( "Warning! faradayio-cli must be run with sudo privileges!" ) raise SystemExit ( error ) try : while True : time . sleep ( 0.1 ) except KeyboardInterrupt : tun . isRunning . clear ( ) tun . join ( ) | Main function of faradayio - cli client . |
16,708 | def lookup_email ( args ) : email = args . email if email is None : email = gituseremail ( ) if email is None : raise RuntimeError ( textwrap . dedent ( ) ) debug ( "email is {email}" . format ( email = email ) ) return email | Return the email address to use when creating git objects or exit program . |
16,709 | def lookup_user ( args ) : user = args . user if user is None : user = gitusername ( ) if user is None : raise RuntimeError ( textwrap . dedent ( ) ) debug ( "user name is {user}" . format ( user = user ) ) return user | Return the user name to use when creating git objects or exit program . |
16,710 | def current_timestamp ( ) : now = datetime . utcnow ( ) timestamp = now . isoformat ( ) [ 0 : 19 ] + 'Z' debug ( "generated timestamp: {now}" . format ( now = timestamp ) ) return timestamp | Returns current time as ISO8601 formatted string in the Zulu TZ |
16,711 | def calc_spectrum ( signal , rate ) : npts = len ( signal ) padto = 1 << ( npts - 1 ) . bit_length ( ) npts = padto sp = np . fft . rfft ( signal , n = padto ) / npts freq = np . arange ( ( npts / 2 ) + 1 ) / ( npts / rate ) return freq , abs ( sp ) | Return the spectrum and frequency indexes for real - valued input signal |
16,712 | def spectrogram ( source , nfft = 512 , overlap = 90 , window = 'hanning' , caldb = 93 , calv = 2.83 ) : if isinstance ( source , basestring ) : fs , wavdata = audioread ( source ) else : fs , wavdata = source duration = float ( len ( wavdata ) ) / fs desired_npts = int ( ( np . trunc ( duration * 1000 ) / 1000 ) * fs ) wavdata = wavdata [ : desired_npts ] duration = len ( wavdata ) / fs if VERBOSE : amp = rms ( wavdata , fs ) print 'RMS of input signal to spectrogram' , amp if len ( wavdata ) > 0 and np . max ( abs ( wavdata ) ) != 0 : wavdata = wavdata / np . max ( abs ( wavdata ) ) if window == 'hanning' : winfnc = mlab . window_hanning elif window == 'hamming' : winfnc = np . hamming ( nfft ) elif window == 'blackman' : winfnc = np . blackman ( nfft ) elif window == 'bartlett' : winfnc = np . bartlett ( nfft ) elif window == None or window == 'none' : winfnc = mlab . window_none noverlap = int ( nfft * ( float ( overlap ) / 100 ) ) Pxx , freqs , bins = mlab . specgram ( wavdata , NFFT = nfft , Fs = fs , noverlap = noverlap , pad_to = nfft * 2 , window = winfnc , detrend = mlab . detrend_none , sides = 'default' , scale_by_freq = False ) Pxx [ Pxx == 0 ] = np . nan spec = 20. * np . log10 ( Pxx ) spec [ np . isnan ( spec ) ] = np . nanmin ( spec ) return spec , freqs , bins , duration | Produce a matrix of spectral intensity uses matplotlib s specgram function . Output is in dB scale . |
16,713 | def convolve_filter ( signal , impulse_response ) : if impulse_response is not None : adjusted_signal = fftconvolve ( signal , impulse_response ) adjusted_signal = adjusted_signal [ len ( impulse_response ) / 2 : len ( adjusted_signal ) - len ( impulse_response ) / 2 + 1 ] return adjusted_signal else : return signal | Convovle the two input signals if impulse_response is None returns the unaltered signal |
16,714 | def attenuation_curve ( signal , resp , fs , calf , smooth_pts = 99 ) : y = resp - np . mean ( resp ) x = signal npts = len ( y ) fq = np . arange ( npts / 2 + 1 ) / ( float ( npts ) / fs ) Y = np . fft . rfft ( y ) X = np . fft . rfft ( x ) Ymag = np . sqrt ( Y . real ** 2 + Y . imag ** 2 ) Xmag = np . sqrt ( X . real ** 2 + X . imag ** 2 ) YmagdB = 20 * np . log10 ( Ymag ) XmagdB = 20 * np . log10 ( Xmag ) diffdB = XmagdB - YmagdB diffdB = smooth ( diffdB , smooth_pts ) fidx = ( np . abs ( fq - calf ) ) . argmin ( ) diffdB -= diffdB [ fidx ] return diffdB | Calculate an attenuation roll - off curve from a signal and its recording |
16,715 | def calibrate_signal ( signal , resp , fs , frange ) : dc = np . mean ( resp ) resp = resp - dc npts = len ( signal ) f0 = np . ceil ( frange [ 0 ] / ( float ( fs ) / npts ) ) f1 = np . floor ( frange [ 1 ] / ( float ( fs ) / npts ) ) y = resp Y = np . fft . rfft ( y ) x = signal X = np . fft . rfft ( x ) H = Y / X A = X / H return np . fft . irfft ( A ) | Given original signal and recording spits out a calibrated signal |
16,716 | def multiply_frequencies ( signal , fs , frange , calibration_frequencies , attendB ) : npts = len ( signal ) padto = 1 << ( npts - 1 ) . bit_length ( ) X = np . fft . rfft ( signal , n = padto ) npts = padto f = np . arange ( ( npts / 2 ) + 1 ) / ( npts / fs ) fidx_low = ( np . abs ( f - frange [ 0 ] ) ) . argmin ( ) fidx_high = ( np . abs ( f - frange [ 1 ] ) ) . argmin ( ) cal_func = interp1d ( calibration_frequencies , attendB ) roi = f [ fidx_low : fidx_high ] Hroi = cal_func ( roi ) H = np . zeros ( ( len ( X ) , ) ) H [ fidx_low : fidx_high ] = Hroi H = smooth ( H ) H = 10 ** ( ( H ) . astype ( float ) / 20 ) Xadjusted = X * H signal_calibrated = np . fft . irfft ( Xadjusted ) return signal_calibrated [ : len ( signal ) ] | Given a vector of dB attenuations adjust signal by multiplication in the frequency domain |
16,717 | def audioread ( filename ) : try : if '.wav' in filename . lower ( ) : fs , signal = wv . read ( filename ) elif '.call' in filename . lower ( ) : with open ( filename , 'rb' ) as f : signal = np . fromfile ( f , dtype = np . int16 ) fs = 333333 else : raise IOError ( "Unsupported audio format for file: {}" . format ( filename ) ) except : print u"Problem reading wav file" raise signal = signal . astype ( float ) return fs , signal | Reads an audio signal from file . |
16,718 | def audiorate ( filename ) : if '.wav' in filename . lower ( ) : wf = wave . open ( filename ) fs = wf . getframerate ( ) wf . close ( ) elif '.call' in filename . lower ( ) : fs = 333333 else : raise IOError ( "Unsupported audio format for file: {}" . format ( filename ) ) return fs | Determines the samplerate of the given audio recording file |
16,719 | def init_ui ( self , ) : self . sidebar = self . get_maya_sidebar ( ) self . lay = self . sidebar . layout ( ) self . tool_pb = QtGui . QPushButton ( "JB Wins" ) self . tooltip = JB_WindowToolTip ( ) self . tooltip . install_tooltip ( self . tool_pb ) self . lay . addWidget ( self . tool_pb ) self . tool_pb . clicked . connect ( self . tooltip . show ) | Create the tooltip in the sidebar |
16,720 | def uninit_ui ( self ) : self . lay . removeWidget ( self . tool_pb ) self . tooltip . deleteLater ( ) self . tool_pb . deleteLater ( ) | Delete the tooltip |
16,721 | def open_acqdata ( filename , user = 'unknown' , filemode = 'w-' ) : if filename . lower ( ) . endswith ( ( ".hdf5" , ".h5" ) ) : return HDF5Data ( filename , user , filemode ) elif filename . lower ( ) . endswith ( ( ".pst" , ".raw" ) ) : return BatlabData ( filename , user , filemode ) else : print "File format not supported: " , filename | Opens and returns the correct AcquisitionData object according to filename extention . |
16,722 | def columnCount ( self , parent = QtCore . QModelIndex ( ) ) : if parent . isValid ( ) : return self . _stim . columnCount ( parent . row ( ) ) else : return self . _stim . columnCount ( ) | Determines the numbers of columns the view will draw |
16,723 | def removeItem ( self , index ) : self . _stim . removeComponent ( index . row ( ) , index . column ( ) ) | Alias for removeComponent |
16,724 | def setEditor ( self , name ) : editor = get_stimulus_editor ( name ) self . editor = editor self . _stim . setStimType ( name ) | Sets the editor class for this Stimulus |
16,725 | def showEditor ( self ) : if self . editor is not None : editor = self . editor ( ) editor . setModel ( self ) factory = get_stimulus_factory ( self . _stim . stimType ( ) ) editor . editingFinished . connect ( factory . update ) return editor else : logger = logging . getLogger ( 'main' ) logger . warning ( 'Erm, no editor available :(' ) | Creates and shows an editor for this Stimulus |
16,726 | def randomToggle ( self , randomize ) : if randomize : self . _stim . setReorderFunc ( order_function ( 'random' ) , 'random' ) else : self . _stim . reorder = None | Sets the reorder function on this StimulusModel to a randomizer or none alternately |
16,727 | def assert_variable_type ( variable , expected_type , raise_exception = True ) : if not isinstance ( expected_type , list ) : expected_type = [ expected_type ] for t in expected_type : if not isinstance ( t , type ) : raise ValueError ( 'expected_type argument "%s" is not a type' % str ( t ) ) if not isinstance ( raise_exception , bool ) : raise ValueError ( 'raise_exception argument "%s" is not a bool' % str ( raise_exception ) ) if not len ( [ ( t ) for t in expected_type if isinstance ( variable , t ) ] ) : error_message = '"%s" is not an instance of type %s. It is of type %s' % ( str ( variable ) , ' or ' . join ( [ str ( t ) for t in expected_type ] ) , str ( type ( variable ) ) ) if raise_exception : raise ValueError ( error_message ) else : return False , error_message return True , None | Return True if a variable is of a certain type or types . Otherwise raise a ValueError exception . |
16,728 | def closeEvent ( self , event ) : self . ok . setText ( "Checking..." ) QtGui . QApplication . processEvents ( ) self . model ( ) . cleanComponents ( ) self . model ( ) . purgeAutoSelected ( ) msg = self . model ( ) . verify ( ) if not msg : msg = self . model ( ) . warning ( ) if msg : warnBox = QtGui . QMessageBox ( QtGui . QMessageBox . Warning , 'Warning - Invalid Settings' , '{}. Do you want to change this?' . format ( msg ) ) yesButton = warnBox . addButton ( self . tr ( 'Edit' ) , QtGui . QMessageBox . YesRole ) noButton = warnBox . addButton ( self . tr ( 'Ignore' ) , QtGui . QMessageBox . NoRole ) warnBox . exec_ ( ) if warnBox . clickedButton ( ) == yesButton : event . ignore ( ) self . ok . setText ( "OK" ) | Verifies the stimulus before closing warns user with a dialog if there are any problems |
16,729 | def close ( self , reason = None ) : with self . _closing : if self . _closed : return self . _websocket . close ( ) self . _consumer . join ( ) self . _consumer = None self . _websocket = None self . _closed = True for cb in self . _close_callbacks : cb ( self , reason ) | Stop consuming messages and perform an orderly shutdown . |
16,730 | def dropEvent ( self , event ) : super ( TrashWidget , self ) . dropEvent ( event ) self . itemTrashed . emit ( ) | Emits the itemTrashed signal data contained in drag operation left to be garbage collected |
16,731 | def choose ( self , choose_from ) : for choice in self . elements : if choice in choose_from : return ImplementationChoice ( choice , choose_from [ choice ] ) raise LookupError ( self . elements , choose_from . keys ( ) ) | given a mapping of implementations choose one based on the current settings returns a key value pair |
16,732 | def remove ( self ) : import shutil printtime ( 'Removing large and/or temporary files' , self . start ) removefolder = list ( ) for sample in self . metadata : for path , dirs , files in os . walk ( sample . general . outputdirectory ) : for item in files : if re . search ( ".fastq$" , item ) or re . search ( ".fastq.gz$" , item ) or re . search ( ".bam$" , item ) or re . search ( ".bt2$" , item ) or re . search ( ".tab$" , item ) or re . search ( "^before" , item ) or re . search ( "^baitedtargets" , item ) or re . search ( "_combined.csv$" , item ) or re . search ( "^scaffolds" , item ) or re . search ( ".fastg$" , item ) or re . search ( ".gfa$" , item ) or re . search ( ".bai$" , item ) or 'coregenome' in path or 'prophages' in path : if item != 'baitedtargets.fa' and not re . search ( "coregenome" , item ) and not re . search ( "paired" , item ) : try : os . remove ( os . path . join ( path , item ) ) except IOError : pass for folder in removefolder : try : shutil . rmtree ( folder ) except ( OSError , TypeError ) : pass | Removes unnecessary temporary files generated by the pipeline |
16,733 | def load_info ( self ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/login.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/team_news.phtml' , headers = headers ) . content soup = BeautifulSoup ( req ) self . title = soup . title . string estado = soup . find ( 'div' , { 'id' : 'content' } ) . find ( 'div' , { 'id' : 'manager' } ) . string if estado : print estado . strip ( ) return [ s . extract ( ) for s in soup ( 'strong' ) ] if ( soup . find ( 'div' , { 'id' : 'userid' } ) != None ) : self . myid = soup . find ( 'div' , { 'id' : 'userid' } ) . p . text . strip ( ) [ 2 : ] self . money = int ( soup . find ( 'div' , { 'id' : 'manager_money' } ) . p . text . strip ( ) . replace ( "." , "" ) [ : - 2 ] ) self . teamvalue = int ( soup . find ( 'div' , { 'id' : 'teamvalue' } ) . p . text . strip ( ) . replace ( "." , "" ) [ : - 2 ] ) self . community_id = soup . find ( 'link' ) [ 'href' ] [ 24 : ] self . username = soup . find ( 'div' , { 'id' : 'username' } ) . p . a . text | Get info from logged account |
16,734 | def get_news ( self ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/login.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/team_news.phtml' , headers = headers ) . content soup = BeautifulSoup ( req ) news = [ ] for i in soup . find_all ( 'div' , { 'class' , 'article_content_text' } ) : news . append ( i . text ) return news | Get all the news from first page |
16,735 | def logout ( self ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , "User-Agent" : user_agent } self . session . get ( 'http://' + self . domain + '/logout.phtml' , headers = headers ) | Logout from Comunio |
16,736 | def standings ( self ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/standings.phtml' , headers = headers ) . content soup = BeautifulSoup ( req ) table = soup . find ( 'table' , { 'id' : 'tablestandings' } ) . find_all ( 'tr' ) clasificacion = [ ] [ clasificacion . append ( ( '%s\t%s\t%s\t%s\t%s' ) % ( tablas . find ( 'td' ) . text , tablas . find ( 'div' ) [ 'id' ] , tablas . a . text , tablas . find_all ( 'td' ) [ 3 ] . text , tablas . find_all ( 'td' ) [ 4 ] . text ) ) for tablas in table [ 1 : ] ] return clasificacion | Get standings from the community s account |
16,737 | def info_user ( self , userid ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/standings.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/playerInfo.phtml?pid=' + userid , headers = headers ) . content soup = BeautifulSoup ( req ) title = soup . title . string community = soup . find_all ( 'table' , border = 0 ) [ 1 ] . a . text info = [ ] info . append ( title ) info . append ( community ) for i in soup . find_all ( 'table' , border = 0 ) [ 1 ] . find_all ( 'td' ) [ 1 : ] : info . append ( i . text ) for i in soup . find ( 'table' , cellpadding = 2 ) . find_all ( 'tr' ) [ 1 : ] : cad = i . find_all ( 'td' ) numero = cad [ 0 ] . text nombre = cad [ 2 ] . text . strip ( ) team = cad [ 3 ] . find ( 'img' ) [ 'alt' ] precio = cad [ 4 ] . text . replace ( "." , "" ) puntos = cad [ 5 ] . text posicion = cad [ 6 ] . text info . append ( [ numero , nombre , team , precio , puntos , posicion ] ) return info | Get user info using a ID |
16,738 | def lineup_user ( self , userid ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/standings.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/playerInfo.phtml?pid=' + userid , headers = headers ) . content soup = BeautifulSoup ( req ) info = [ ] for i in soup . find_all ( 'td' , { 'class' : 'name_cont' } ) : info . append ( i . text . strip ( ) ) return info | Get user lineup using a ID |
16,739 | def info_community ( self , teamid ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/standings.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/teamInfo.phtml?tid=' + teamid , headers = headers ) . content soup = BeautifulSoup ( req ) info = [ ] for i in soup . find ( 'table' , cellpadding = 2 ) . find_all ( 'tr' ) [ 1 : ] : info . append ( '%s\t%s\t%s\t%s\t%s' % ( i . find ( 'td' ) . text , i . find ( 'a' ) [ 'href' ] . split ( 'pid=' ) [ 1 ] , i . a . text , i . find_all ( 'td' ) [ 2 ] . text , i . find_all ( 'td' ) [ 3 ] . text ) ) return info | Get comunity info using a ID |
16,740 | def info_player ( self , pid ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/team_news.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/tradableInfo.phtml?tid=' + pid , headers = headers ) . content soup = BeautifulSoup ( req ) info = [ ] info . append ( soup . title . text . strip ( ) ) for i in soup . find ( 'table' , cellspacing = 1 ) . find_all ( 'tr' ) : info . append ( i . find_all ( 'td' ) [ 1 ] . text . replace ( "." , "" ) ) return info | Get info football player using a ID |
16,741 | def info_player_id ( self , name ) : number = 0 name = name . title ( ) . replace ( " " , "+" ) headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/team_news.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://stats.comunio.es/search.php?name=' + name , headers = headers ) . content soup = BeautifulSoup ( req ) for i in soup . find_all ( 'a' , { 'class' , 'nowrap' } ) : number = re . search ( "([0-9]+)-" , str ( i ) ) . group ( 1 ) break return number | Get id using name football player |
16,742 | def club ( self , cid ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/clubInfo.phtml?cid=' + cid , headers = headers ) . content soup = BeautifulSoup ( req ) plist = [ ] for i in soup . find ( 'table' , cellpadding = 2 ) . find_all ( 'tr' ) [ 1 : ] : plist . append ( '%s\t%s\t%s\t%s\t%s' % ( i . find_all ( 'td' ) [ 0 ] . text , i . find_all ( 'td' ) [ 1 ] . text , i . find_all ( 'td' ) [ 2 ] . text , i . find_all ( 'td' ) [ 3 ] . text , i . find_all ( 'td' ) [ 4 ] . text ) ) return soup . title . text , plist | Get info by real team using a ID |
16,743 | def team_id ( self , team ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain , headers = headers ) . content soup = BeautifulSoup ( req ) for i in soup . find ( 'table' , cellpadding = 2 ) . find_all ( 'tr' ) : team1 = i . find ( 'a' ) [ 'title' ] team2 = i . find_all ( 'a' ) [ 1 ] [ 'title' ] if ( team == team1 ) : return i . find ( 'a' ) [ 'href' ] . split ( 'cid=' ) [ 1 ] elif ( team == team2 ) : return i . find_all ( 'a' ) [ 1 ] [ 'href' ] . split ( 'cid=' ) [ 1 ] return None | Get team ID using a real team name |
16,744 | def user_id ( self , user ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/team_news.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/standings.phtml' , headers = headers ) . content soup = BeautifulSoup ( req ) for i in soup . find ( 'table' , cellpadding = 2 ) . find_all ( 'tr' ) : try : if ( user == i . find_all ( 'td' ) [ 2 ] . text . encode ( 'utf8' ) ) : return i . find ( 'a' ) [ 'href' ] . split ( 'pid=' ) [ 1 ] except : continue return None | Get userid from a name |
16,745 | def players_onsale ( self , community_id , only_computer = False ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/team_news.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/teamInfo.phtml?tid=' + community_id , headers = headers ) . content soup = BeautifulSoup ( req ) current_year = dt . today ( ) . year current_month = dt . today ( ) . month on_sale = [ ] year_flag = 0 for i in soup . find_all ( 'table' , { 'class' , 'tablecontent03' } ) [ 2 ] . find_all ( 'tr' ) [ 1 : ] : name = i . find_all ( 'td' ) [ 0 ] . text . strip ( ) team = i . find ( 'img' ) [ 'alt' ] min_price = i . find_all ( 'td' ) [ 2 ] . text . replace ( "." , "" ) . strip ( ) market_price = i . find_all ( 'td' ) [ 3 ] . text . replace ( "." , "" ) . strip ( ) points = i . find_all ( 'td' ) [ 4 ] . text . strip ( ) . strip ( ) if current_month <= 7 and int ( i . find_all ( 'td' ) [ 5 ] . text [ 3 : 5 ] ) > 7 : year_flag = 1 date = str ( current_year - year_flag ) + i . find_all ( 'td' ) [ 5 ] . text [ 3 : 5 ] + i . find_all ( 'td' ) [ 5 ] . text [ : 2 ] owner = i . find_all ( 'td' ) [ 6 ] . text . strip ( ) position = i . find_all ( 'td' ) [ 7 ] . text . strip ( ) if ( only_computer and owner == 'Computer' ) or not only_computer : on_sale . append ( [ name , team , min_price , market_price , points , date , owner , position ] ) return on_sale | Returns the football players currently on sale |
16,746 | def bids_to_you ( self ) : headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/team_news.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/exchangemarket.phtml?viewoffers_x=' , headers = headers ) . content soup = BeautifulSoup ( req ) table = [ ] for i in soup . find ( 'table' , { 'class' , 'tablecontent03' } ) . find_all ( 'tr' ) [ 1 : ] : player , owner , team , price , bid_date , trans_date , status = self . _parse_bid_table ( i ) table . append ( [ player , owner , team , price , bid_date , trans_date , status ] ) return table | Get bids made to you |
16,747 | def _parse_bid_table ( self , table ) : player = table . find_all ( 'td' ) [ 0 ] . text owner = table . find_all ( 'td' ) [ 1 ] . text team = table . find ( 'img' ) [ 'alt' ] price = int ( table . find_all ( 'td' ) [ 3 ] . text . replace ( "." , "" ) ) bid_date = table . find_all ( 'td' ) [ 4 ] . text trans_date = table . find_all ( 'td' ) [ 5 ] . text status = table . find_all ( 'td' ) [ 6 ] . text return player , owner , team , price , bid_date , trans_date , status | Convert table row values into strings |
16,748 | def run ( self ) : while not self . stopped . isSet ( ) : try : timeout = ( self . _state != 'idle' ) and 0.2 or None rdlist , _ , _ = select . select ( [ self . _socket . fileno ( ) ] , [ ] , [ ] , timeout ) if not rdlist : if self . _state != 'idle' : self . _state = 'idle' continue data = self . _socket . recv ( 1024 ) if not data : try : os . fstat ( recv . _socket . fileno ( ) ) except socket . error : break continue code = utils . mangleIR ( data , ignore_errors = True ) codeName = self . codeMap . get ( code ) if codeName and ( self . _state != codeName ) : self . _state = codeName for callback in self . _callbacks : callback ( codeName ) except : time . sleep ( 0.1 ) | Main loop of KIRA thread . |
16,749 | def convert_vec2_to_vec4 ( scale , data ) : it = iter ( data ) while True : yield next ( it ) * scale yield next ( it ) * scale yield 0.0 yield 1.0 | transforms an array of 2d coords into 4d |
16,750 | def calculate_edges ( self , excludes ) : edges = [ ] MEW = 100.0 if excludes is None : excludes = [ 0 ] * len ( self . indices ) * 2 for i in range ( 0 , len ( self . indices ) , 3 ) : i0 = self . indices [ i + 0 ] * 4 i1 = self . indices [ i + 1 ] * 4 i2 = self . indices [ i + 2 ] * 4 e0 = excludes [ i + 0 ] e1 = excludes [ i + 1 ] e2 = excludes [ i + 2 ] p0 = self . vertices [ i0 : i0 + 4 ] p1 = self . vertices [ i1 : i1 + 4 ] p2 = self . vertices [ i2 : i2 + 4 ] v0 = self . vec2minus ( p2 , p1 ) v1 = self . vec2minus ( p2 , p0 ) v2 = self . vec2minus ( p1 , p0 ) area = fabs ( v1 [ 0 ] * v2 [ 1 ] - v1 [ 1 ] * v2 [ 0 ] ) c0 = ( area / self . magnitude ( v0 ) , e1 * MEW , e2 * MEW ) c1 = ( e0 * MEW , area / self . magnitude ( v1 ) , e2 * MEW ) c2 = ( e0 * MEW , e1 * MEW , area / self . magnitude ( v2 ) ) edges . extend ( p0 ) edges . extend ( c0 ) edges . extend ( p1 ) edges . extend ( c1 ) edges . extend ( p2 ) edges . extend ( c2 ) return create_vertex_buffer ( edges ) | Builds a vertex list adding barycentric coordinates to each vertex . |
16,751 | def get_bin ( self , arch = 'x86' ) : bin_dir = os . path . join ( self . vc_dir , 'bin' ) if arch == 'x86' : arch = '' cl_path = os . path . join ( bin_dir , arch , 'cl.exe' ) link_path = os . path . join ( bin_dir , arch , 'link.exe' ) ml_name = 'ml.exe' if arch in [ 'x86_amd64' , 'amd64' ] : ml_name = 'ml64.exe' ml_path = os . path . join ( bin_dir , arch , ml_name ) if os . path . isfile ( cl_path ) and os . path . isfile ( link_path ) and os . path . isfile ( ml_path ) : logging . info ( _ ( 'using cl.exe: %s' ) , cl_path ) logging . info ( _ ( 'using link.exe: %s' ) , link_path ) logging . info ( _ ( 'using %s: %s' ) , ml_name , ml_path ) run_cl = partial ( run_program , cl_path ) run_link = partial ( run_program , link_path ) run_ml = partial ( run_program , ml_path ) return self . Bin ( run_cl , run_link , run_ml ) logging . debug ( _ ( 'cl.exe not found: %s' ) , cl_path ) logging . debug ( _ ( 'link.exe not found: %s' ) , link_path ) logging . debug ( _ ( '%s not found: %s' ) , ml_name , ml_path ) return self . Bin ( None , None , None ) | Get binaries of Visual C ++ . |
16,752 | def get_inc ( self ) : dirs = [ ] for part in [ '' , 'atlmfc' ] : include = os . path . join ( self . vc_dir , part , 'include' ) if os . path . isdir ( include ) : logging . info ( _ ( 'using include: %s' ) , include ) dirs . append ( include ) else : logging . debug ( _ ( 'include not found: %s' ) , include ) return dirs | Get include directories of Visual C ++ . |
16,753 | def get_lib ( self , arch = 'x86' ) : if arch == 'x86' : arch = '' if arch == 'x64' : arch = 'amd64' lib = os . path . join ( self . vc_dir , 'lib' , arch ) if os . path . isdir ( lib ) : logging . info ( _ ( 'using lib: %s' ) , lib ) return [ lib ] logging . debug ( _ ( 'lib not found: %s' ) , lib ) return [ ] | Get lib directories of Visual C ++ . |
16,754 | def get_bin_and_lib ( self , x64 = False , native = False ) : if x64 : msvc = self . bin64 paths = self . lib64 else : msvc = self . bin32 paths = self . lib if native : arch = 'x64' if x64 else 'x86' paths += self . sdk . get_lib ( arch , native = True ) else : attr = 'lib64' if x64 else 'lib' paths += getattr ( self . sdk , attr ) return msvc , paths | Get bin and lib . |
16,755 | def get_inc ( self , native = False ) : if self . sdk_version == 'v7.0A' : include = os . path . join ( self . sdk_dir , 'include' ) if os . path . isdir ( include ) : logging . info ( _ ( 'using include: %s' ) , include ) return [ include ] logging . debug ( _ ( 'include not found: %s' ) , include ) return [ ] if self . sdk_version == 'v8.1' : dirs = [ ] if native : parts = [ 'km' , os . path . join ( 'km' , 'crt' ) , 'shared' ] else : parts = [ 'um' , 'winrt' , 'shared' ] for part in parts : include = os . path . join ( self . sdk_dir , 'include' , part ) if os . path . isdir ( include ) : logging . info ( _ ( 'using include: %s' ) , include ) dirs . append ( include ) else : logging . debug ( _ ( 'inc not found: %s' ) , include ) return dirs if self . sdk_version == 'v10.0' : dirs = [ ] extra = os . path . join ( 'include' , '10.0.10240.0' ) for mode in [ 'um' , 'ucrt' , 'shared' , 'winrt' ] : include = os . path . join ( self . sdk_dir , extra , mode ) if os . path . isdir ( include ) : logging . info ( _ ( 'using include: %s' ) , include ) dirs . append ( include ) else : logging . debug ( _ ( 'inc not found: %s' ) , include ) return dirs message = 'unknown sdk version: {}' . format ( self . sdk_version ) raise RuntimeError ( message ) | Get include directories of Windows SDK . |
16,756 | def get_lib ( self , arch = 'x86' , native = False ) : if self . sdk_version == 'v7.0A' : if arch == 'x86' : arch = '' lib = os . path . join ( self . sdk_dir , 'lib' , arch ) if os . path . isdir ( lib ) : logging . info ( _ ( 'using lib: %s' ) , lib ) return [ lib ] logging . debug ( _ ( 'lib not found: %s' ) , lib ) return [ ] if self . sdk_version == 'v8.1' : if native : extra = os . path . join ( 'winv6.3' , 'km' ) else : extra = os . path . join ( 'winv6.3' , 'um' ) lib = os . path . join ( self . sdk_dir , 'lib' , extra , arch ) if os . path . isdir ( lib ) : logging . info ( _ ( 'using lib: %s' ) , lib ) return [ lib ] logging . debug ( _ ( 'lib not found: %s' ) , lib ) return [ ] if self . sdk_version == 'v10.0' : dirs = [ ] extra = os . path . join ( 'lib' , '10.0.10240.0' ) for mode in [ 'um' , 'ucrt' ] : lib = os . path . join ( self . sdk_dir , extra , mode , arch ) if os . path . isdir ( lib ) : logging . info ( _ ( 'using lib: %s' ) , lib ) dirs . append ( lib ) else : logging . debug ( _ ( 'lib not found: %s' ) , lib ) return dirs message = 'unknown sdk version: {}' . format ( self . sdk_version ) raise RuntimeError ( message ) | Get lib directories of Windows SDK . |
16,757 | def get_tool_dir ( ) : def _is_comntools ( name ) : return re . match ( r'vs\d+comntools' , name . lower ( ) ) def _get_version_from_name ( name ) : return ( re . search ( r'\d+' , name ) . group ( 0 ) , name ) names = [ name for name in os . environ if _is_comntools ( name ) ] logging . debug ( _ ( 'found vscomntools: %s' ) , names ) versions = [ _get_version_from_name ( name ) for name in names ] logging . debug ( _ ( 'extracted versions: %s' ) , versions ) try : version = max ( versions ) except ValueError : raise OSError ( _ ( 'Failed to find the VSCOMNTOOLS. ' 'Have you installed Visual Studio?' ) ) else : logging . info ( _ ( 'using version: %s' ) , version ) vscomntools = os . environ [ version [ 1 ] ] logging . info ( _ ( 'using vscomntools: %s' ) , vscomntools ) return vscomntools | Get the directory of Visual Studio from environment variables . |
16,758 | def get_vs_dir_from_tool_dir ( self ) : index = self . tool_dir . find ( r'Common7\Tools' ) return self . tool_dir [ : index ] | Get the directory of Visual Studio from the directory Tools . |
16,759 | def get_vc_dir_from_vs_dir ( self ) : vc_dir = os . path . join ( self . vs_dir , 'vc' ) if os . path . isdir ( vc_dir ) : logging . info ( _ ( 'using vc: %s' ) , vc_dir ) return vc_dir logging . debug ( _ ( 'vc not found: %s' ) , vc_dir ) return '' | Get Visual C ++ directory from Visual Studio directory . |
16,760 | def get_sdk_version ( self ) : name = 'VCVarsQueryRegistry.bat' path = os . path . join ( self . tool_dir , name ) batch = read_file ( path ) if not batch : raise RuntimeError ( _ ( 'failed to find the SDK version' ) ) regex = r'(?<=\\Microsoft SDKs\\Windows\\).+?(?=")' try : version = re . search ( regex , batch ) . group ( ) except AttributeError : return '' else : logging . debug ( _ ( 'SDK version: %s' ) , version ) return version | Get the version of Windows SDK from VCVarsQueryRegistry . bat . |
16,761 | def get_sdk_dir ( self ) : if not WINREG : return '' path = r'\Microsoft\Microsoft SDKs\Windows' for node in [ 'SOFTWARE' , r'SOFTWARE\Wow6432Node' ] : for hkey in [ HKEY_LOCAL_MACHINE , HKEY_CURRENT_USER ] : sub_key = node + path + '\\' + self . sdk_version try : key = OpenKey ( hkey , sub_key ) except OSError : logging . debug ( _ ( 'key not found: %s' ) , sub_key ) continue else : logging . info ( _ ( 'using key: %s' ) , sub_key ) value_name = 'InstallationFolder' try : value = QueryValueEx ( key , value_name ) except OSError : return '' logging . info ( _ ( 'using dir: %s' ) , value [ 0 ] ) return value [ 0 ] return '' | Get the directory of Windows SDK from registry . |
16,762 | def main ( self ) : logging . info ( 'Preparing metadata' ) if not self . metadata : self . filer ( ) else : self . objectprep ( ) try : self . threads = int ( self . cpus / len ( self . metadata ) ) if self . cpus / len ( self . metadata ) > 1 else 1 except ( TypeError , ZeroDivisionError ) : self . threads = self . cpus logging . info ( 'Reading and formatting primers' ) self . primers ( ) logging . info ( 'Baiting .fastq files against primers' ) self . bait ( ) logging . info ( 'Baiting .fastq files against previously baited .fastq files' ) self . doublebait ( ) logging . info ( 'Assembling contigs from double-baited .fastq files' ) self . assemble_amplicon_spades ( ) logging . info ( 'Creating BLAST database' ) self . make_blastdb ( ) logging . info ( 'Running BLAST analyses' ) self . blastnthreads ( ) logging . info ( 'Parsing BLAST results' ) self . parseblast ( ) logging . info ( 'Clearing amplicon files from previous iterations' ) self . ampliconclear ( ) logging . info ( 'Creating reports' ) self . reporter ( ) | Run the necessary methods |
16,763 | def objectprep ( self ) : for sample in self . metadata : setattr ( sample , self . analysistype , GenObject ( ) ) sample [ self . analysistype ] . outputdir = os . path . join ( self . path , self . analysistype ) make_path ( sample [ self . analysistype ] . outputdir ) sample [ self . analysistype ] . baitedfastq = os . path . join ( sample [ self . analysistype ] . outputdir , '{at}_targetMatches.fastq.gz' . format ( at = self . analysistype ) ) sample [ self . analysistype ] . filetype = self . filetype if self . filetype == 'fasta' : sample [ self . analysistype ] . assemblyfile = sample . general . bestassemblyfile | If the script is being run as part of a pipeline create and populate the objects for the current analysis |
16,764 | def bait ( self ) : with progressbar ( self . metadata ) as bar : for sample in bar : if sample . general . bestassemblyfile != 'NA' : if sample [ self . analysistype ] . filetype == 'fastq' : if len ( sample . general . fastqfiles ) == 2 : sample [ self . analysistype ] . bbdukcmd = 'bbduk.sh ref={primerfile} k={klength} in1={forward} in2={reverse} ' 'hdist={mismatches} threads={threads} interleaved=t outm={outfile}' . format ( primerfile = self . formattedprimers , klength = self . klength , forward = sample . general . trimmedcorrectedfastqfiles [ 0 ] , reverse = sample . general . trimmedcorrectedfastqfiles [ 1 ] , mismatches = self . mismatches , threads = str ( self . cpus ) , outfile = sample [ self . analysistype ] . baitedfastq ) else : sample [ self . analysistype ] . bbdukcmd = 'bbduk.sh ref={primerfile} k={klength} in={fastq} hdist={mismatches} ' 'threads={threads} interleaved=t outm={outfile}' . format ( primerfile = self . formattedprimers , klength = self . klength , fastq = sample . general . trimmedcorrectedfastqfiles [ 0 ] , mismatches = self . mismatches , threads = str ( self . cpus ) , outfile = sample [ self . analysistype ] . baitedfastq ) if not os . path . isfile ( sample [ self . analysistype ] . baitedfastq ) : run_subprocess ( sample [ self . analysistype ] . bbdukcmd ) | Use bbduk to bait FASTQ reads from input files using the primer file as the target |
16,765 | def doublebait ( self ) : with progressbar ( self . metadata ) as bar : for sample in bar : if sample . general . bestassemblyfile != 'NA' : if sample [ self . analysistype ] . filetype == 'fastq' : sample [ self . analysistype ] . doublebaitedfastq = os . path . join ( sample [ self . analysistype ] . outputdir , '{at}_doubletargetMatches.fastq.gz' . format ( at = self . analysistype ) ) if len ( sample . general . fastqfiles ) == 2 : sample [ self . analysistype ] . bbdukcmd2 = 'bbduk.sh ref={baitfile} in1={forward} in2={reverse} hdist={mismatches} ' 'threads={threads} interleaved=t outm={outfile}' . format ( baitfile = sample [ self . analysistype ] . baitedfastq , forward = sample . general . trimmedcorrectedfastqfiles [ 0 ] , reverse = sample . general . trimmedcorrectedfastqfiles [ 1 ] , mismatches = self . mismatches , threads = str ( self . cpus ) , outfile = sample [ self . analysistype ] . doublebaitedfastq ) else : sample [ self . analysistype ] . bbdukcmd2 = 'bbduk.sh ref={baitfile} in={fastq} hdist={mismatches} threads={threads} ' 'interleaved=t outm={outfile}' . format ( baitfile = sample [ self . analysistype ] . baitedfastq , fastq = sample . general . trimmedcorrectedfastqfiles [ 0 ] , mismatches = self . mismatches , threads = str ( self . cpus ) , outfile = sample [ self . analysistype ] . doublebaitedfastq ) if not os . path . isfile ( sample [ self . analysistype ] . doublebaitedfastq ) : run_subprocess ( sample [ self . analysistype ] . bbdukcmd2 ) | In order to ensure that there is enough sequence data to bridge the gap between the two primers the paired . fastq files produced above will be used to bait the original input . fastq files |
16,766 | def assemble_amplicon_spades ( self ) : for _ in self . metadata : threads = Thread ( target = self . assemble , args = ( ) ) threads . setDaemon ( True ) threads . start ( ) for sample in self . metadata : if sample . general . bestassemblyfile != 'NA' : if sample [ self . analysistype ] . filetype == 'fastq' : sample [ self . analysistype ] . spadesoutput = os . path . join ( sample [ self . analysistype ] . outputdir , self . analysistype ) if len ( sample . general . fastqfiles ) == 2 : sample [ self . analysistype ] . spadescommand = 'spades.py -k {klength} --only-assembler --12 {fastq} -o {outfile} -t {threads}' . format ( klength = self . kmers , fastq = sample [ self . analysistype ] . doublebaitedfastq , outfile = sample [ self . analysistype ] . spadesoutput , threads = self . threads ) else : sample [ self . analysistype ] . spadescommand = 'spades.py -k {klength} --only-assembler -s {fastq} -o {outfile} -t {threads}' . format ( klength = self . kmers , fastq = sample [ self . analysistype ] . doublebaitedfastq , outfile = sample [ self . analysistype ] . spadesoutput , threads = self . threads ) sample [ self . analysistype ] . assemblyfile = os . path . join ( sample [ self . analysistype ] . spadesoutput , 'contigs.fasta' ) self . queue . put ( sample ) self . queue . join ( ) | Use SPAdes to assemble the amplicons using the double - baited . fastq files |
16,767 | def make_blastdb ( self ) : db = os . path . splitext ( self . formattedprimers ) [ 0 ] nhr = '{db}.nhr' . format ( db = db ) if not os . path . isfile ( str ( nhr ) ) : command = 'makeblastdb -in {primerfile} -parse_seqids -max_file_sz 2GB -dbtype nucl -out {outfile}' . format ( primerfile = self . formattedprimers , outfile = db ) run_subprocess ( command ) | Create a BLAST database of the primer file |
16,768 | def ampliconclear ( self ) : for sample in self . metadata : sample [ self . analysistype ] . ampliconfile = os . path . join ( sample [ self . analysistype ] . outputdir , '{sn}_amplicons.fa' . format ( sn = sample . name ) ) try : os . remove ( sample [ self . analysistype ] . ampliconfile ) except IOError : pass | Clear previously created amplicon files to prepare for the appending of data to fresh files |
16,769 | def writeline ( self , line , line_number ) : tmp_file = tempfile . TemporaryFile ( 'w+' ) if not line . endswith ( os . linesep ) : line += os . linesep try : with open ( self . path , 'r' ) as file_handle : for count , new_line in enumerate ( file_handle ) : if count == line_number : new_line = line tmp_file . write ( new_line ) tmp_file . seek ( 0 ) with open ( self . path , 'w' ) as file_handle : for new_line in tmp_file : file_handle . write ( new_line ) finally : tmp_file . close ( ) | Rewrite a single line in the file . |
16,770 | def paths ( self ) : contents = os . listdir ( self . path ) contents = ( os . path . join ( self . path , path ) for path in contents ) contents = ( VenvPath ( path ) for path in contents ) return contents | Get an iter of VenvPaths within the directory . |
16,771 | def shebang ( self ) : with open ( self . path , 'rb' ) as file_handle : hashtag = file_handle . read ( 2 ) if hashtag == b'#!' : file_handle . seek ( 0 ) return file_handle . readline ( ) . decode ( 'utf8' ) return None | Get the file shebang if is has one . |
16,772 | def shebang ( self , new_shebang ) : if not self . shebang : raise ValueError ( 'Cannot modify a shebang if it does not exist.' ) if not new_shebang . startswith ( '#!' ) : raise ValueError ( 'Invalid shebang.' ) self . writeline ( new_shebang , 0 ) | Write a new shebang to the file . |
16,773 | def _find_vpath ( self ) : with open ( self . path , 'r' ) as file_handle : for count , line in enumerate ( file_handle ) : match = self . read_pattern . match ( line ) if match : return match . group ( 1 ) , count return None , None | Find the VIRTUAL_ENV path entry . |
16,774 | def vpath ( self , new_vpath ) : _ , line_number = self . _find_vpath ( ) new_vpath = self . write_pattern . format ( new_vpath ) self . writeline ( new_vpath , line_number ) | Change the path to the virtual environment . |
16,775 | def wrapComponent ( comp ) : if hasattr ( comp , 'paint' ) : return comp current_module = sys . modules [ __name__ ] module_classes = { name [ 1 : ] : obj for name , obj in inspect . getmembers ( sys . modules [ __name__ ] , inspect . isclass ) if obj . __module__ == __name__ } stimclass = comp . __class__ . __name__ qclass = module_classes . get ( stimclass , QStimulusComponent ) return qclass ( comp ) | Wraps a StimulusComponent with a class containing methods for painting and editing . Class will in fact be the same as the component provided but will also be a subclass of QStimulusComponent |
16,776 | def paint ( self , painter , rect , palette ) : painter . save ( ) image = img . default ( ) painter . drawImage ( rect , image ) painter . setPen ( QtGui . QPen ( QtCore . Qt . red ) ) painter . drawText ( rect , QtCore . Qt . AlignLeft , self . __class__ . __name__ ) painter . restore ( ) | Draws a generic visual representation for this component |
16,777 | def replace_tags ( cls , raw_filter ) : for k , v in iter ( cls . known_tags . items ( ) ) : raw_filter = raw_filter . replace ( k , v ) return raw_filter | Searches for known tags in the given string and replaces them with the corresponding regular expression . |
16,778 | def from_string ( cls , raw_filter , rule_limit ) : parsed_filter = cls . replace_tags ( raw_filter ) regexes = cls . build_regex_list ( parsed_filter , rule_limit ) return cls ( regexes ) | Creates a new Filter instance from the given string . |
16,779 | def values ( self ) : result = { } result [ 'fontsz' ] = self . ui . fontszSpnbx . value ( ) result [ 'display_attributes' ] = self . ui . detailWidget . getCheckedDetails ( ) return result | Gets user inputs |
16,780 | def flatten_args ( args : list , join = False , * , empty = ( None , [ ] , ( ) , '' ) ) -> list : flat_args = [ ] non_empty_args = ( arg for arg in args if arg not in empty ) for arg in non_empty_args : if isinstance ( arg , ( list , tuple ) ) : flat_args . extend ( flatten_args ( arg ) ) else : flat_args . append ( str ( arg ) ) if join : join = ' ' if join is True else join flat_args = join . join ( flat_args ) return flat_args | Flatten args and remove empty items . |
16,781 | def load_object ( obj ) -> object : if isinstance ( obj , str ) : if ':' in obj : module_name , obj_name = obj . split ( ':' ) if not module_name : module_name = '.' else : module_name = obj obj = importlib . import_module ( module_name ) if obj_name : attrs = obj_name . split ( '.' ) for attr in attrs : obj = getattr ( obj , attr ) return obj | Load an object . |
16,782 | def escape_args ( cls , * args ) : escaped_args = [ shlex . quote ( str ( arg ) ) for arg in args ] return " " . join ( escaped_args ) | Transforms the given list of unescaped arguments into a suitable shell - escaped str that is ready to be append to the command . |
16,783 | def pages_admin_menu ( context , page ) : request = context . get ( 'request' , None ) expanded = False if request and "tree_expanded" in request . COOKIES : cookie_string = urllib . unquote ( request . COOKIES [ 'tree_expanded' ] ) if cookie_string : ids = [ int ( id ) for id in urllib . unquote ( request . COOKIES [ 'tree_expanded' ] ) . split ( ',' ) ] if page . id in ids : expanded = True context . update ( { 'expanded' : expanded , 'page' : page } ) return context | Render the admin table of pages . |
16,784 | def findArgs ( args , prefixes ) : return list ( [ arg for arg in args if len ( [ p for p in prefixes if arg . lower ( ) . startswith ( p . lower ( ) ) ] ) > 0 ] ) | Extracts the list of arguments that start with any of the specified prefix values |
16,785 | def stripArgs ( args , blacklist ) : blacklist = [ b . lower ( ) for b in blacklist ] return list ( [ arg for arg in args if arg . lower ( ) not in blacklist ] ) | Removes any arguments in the supplied list that are contained in the specified blacklist |
16,786 | def capture ( command , input = None , cwd = None , shell = False , raiseOnError = False ) : proc = subprocess . Popen ( command , stdin = subprocess . PIPE , stdout = subprocess . PIPE , stderr = subprocess . PIPE , cwd = cwd , shell = shell , universal_newlines = True ) ( stdout , stderr ) = proc . communicate ( input ) if raiseOnError == True and proc . returncode != 0 : raise Exception ( 'child process ' + str ( command ) + ' failed with exit code ' + str ( proc . returncode ) + '\nstdout: "' + stdout + '"' + '\nstderr: "' + stderr + '"' ) return CommandOutput ( proc . returncode , stdout , stderr ) | Executes a child process and captures its output |
16,787 | def run ( command , cwd = None , shell = False , raiseOnError = False ) : returncode = subprocess . call ( command , cwd = cwd , shell = shell ) if raiseOnError == True and returncode != 0 : raise Exception ( 'child process ' + str ( command ) + ' failed with exit code ' + str ( returncode ) ) return returncode | Executes a child process and waits for it to complete |
16,788 | def setEngineRootOverride ( self , rootDir ) : ConfigurationManager . setConfigKey ( 'rootDirOverride' , os . path . abspath ( rootDir ) ) try : self . getEngineVersion ( ) except : print ( 'Warning: the specified directory does not appear to contain a valid version of the Unreal Engine.' ) | Sets a user - specified directory as the root engine directory overriding any auto - detection |
16,789 | def getEngineRoot ( self ) : if not hasattr ( self , '_engineRoot' ) : self . _engineRoot = self . _getEngineRoot ( ) return self . _engineRoot | Returns the root directory location of the latest installed version of UE4 |
16,790 | def getEngineVersion ( self , outputFormat = 'full' ) : version = self . _getEngineVersionDetails ( ) formats = { 'major' : version [ 'MajorVersion' ] , 'minor' : version [ 'MinorVersion' ] , 'patch' : version [ 'PatchVersion' ] , 'full' : '{}.{}.{}' . format ( version [ 'MajorVersion' ] , version [ 'MinorVersion' ] , version [ 'PatchVersion' ] ) , 'short' : '{}.{}' . format ( version [ 'MajorVersion' ] , version [ 'MinorVersion' ] ) } if outputFormat not in formats : raise Exception ( 'unreconised version output format "{}"' . format ( outputFormat ) ) return formats [ outputFormat ] | Returns the version number of the latest installed version of UE4 |
16,791 | def getEngineChangelist ( self ) : version = self . _getEngineVersionDetails ( ) if 'CompatibleChangelist' in version : return int ( version [ 'CompatibleChangelist' ] ) else : return int ( version [ 'Changelist' ] ) | Returns the compatible Perforce changelist identifier for the latest installed version of UE4 |
16,792 | def isInstalledBuild ( self ) : sentinelFile = os . path . join ( self . getEngineRoot ( ) , 'Engine' , 'Build' , 'InstalledBuild.txt' ) return os . path . exists ( sentinelFile ) | Determines if the Engine is an Installed Build |
16,793 | def getEditorBinary ( self , cmdVersion = False ) : return os . path . join ( self . getEngineRoot ( ) , 'Engine' , 'Binaries' , self . getPlatformIdentifier ( ) , 'UE4Editor' + self . _editorPathSuffix ( cmdVersion ) ) | Determines the location of the UE4Editor binary |
16,794 | def getProjectDescriptor ( self , dir ) : for project in glob . glob ( os . path . join ( dir , '*.uproject' ) ) : return os . path . realpath ( project ) raise UnrealManagerException ( 'could not detect an Unreal project in the current directory' ) | Detects the . uproject descriptor file for the Unreal project in the specified directory |
16,795 | def getPluginDescriptor ( self , dir ) : for plugin in glob . glob ( os . path . join ( dir , '*.uplugin' ) ) : return os . path . realpath ( plugin ) raise UnrealManagerException ( 'could not detect an Unreal plugin in the current directory' ) | Detects the . uplugin descriptor file for the Unreal plugin in the specified directory |
16,796 | def getDescriptor ( self , dir ) : try : return self . getProjectDescriptor ( dir ) except : try : return self . getPluginDescriptor ( dir ) except : raise UnrealManagerException ( 'could not detect an Unreal project or plugin in the directory "{}"' . format ( dir ) ) | Detects the descriptor file for either an Unreal project or an Unreal plugin in the specified directory |
16,797 | def listThirdPartyLibs ( self , configuration = 'Development' ) : interrogator = self . _getUE4BuildInterrogator ( ) return interrogator . list ( self . getPlatformIdentifier ( ) , configuration , self . _getLibraryOverrides ( ) ) | Lists the supported Unreal - bundled third - party libraries |
16,798 | def getThirdpartyLibs ( self , libs , configuration = 'Development' , includePlatformDefaults = True ) : if includePlatformDefaults == True : libs = self . _defaultThirdpartyLibs ( ) + libs interrogator = self . _getUE4BuildInterrogator ( ) return interrogator . interrogate ( self . getPlatformIdentifier ( ) , configuration , libs , self . _getLibraryOverrides ( ) ) | Retrieves the ThirdPartyLibraryDetails instance for Unreal - bundled versions of the specified third - party libraries |
16,799 | def getThirdPartyLibCompilerFlags ( self , libs ) : fmt = PrintingFormat . singleLine ( ) if libs [ 0 ] == '--multiline' : fmt = PrintingFormat . multiLine ( ) libs = libs [ 1 : ] platformDefaults = True if libs [ 0 ] == '--nodefaults' : platformDefaults = False libs = libs [ 1 : ] details = self . getThirdpartyLibs ( libs , includePlatformDefaults = platformDefaults ) return details . getCompilerFlags ( self . getEngineRoot ( ) , fmt ) | Retrieves the compiler flags for building against the Unreal - bundled versions of the specified third - party libraries |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.