idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
25,900 | def play_from_queue ( self , index , start = True ) : if not self . speaker_info : self . get_speaker_info ( ) uri = 'x-rincon-queue:{0}#0' . format ( self . uid ) self . avTransport . SetAVTransportURI ( [ ( 'InstanceID' , 0 ) , ( 'CurrentURI' , uri ) , ( 'CurrentURIMetaData' , '' ) ] ) self . avTransport . Seek ( [ (... | Play a track from the queue by index . |
25,901 | def play_uri ( self , uri = '' , meta = '' , title = '' , start = True , force_radio = False ) : if meta == '' and title != '' : meta_template = '<DIDL-Lite xmlns:dc="http://purl.org/dc/elements' '/1.1/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" ' 'xmlns:r="urn:schemas-rinconnetworks-com:metadata-1-0/" ' 'xm... | Play a URI . |
25,902 | def volume ( self , volume ) : volume = int ( volume ) volume = max ( 0 , min ( volume , 100 ) ) self . renderingControl . SetVolume ( [ ( 'InstanceID' , 0 ) , ( 'Channel' , 'Master' ) , ( 'DesiredVolume' , volume ) ] ) | Set the speaker s volume . |
25,903 | def bass ( self , bass ) : bass = int ( bass ) bass = max ( - 10 , min ( bass , 10 ) ) self . renderingControl . SetBass ( [ ( 'InstanceID' , 0 ) , ( 'DesiredBass' , bass ) ] ) | Set the speaker s bass . |
25,904 | def treble ( self , treble ) : treble = int ( treble ) treble = max ( - 10 , min ( treble , 10 ) ) self . renderingControl . SetTreble ( [ ( 'InstanceID' , 0 ) , ( 'DesiredTreble' , treble ) ] ) | Set the speaker s treble . |
25,905 | def _parse_zone_group_state ( self ) : def parse_zone_group_member ( member_element ) : member_attribs = member_element . attrib ip_addr = member_attribs [ 'Location' ] . split ( '//' ) [ 1 ] . split ( ':' ) [ 0 ] zone = config . SOCO_CLASS ( ip_addr ) zone . _uid = member_attribs [ 'UUID' ] zone . _player_name = membe... | The Zone Group State contains a lot of useful information . |
25,906 | def partymode ( self ) : [ zone . join ( self ) for zone in self . visible_zones if zone is not self ] | Put all the speakers in the network in the same group a . k . a Party Mode . |
25,907 | def switch_to_line_in ( self , source = None ) : if source : uid = source . uid else : uid = self . uid self . avTransport . SetAVTransportURI ( [ ( 'InstanceID' , 0 ) , ( 'CurrentURI' , 'x-rincon-stream:{0}' . format ( uid ) ) , ( 'CurrentURIMetaData' , '' ) ] ) | Switch the speaker s input to line - in . |
25,908 | def get_current_track_info ( self ) : response = self . avTransport . GetPositionInfo ( [ ( 'InstanceID' , 0 ) , ( 'Channel' , 'Master' ) ] ) track = { 'title' : '' , 'artist' : '' , 'album' : '' , 'album_art' : '' , 'position' : '' } track [ 'playlist_position' ] = response [ 'Track' ] track [ 'duration' ] = response ... | Get information about the currently playing track . |
25,909 | def get_speaker_info ( self , refresh = False , timeout = None ) : if self . speaker_info and refresh is False : return self . speaker_info else : response = requests . get ( 'http://' + self . ip_address + ':1400/xml/device_description.xml' , timeout = timeout ) dom = XML . fromstring ( response . content ) device = d... | Get information about the Sonos speaker . |
25,910 | def get_current_transport_info ( self ) : response = self . avTransport . GetTransportInfo ( [ ( 'InstanceID' , 0 ) , ] ) playstate = { 'current_transport_status' : '' , 'current_transport_state' : '' , 'current_transport_speed' : '' } playstate [ 'current_transport_state' ] = response [ 'CurrentTransportState' ] plays... | Get the current playback state . |
25,911 | def get_queue ( self , start = 0 , max_items = 100 , full_album_art_uri = False ) : queue = [ ] response = self . contentDirectory . Browse ( [ ( 'ObjectID' , 'Q:0' ) , ( 'BrowseFlag' , 'BrowseDirectChildren' ) , ( 'Filter' , '*' ) , ( 'StartingIndex' , start ) , ( 'RequestedCount' , max_items ) , ( 'SortCriteria' , ''... | Get information about the queue . |
25,912 | def add_uri_to_queue ( self , uri , position = 0 , as_next = False ) : res = [ DidlResource ( uri = uri , protocol_info = "x-rincon-playlist:*:*:*" ) ] item = DidlObject ( resources = res , title = '' , parent_id = '' , item_id = '' ) return self . add_to_queue ( item , position , as_next ) | Add the URI to the queue . |
25,913 | def add_to_queue ( self , queueable_item , position = 0 , as_next = False ) : metadata = to_didl_string ( queueable_item ) response = self . avTransport . AddURIToQueue ( [ ( 'InstanceID' , 0 ) , ( 'EnqueuedURI' , queueable_item . resources [ 0 ] . uri ) , ( 'EnqueuedURIMetaData' , metadata ) , ( 'DesiredFirstTrackNumb... | Add a queueable item to the queue . |
25,914 | def add_multiple_to_queue ( self , items , container = None ) : if container is not None : container_uri = container . resources [ 0 ] . uri container_metadata = to_didl_string ( container ) else : container_uri = '' container_metadata = '' chunk_size = 16 item_list = list ( items ) for index in range ( 0 , len ( item_... | Add a sequence of items to the queue . |
25,915 | def remove_from_queue ( self , index ) : updid = '0' objid = 'Q:0/' + str ( index + 1 ) self . avTransport . RemoveTrackFromQueue ( [ ( 'InstanceID' , 0 ) , ( 'ObjectID' , objid ) , ( 'UpdateID' , updid ) , ] ) | Remove a track from the queue by index . The index number is required as an argument where the first index is 0 . |
25,916 | def get_favorite_radio_shows ( self , start = 0 , max_items = 100 ) : message = 'The output type of this method will probably change in ' 'the future to use SoCo data structures' warnings . warn ( message , stacklevel = 2 ) return self . __get_favorites ( RADIO_SHOWS , start , max_items ) | Get favorite radio shows from Sonos Radio app . |
25,917 | def get_favorite_radio_stations ( self , start = 0 , max_items = 100 ) : message = 'The output type of this method will probably change in ' 'the future to use SoCo data structures' warnings . warn ( message , stacklevel = 2 ) return self . __get_favorites ( RADIO_STATIONS , start , max_items ) | Get favorite radio stations from Sonos Radio app . |
25,918 | def get_sonos_favorites ( self , start = 0 , max_items = 100 ) : message = 'The output type of this method will probably change in ' 'the future to use SoCo data structures' warnings . warn ( message , stacklevel = 2 ) return self . __get_favorites ( SONOS_FAVORITES , start , max_items ) | Get Sonos favorites . |
25,919 | def create_sonos_playlist ( self , title ) : response = self . avTransport . CreateSavedQueue ( [ ( 'InstanceID' , 0 ) , ( 'Title' , title ) , ( 'EnqueuedURI' , '' ) , ( 'EnqueuedURIMetaData' , '' ) , ] ) item_id = response [ 'AssignedObjectID' ] obj_id = item_id . split ( ':' , 2 ) [ 1 ] uri = "file:///jffs/settings/s... | Create a new empty Sonos playlist . |
25,920 | def create_sonos_playlist_from_queue ( self , title ) : response = self . avTransport . SaveQueue ( [ ( 'InstanceID' , 0 ) , ( 'Title' , title ) , ( 'ObjectID' , '' ) ] ) item_id = response [ 'AssignedObjectID' ] obj_id = item_id . split ( ':' , 2 ) [ 1 ] uri = "file:///jffs/settings/savedqueues.rsq#{0}" . format ( obj... | Create a new Sonos playlist from the current queue . |
25,921 | def remove_sonos_playlist ( self , sonos_playlist ) : object_id = getattr ( sonos_playlist , 'item_id' , sonos_playlist ) return self . contentDirectory . DestroyObject ( [ ( 'ObjectID' , object_id ) ] ) | Remove a Sonos playlist . |
25,922 | def add_item_to_sonos_playlist ( self , queueable_item , sonos_playlist ) : response , _ = self . music_library . _music_lib_search ( sonos_playlist . item_id , 0 , 1 ) update_id = response [ 'UpdateID' ] metadata = to_didl_string ( queueable_item ) self . avTransport . AddURIToSavedQueue ( [ ( 'InstanceID' , 0 ) , ( '... | Adds a queueable item to a Sonos playlist . |
25,923 | def get_sleep_timer ( self ) : resp = self . avTransport . GetRemainingSleepTimerDuration ( [ ( 'InstanceID' , 0 ) , ] ) if resp [ 'RemainingSleepTimerDuration' ] : times = resp [ 'RemainingSleepTimerDuration' ] . split ( ':' ) return ( int ( times [ 0 ] ) * 3600 + int ( times [ 1 ] ) * 60 + int ( times [ 2 ] ) ) else ... | Retrieves remaining sleep time if any |
25,924 | def get_sonos_playlist_by_attr ( self , attr_name , match ) : for sonos_playlist in self . get_sonos_playlists ( ) : if getattr ( sonos_playlist , attr_name ) == match : return sonos_playlist raise ValueError ( 'No match on "{0}" for value "{1}"' . format ( attr_name , match ) ) | Return the first Sonos Playlist DidlPlaylistContainer that matches the attribute specified . |
25,925 | def really_unicode ( in_string ) : if isinstance ( in_string , StringType ) : for args in ( ( 'utf-8' , ) , ( 'latin-1' , ) , ( 'ascii' , 'replace' ) ) : try : in_string = in_string . decode ( * args ) break except UnicodeDecodeError : continue if not isinstance ( in_string , UnicodeType ) : raise ValueError ( '%s is n... | Make a string unicode . Really . |
25,926 | def camel_to_underscore ( string ) : string = FIRST_CAP_RE . sub ( r'\1_\2' , string ) return ALL_CAP_RE . sub ( r'\1_\2' , string ) . lower ( ) | Convert camelcase to lowercase and underscore . |
25,927 | def prettify ( unicode_text ) : import xml . dom . minidom reparsed = xml . dom . minidom . parseString ( unicode_text . encode ( 'utf-8' ) ) return reparsed . toprettyxml ( indent = " " , newl = "\n" ) | Return a pretty - printed version of a unicode XML string . |
25,928 | def prepare_headers ( self , http_headers , soap_action ) : headers = { 'Content-Type' : 'text/xml; charset="utf-8"' } if soap_action is not None : headers . update ( { 'SOAPACTION' : '"{}"' . format ( soap_action ) } ) if http_headers is not None : headers . update ( http_headers ) return headers | Prepare the http headers for sending . |
25,929 | def prepare_soap_body ( self , method , parameters , namespace ) : tags = [ ] for name , value in parameters : tag = "<{name}>{value}</{name}>" . format ( name = name , value = escape ( "%s" % value , { '"' : """ } ) ) tags . append ( tag ) wrapped_params = "" . join ( tags ) if namespace is not None : soap_body =... | Prepare the SOAP message body for sending . |
25,930 | def prepare_soap_envelope ( self , prepared_soap_header , prepared_soap_body ) : soap_env_template = ( '<?xml version="1.0"?>' '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"' ' s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' '{soap_header}' '<s:Body>' '{soap_body}' '</s:Body>' '</s:Envel... | Prepare the SOAP Envelope for sending . |
25,931 | def prepare ( self ) : headers = self . prepare_headers ( self . http_headers , self . soap_action ) soap_header = self . prepare_soap_header ( self . soap_header ) soap_body = self . prepare_soap_body ( self . method , self . parameters , self . namespace ) data = self . prepare_soap_envelope ( soap_header , soap_body... | Prepare the SOAP message for sending to the server . |
25,932 | def call ( self ) : headers , data = self . prepare ( ) if _LOG . isEnabledFor ( logging . DEBUG ) : _LOG . debug ( "Sending %s, %s" , headers , prettify ( data ) ) response = requests . post ( self . endpoint , headers = headers , data = data . encode ( 'utf-8' ) , ** self . request_args ) _LOG . debug ( "Received %s,... | Call the SOAP method on the server . |
25,933 | def __build_option_parser ( ) : description = description = textwrap . dedent ( description ) . strip ( ) parser = argparse . ArgumentParser ( description = description , formatter_class = argparse . RawTextHelpFormatter ) parser . add_argument ( 'file_' , metavar = 'FILE' , type = str , nargs = 1 , help = 'the file to... | Build the option parser for this script |
25,934 | def main ( ) : parser = __build_option_parser ( ) args = parser . parse_args ( ) analyze_ws = AnalyzeWS ( args ) try : analyze_ws . set_file ( args . file_ [ 0 ] ) except IOError : print 'IOError raised while reading file. Exiting!' sys . exit ( 3 ) if args . to_file or args . to_browser : analyze_ws . to_file_mode ( )... | Main method of the script |
25,935 | def set_file ( self , filename ) : if self . output_prefix is None : _ , self . output_prefix = os . path . split ( filename ) if not ( os . path . isfile ( filename ) and os . access ( filename , os . R_OK ) ) : print 'The file \'{0}\' is either not present or not readable. ' 'Exiting!' . format ( filename ) sys . exi... | Analyse the file with the captured content |
25,936 | def _parse_load ( self , load ) : if load in [ '??' ] : self . _debug ( 'IGNORING' ) elif any ( [ start in load for start in STARTS ] ) : self . _debug ( 'START' ) self . messages . append ( WSPart ( load , self . args ) ) if any ( [ end in load for end in ENDS ] ) : self . messages [ - 1 ] . finalize_content ( ) self ... | Parse the load from a single packet |
25,937 | def _debug ( self , message , load = False , no_prefix = False ) : if self . args . debug_analysis : if load : message = '\r\n' . join ( [ '# ' + line for line in message . strip ( ) . split ( '\r\n' ) ] ) print '{0}\n{1}\n{0}' . format ( '#' * 78 , message ) else : if ( len ( self . messages ) > 0 and not self . messa... | Output debug information |
25,938 | def to_file_mode ( self ) : for message_no in range ( len ( self . messages ) ) : self . __to_file ( message_no ) | Write all the messages to files |
25,939 | def __to_file ( self , message_no ) : filename = self . __create_file_name ( message_no ) try : with codecs . open ( filename , mode = 'w' , encoding = self . messages [ message_no ] . encoding ) as file__ : file__ . write ( self . messages [ message_no ] . output ) except IOError as excep : print 'Unable for open the ... | Write a single message to file |
25,940 | def __create_file_name ( self , message_no ) : cwd = os . getcwd ( ) filename = '{0}_{1}.xml' . format ( self . output_prefix , message_no ) return os . path . join ( cwd , filename ) | Create the filename to save to |
25,941 | def to_browser_mode ( self ) : for message_no in range ( len ( self . messages ) ) : self . __to_browser ( message_no ) | Write all the messages to files and open them in the browser |
25,942 | def __to_browser ( self , message_no ) : filename = self . __to_file ( message_no ) try : command = self . config . get ( 'General' , 'browser_command' ) except ( ConfigParser . NoOptionError , AttributeError ) : print 'Incorrect or missing .ini file. See --help.' sys . exit ( 5 ) command = str ( command ) . format ( f... | Write a single message to file and open the file in a browser |
25,943 | def __update_window ( self , width , height , message_no , page_no ) : file_exists_label = '-F-ILE' if not os . path . exists ( self . __create_file_name ( message_no ) ) : file_exists_label = '(f)ile' if PLATFORM == 'win32' : for _ in range ( 50 ) : print else : sys . stdout . write ( '\x1b[2J\x1b[H' ) content = self ... | Update the window with the menu and the new text |
25,944 | def _form_pages ( self , message_no , content , out , height , width ) : self . pages [ message_no ] = [ ] page_height = height - 4 outline = u'' no_lines_page = 0 for original , formatted in zip ( content . split ( '\n' ) , out . split ( '\n' ) ) : no_lines_original = int ( math . ceil ( len ( original ) / float ( wid... | Form the pages |
25,945 | def finalize_content ( self ) : self . write_closed = True body = self . raw_body . decode ( self . encoding ) self . _init_xml ( body ) self . _form_output ( ) | Finalize the additons |
25,946 | def _init_xml ( self , body ) : tree = etree . fromstring ( body . encode ( self . encoding ) , PARSER ) for text in tree . xpath ( './/text()[contains(., "DIDL")]' ) : item = text . getparent ( ) didl_tree = etree . fromstring ( item . text ) if self . external_inner_xml : item . text = 'DIDL_REPLACEMENT_{0}' . format... | Parse the present body as xml |
25,947 | def _form_output ( self ) : self . output = u'' if self . external_inner_xml : self . output += u'<Dummy_tag_to_create_valid_xml_on_external_inner' '_xml>\n' self . output += u'<!-- BODY . format ( self . body_formatted ) if self . external_inner_xml : for number , didl in enumerate ( self . inner_xml ) : self . outpu... | Form the output |
25,948 | def attempt_datastructure_upgrade ( didl_item ) : try : resource = didl_item . resources [ 0 ] except IndexError : _LOG . debug ( 'Upgrade not possible, no resources' ) return didl_item if resource . uri . startswith ( 'x-sonos-http' ) : uri = resource . uri path = urlparse ( uri ) . path path = path . rsplit ( '.' , 1... | Attempt to upgrade a didl_item to a music services data structure if it originates from a music services |
25,949 | def from_name ( cls , fullname , soco , * args , ** kwargs ) : _LOG . info ( 'Loading plugin %s' , fullname ) parts = fullname . split ( '.' ) modname = '.' . join ( parts [ : - 1 ] ) clsname = parts [ - 1 ] mod = importlib . import_module ( modname ) class_ = getattr ( mod , clsname ) _LOG . info ( 'Loaded class %s' ,... | Instantiate a plugin by its full name . |
25,950 | def get_ms_item ( xml , service , parent_id ) : cls = MS_TYPE_TO_CLASS . get ( xml . findtext ( ns_tag ( 'ms' , 'itemType' ) ) ) out = cls . from_xml ( xml , service , parent_id ) return out | Return the music service item that corresponds to xml . |
25,951 | def tags_with_text ( xml , tags = None ) : if tags is None : tags = [ ] for element in xml : if element . text is not None : tags . append ( element ) elif len ( element ) > 0 : tags_with_text ( element , tags ) else : message = 'Unknown XML structure: {}' . format ( element ) raise ValueError ( message ) return tags | Return a list of tags that contain text retrieved recursively from an XML tree . |
25,952 | def from_xml ( cls , xml , service , parent_id ) : content = { 'description' : service . description , 'service_id' : service . service_id , 'parent_id' : parent_id } all_text_elements = tags_with_text ( xml ) for item in all_text_elements : tag = item . tag [ len ( NAMESPACES [ 'ms' ] ) + 2 : ] tag = camel_to_undersco... | Return a Music Service item generated from xml . |
25,953 | def from_dict ( cls , dict_in ) : kwargs = dict_in . copy ( ) args = [ kwargs . pop ( key ) for key in cls . required_fields ] return cls ( * args , ** kwargs ) | Initialize the class from a dict . |
25,954 | def didl_metadata ( self ) : if not self . can_play : message = 'This item is not meant to be played and therefore ' 'also not to create its own didl_metadata' raise DIDLMetadataError ( message ) for key in [ 'extended_id' , 'title' , 'item_class' ] : if not hasattr ( self , key ) : message = 'The property \'{}\' is no... | Return the DIDL metadata for a Music Service Track . |
25,955 | def get_alarms ( zone = None ) : if zone is None : zone = discovery . any_soco ( ) response = zone . alarmClock . ListAlarms ( ) alarm_list = response [ 'CurrentAlarmList' ] tree = XML . fromstring ( alarm_list . encode ( 'utf-8' ) ) alarms = tree . findall ( 'Alarm' ) result = set ( ) for alarm in alarms : values = al... | Get a set of all alarms known to the Sonos system . |
25,956 | def play_mode ( self , play_mode ) : play_mode = play_mode . upper ( ) if play_mode not in PLAY_MODES : raise KeyError ( "'%s' is not a valid play mode" % play_mode ) self . _play_mode = play_mode | See playmode . |
25,957 | def volume ( self , volume ) : volume = int ( volume ) self . _volume = max ( 0 , min ( volume , 100 ) ) | See volume . |
25,958 | def recurrence ( self , recurrence ) : if not is_valid_recurrence ( recurrence ) : raise KeyError ( "'%s' is not a valid recurrence value" % recurrence ) self . _recurrence = recurrence | See recurrence . |
25,959 | def save ( self ) : args = [ ( 'StartLocalTime' , self . start_time . strftime ( TIME_FORMAT ) ) , ( 'Duration' , '' if self . duration is None else self . duration . strftime ( TIME_FORMAT ) ) , ( 'Recurrence' , self . recurrence ) , ( 'Enabled' , '1' if self . enabled else '0' ) , ( 'RoomUUID' , self . zone . uid ) ,... | Save the alarm to the Sonos system . |
25,960 | def remove ( self ) : self . zone . alarmClock . DestroyAlarm ( [ ( 'ID' , self . _alarm_id ) ] ) alarm_id = self . _alarm_id try : del Alarm . _all_alarms [ alarm_id ] except KeyError : pass self . _alarm_id = None | Remove the alarm from the Sonos system . |
25,961 | def main ( ) : parser = argparse . ArgumentParser ( prog = '' , description = 'Dump data about Sonos services' ) parser . add_argument ( '-d' , '--device' , default = None , help = "The ip address of the device to query. " "If none is supplied, a random device will be used" ) parser . add_argument ( '-s' , '--service' ... | Run the main script |
25,962 | def print_details ( srv ) : name = srv . service_type box = "=" * 79 print ( "{0}\n|{1:^77}|\n{0}\n" . format ( box , name ) ) for action in srv . iter_actions ( ) : print ( action . name ) print ( "~" * len ( action . name ) ) print ( "\n Input" ) for arg in action . in_args : print ( " " , arg ) print ( "\n Outp... | Print the details of a service |
25,963 | def snapshot ( self ) : self . is_coordinator = self . device . is_coordinator media_info = self . device . avTransport . GetMediaInfo ( [ ( 'InstanceID' , 0 ) ] ) self . media_uri = media_info [ 'CurrentURI' ] if self . media_uri . split ( ':' ) [ 0 ] == 'x-rincon-queue' : if self . media_uri . split ( '#' ) [ 1 ] == ... | Record and store the current state of a device . |
25,964 | def _save_queue ( self ) : if self . queue is not None : batch_size = 400 total = 0 num_return = batch_size while num_return == batch_size : queue_items = self . device . get_queue ( total , batch_size ) num_return = len ( queue_items ) if num_return > 0 : self . queue . append ( queue_items ) total = total + num_retur... | Save the current state of the queue . |
25,965 | def _restore_queue ( self ) : if self . queue is not None : self . device . clear_queue ( ) for queue_group in self . queue : for queue_item in queue_group : self . device . add_uri_to_queue ( queue_item . uri ) | Restore the previous state of the queue . |
25,966 | def default_params ( model , update_dict = None ) : if model in parameters : params = parameters [ model ] . copy ( ) else : params = None if update_dict : if params is None : params = { } params . update ( update_dict ) return params | Loads and updates default model parameters |
25,967 | def describe ( x , reduce = 'IncrementalPCA' , max_dims = None , show = True , format_data = True ) : warnings . warn ( 'When input data is large, this computation can take a long time.' ) def summary ( x , max_dims = None ) : if type ( x ) is list : x = np . vstack ( x ) if max_dims is None : if x . shape [ 1 ] > x . ... | Create plot describing covariance with as a function of number of dimensions |
25,968 | def missing_inds ( x , format_data = True ) : if format_data : x = formatter ( x , ppca = False ) inds = [ ] for arr in x : if np . argwhere ( np . isnan ( arr ) ) . size is 0 : inds . append ( None ) else : inds . append ( np . argwhere ( np . isnan ( arr ) ) [ : , 0 ] ) if len ( inds ) > 1 : return inds else : return... | Returns indices of missing data |
25,969 | def normalize ( x , normalize = 'across' , internal = False , format_data = True ) : assert normalize in [ 'across' , 'within' , 'row' , False , None ] , "scale_type must be across, within, row or none." if normalize in [ False , None ] : return x else : if format_data : x = formatter ( x , ppca = True ) zscore = lambd... | Z - transform the columns or rows of an array or list of arrays |
25,970 | def _init_structures ( self , data , subjects ) : x = [ ] mu = [ ] rho2 = np . zeros ( subjects ) trace_xtx = np . zeros ( subjects ) for subject in range ( subjects ) : mu . append ( np . mean ( data [ subject ] , 1 ) ) rho2 [ subject ] = 1 trace_xtx [ subject ] = np . sum ( data [ subject ] ** 2 ) x . append ( data [... | Initializes data structures for SRM and preprocess the data . |
25,971 | def _likelihood ( self , chol_sigma_s_rhos , log_det_psi , chol_sigma_s , trace_xt_invsigma2_x , inv_sigma_s_rhos , wt_invpsi_x , samples ) : log_det = ( np . log ( np . diag ( chol_sigma_s_rhos ) ** 2 ) . sum ( ) + log_det_psi + np . log ( np . diag ( chol_sigma_s ) ** 2 ) . sum ( ) ) loglikehood = - 0.5 * samples * l... | Calculate the log - likelihood function |
25,972 | def fit ( self , X , y = None ) : logger . info ( 'Starting Deterministic SRM' ) if len ( X ) <= 1 : raise ValueError ( "There are not enough subjects " "({0:d}) to train the model." . format ( len ( X ) ) ) if X [ 0 ] . shape [ 1 ] < self . features : raise ValueError ( "There are not enough samples to train the model... | Compute the Deterministic Shared Response Model |
25,973 | def _objective_function ( self , data , w , s ) : subjects = len ( data ) objective = 0.0 for m in range ( subjects ) : objective += np . linalg . norm ( data [ m ] - w [ m ] . dot ( s ) , 'fro' ) ** 2 return objective * 0.5 / data [ 0 ] . shape [ 1 ] | Calculate the objective function |
25,974 | def text2mat ( data , vectorizer = 'CountVectorizer' , semantic = 'LatentDirichletAllocation' , corpus = 'wiki' ) : if semantic is None : semantic = 'LatentDirichletAllocation' if vectorizer is None : vectorizer = 'CountVectorizer' model_is_fit = False if corpus is not None : if corpus in ( 'wiki' , 'nips' , 'sotus' , ... | Turns a list of text samples into a matrix using a vectorizer and a text model |
25,975 | def patch_lines ( x ) : for idx in range ( len ( x ) - 1 ) : x [ idx ] = np . vstack ( [ x [ idx ] , x [ idx + 1 ] [ 0 , : ] ] ) return x | Draw lines between groups |
25,976 | def check_geo ( geo ) : geo = copy . copy ( geo ) def fix_item ( item ) : if isinstance ( item , six . binary_type ) : return item . decode ( ) return item def fix_list ( lst ) : return [ fix_item ( i ) for i in lst ] if isinstance ( geo . reduce , six . binary_type ) : geo . reduce = geo . reduce . decode ( ) for key ... | Checks a geo and makes sure the text fields are not binary |
25,977 | def df2mat ( data , return_labels = False ) : df_str = data . select_dtypes ( include = [ 'object' ] ) df_num = data . select_dtypes ( exclude = [ 'object' ] ) for colname in df_str . columns : df_num = df_num . join ( pd . get_dummies ( data [ colname ] , prefix = colname ) ) plot_data = df_num . as_matrix ( ) labels ... | Transforms a Pandas DataFrame into a Numpy array with binarized text columns |
25,978 | def load ( dataset , reduce = None , ndims = None , align = None , normalize = None ) : if dataset [ - 4 : ] == '.geo' : geo = dd . io . load ( dataset ) if 'dtype' in geo : if 'list' in geo [ 'dtype' ] : geo [ 'data' ] = list ( geo [ 'data' ] ) elif 'df' in geo [ 'dtype' ] : geo [ 'data' ] = pd . DataFrame ( geo [ 'da... | Load a . geo file or example data |
25,979 | def transform ( self , data = None ) : if data is None : return self . xform_data else : formatted = format_data ( data , semantic = self . semantic , vectorizer = self . vectorizer , corpus = self . corpus , ppca = True ) norm = normalizer ( formatted , normalize = self . normalize ) reduction = reducer ( norm , reduc... | Return transformed data or transform new data using the same model parameters |
25,980 | def save ( self , fname , compression = 'blosc' ) : if hasattr ( self , 'dtype' ) : if 'list' in self . dtype : data = np . array ( self . data ) elif 'df' in self . dtype : data = { k : np . array ( v ) . astype ( 'str' ) for k , v in self . data . to_dict ( 'list' ) . items ( ) } else : data = self . data geo = { 'da... | Save method for the data geometry object |
25,981 | def analyze ( data , normalize = None , reduce = None , ndims = None , align = None , internal = False ) : return aligner ( reducer ( normalizer ( data , normalize = normalize , internal = internal ) , reduce = reduce , ndims = ndims , internal = internal ) , align = align ) | Wrapper function for normalize - > reduce - > align transformations . |
25,982 | def reduce ( x , reduce = 'IncrementalPCA' , ndims = None , normalize = None , align = None , model = None , model_params = None , internal = False , format_data = True ) : if ( model is not None ) or ( model_params is not None ) : warnings . warn ( 'Model and model params will be deprecated. Please use the \ ... | Reduces dimensionality of an array or list of arrays |
25,983 | def cluster ( x , cluster = 'KMeans' , n_clusters = 3 , ndims = None , format_data = True ) : if cluster == None : return x elif ( isinstance ( cluster , six . string_types ) and cluster == 'HDBSCAN' ) or ( isinstance ( cluster , dict ) and cluster [ 'model' ] == 'HDBSCAN' ) : if not _has_hdbscan : raise ImportError ( ... | Performs clustering analysis and returns a list of cluster labels |
25,984 | def build_grab_exception ( ex , curl ) : if ex . args [ 0 ] == 23 : if getattr ( curl , 'grab_callback_interrupted' , None ) is True : return None else : return error . GrabNetworkError ( ex . args [ 1 ] , ex ) else : if ex . args [ 0 ] == 28 : return error . GrabTimeoutError ( ex . args [ 1 ] , ex ) elif ex . args [ 0... | Build Grab exception from the pycurl exception |
25,985 | def body_processor ( self , chunk ) : if self . config_nobody : self . curl . grab_callback_interrupted = True return 0 bytes_read = len ( chunk ) self . response_body_bytes_read += bytes_read if self . body_file : self . body_file . write ( chunk ) else : self . response_body_chunks . append ( chunk ) if self . config... | Process body of response . |
25,986 | def debug_processor ( self , _type , text ) : if _type == pycurl . INFOTYPE_HEADER_OUT : if isinstance ( text , six . text_type ) : text = text . encode ( 'utf-8' ) self . request_head += text if _type == pycurl . INFOTYPE_DATA_OUT : if isinstance ( text , six . text_type ) : text = text . encode ( 'utf-8' ) self . req... | Process request details . |
25,987 | def extract_cookiejar ( self ) : cookiejar = CookieJar ( ) for line in self . curl . getinfo ( pycurl . INFO_COOKIELIST ) : values = line . split ( '\t' ) domain = values [ 0 ] . lower ( ) if domain . startswith ( '#httponly_' ) : domain = domain . replace ( '#httponly_' , '' ) httponly = True else : httponly = False c... | Extract cookies that pycurl instance knows . |
25,988 | def default_logging ( grab_log = None , network_log = None , level = logging . DEBUG , mode = 'a' , propagate_network_logger = False ) : logging . basicConfig ( level = level ) network_logger = logging . getLogger ( 'grab.network' ) network_logger . propagate = propagate_network_logger if network_log : hdl = logging . ... | Customize logging output to display all log messages except grab network logs . |
25,989 | def save_list ( lst , path ) : with open ( path , 'wb' ) as out : lines = [ ] for item in lst : if isinstance ( item , ( six . text_type , six . binary_type ) ) : lines . append ( make_str ( item ) ) else : lines . append ( make_str ( json . dumps ( item ) ) ) out . write ( b'\n' . join ( lines ) + b'\n' ) | Save items from list to the file . |
25,990 | def parse_proxy_line ( line ) : line = line . strip ( ) match = RE_SIMPLE_PROXY . search ( line ) if match : return match . group ( 1 ) , match . group ( 2 ) , None , None match = RE_AUTH_PROXY . search ( line ) if match : host , port , user , pwd = match . groups ( ) return host , port , user , pwd raise InvalidProxyL... | Parse proxy details from the raw text line . |
25,991 | def parse_raw_list_data ( data , proxy_type = 'http' , proxy_userpwd = None ) : if not isinstance ( data , six . text_type ) : data = data . decode ( 'utf-8' ) for orig_line in data . splitlines ( ) : line = orig_line . strip ( ) . replace ( ' ' , '' ) if line and not line . startswith ( '#' ) : try : host , port , use... | Iterate over proxy servers found in the raw data |
25,992 | def load ( self ) : self . _list = self . _source . load ( ) self . _list_iter = itertools . cycle ( self . _list ) | Load proxy list from configured proxy source |
25,993 | def get_random_proxy ( self ) : idx = randint ( 0 , len ( self . _list ) - 1 ) return self . _list [ idx ] | Return random proxy |
25,994 | def clone ( self , ** kwargs ) : attr_copy = self . __dict__ . copy ( ) if attr_copy . get ( 'grab_config' ) is not None : del attr_copy [ 'url' ] if not attr_copy [ 'priority_set_explicitly' ] : attr_copy [ 'priority' ] = None task = Task ( ** attr_copy ) if 'network_try_count' not in kwargs : task . network_try_count... | Clone Task instance . |
25,995 | def copy_config ( config , mutable_config_keys = MUTABLE_CONFIG_KEYS ) : cloned_config = copy ( config ) for key in mutable_config_keys : cloned_config [ key ] = copy ( config [ key ] ) return cloned_config | Copy grab config with correct handling of mutable config values . |
25,996 | def reset ( self ) : self . request_head = None self . request_body = None self . request_method = None self . request_counter = None self . exception = None if self . transport : self . transport . reset ( ) | Reset all attributes which could be modified during previous request or which is not initialized yet if this is the new Grab instance . |
25,997 | def clone ( self , ** kwargs ) : grab = Grab ( transport = self . transport_param ) grab . config = self . dump_config ( ) grab . doc = self . doc . copy ( ) for key in self . clonable_attributes : setattr ( grab , key , getattr ( self , key ) ) grab . cookies = deepcopy ( self . cookies ) if kwargs : grab . setup ( **... | Create clone of Grab instance . |
25,998 | def adopt ( self , grab ) : self . load_config ( grab . config ) self . doc = grab . doc . copy ( new_grab = self ) for key in self . clonable_attributes : setattr ( self , key , getattr ( grab , key ) ) self . cookies = deepcopy ( grab . cookies ) | Copy the state of another Grab instance . |
25,999 | def dump_config ( self ) : conf = copy_config ( self . config , self . mutable_config_keys ) conf [ 'state' ] = { 'cookiejar_cookies' : list ( self . cookies . cookiejar ) , } return conf | Make clone of current config . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.