idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
247,100 | def upload_to_mugshot ( instance , filename ) : extension = filename . split ( '.' ) [ - 1 ] . lower ( ) salt , hash = generate_sha1 ( instance . pk ) path = userena_settings . USERENA_MUGSHOT_PATH % { 'username' : instance . user . username , 'id' : instance . user . id , 'date' : instance . user . date_joined , 'date_now' : get_datetime_now ( ) . date ( ) } return '%(path)s%(hash)s.%(extension)s' % { 'path' : path , 'hash' : hash [ : 10 ] , 'extension' : extension } | Uploads a mugshot for a user to the USERENA_MUGSHOT_PATH and saving it under unique hash for the image . This is for privacy reasons so others can t just browse through the mugshot directory . | 161 | 47 |
247,101 | def message_compose ( request , recipients = None , compose_form = ComposeForm , success_url = None , template_name = "umessages/message_form.html" , recipient_filter = None , extra_context = None ) : initial_data = dict ( ) if recipients : username_list = [ r . strip ( ) for r in recipients . split ( "+" ) ] recipients = [ u for u in get_user_model ( ) . objects . filter ( username__in = username_list ) ] initial_data [ "to" ] = recipients form = compose_form ( initial = initial_data ) if request . method == "POST" : form = compose_form ( request . POST ) if form . is_valid ( ) : requested_redirect = request . GET . get ( REDIRECT_FIELD_NAME , request . POST . get ( REDIRECT_FIELD_NAME , False ) ) message = form . save ( request . user ) recipients = form . cleaned_data [ 'to' ] if userena_settings . USERENA_USE_MESSAGES : messages . success ( request , _ ( 'Message is sent.' ) , fail_silently = True ) # Redirect mechanism redirect_to = reverse ( 'userena_umessages_list' ) if requested_redirect : redirect_to = requested_redirect elif success_url : redirect_to = success_url elif len ( recipients ) == 1 : redirect_to = reverse ( 'userena_umessages_detail' , kwargs = { 'username' : recipients [ 0 ] . username } ) return redirect ( redirect_to ) if not extra_context : extra_context = dict ( ) extra_context [ "form" ] = form extra_context [ "recipients" ] = recipients return render ( request , template_name , extra_context ) | Compose a new message | 410 | 5 |
247,102 | def message_remove ( request , undo = False ) : message_pks = request . POST . getlist ( 'message_pks' ) redirect_to = request . GET . get ( REDIRECT_FIELD_NAME , request . POST . get ( REDIRECT_FIELD_NAME , False ) ) if message_pks : # Check that all values are integers. valid_message_pk_list = set ( ) for pk in message_pks : try : valid_pk = int ( pk ) except ( TypeError , ValueError ) : pass else : valid_message_pk_list . add ( valid_pk ) # Delete all the messages, if they belong to the user. now = get_datetime_now ( ) changed_message_list = set ( ) for pk in valid_message_pk_list : message = get_object_or_404 ( Message , pk = pk ) # Check if the user is the owner if message . sender == request . user : if undo : message . sender_deleted_at = None else : message . sender_deleted_at = now message . save ( ) changed_message_list . add ( message . pk ) # Check if the user is a recipient of the message if request . user in message . recipients . all ( ) : mr = message . messagerecipient_set . get ( user = request . user , message = message ) if undo : mr . deleted_at = None else : mr . deleted_at = now mr . save ( ) changed_message_list . add ( message . pk ) # Send messages if ( len ( changed_message_list ) > 0 ) and userena_settings . USERENA_USE_MESSAGES : if undo : message = ungettext ( 'Message is succesfully restored.' , 'Messages are succesfully restored.' , len ( changed_message_list ) ) else : message = ungettext ( 'Message is successfully removed.' , 'Messages are successfully removed.' , len ( changed_message_list ) ) messages . success ( request , message , fail_silently = True ) if redirect_to : return redirect ( redirect_to ) else : return redirect ( reverse ( 'userena_umessages_list' ) ) | A POST to remove messages . | 501 | 6 |
247,103 | def save ( self ) : # First save the parent form and get the user. new_user = super ( SignupFormExtra , self ) . save ( ) new_user . first_name = self . cleaned_data [ 'first_name' ] new_user . last_name = self . cleaned_data [ 'last_name' ] new_user . save ( ) # Userena expects to get the new user from this form, so return the new # user. return new_user | Override the save method to save the first and last name to the user field . | 106 | 16 |
247,104 | def save ( self , sender ) : um_to_user_list = self . cleaned_data [ 'to' ] body = self . cleaned_data [ 'body' ] msg = Message . objects . send_message ( sender , um_to_user_list , body ) return msg | Save the message and send it out into the wide world . | 62 | 12 |
247,105 | def clean_username ( self ) : try : user = get_user_model ( ) . objects . get ( username__iexact = self . cleaned_data [ 'username' ] ) except get_user_model ( ) . DoesNotExist : pass else : if userena_settings . USERENA_ACTIVATION_REQUIRED and UserenaSignup . objects . filter ( user__username__iexact = self . cleaned_data [ 'username' ] ) . exclude ( activation_key = userena_settings . USERENA_ACTIVATED ) : raise forms . ValidationError ( _ ( 'This username is already taken but not confirmed. Please check your email for verification steps.' ) ) raise forms . ValidationError ( _ ( 'This username is already taken.' ) ) if self . cleaned_data [ 'username' ] . lower ( ) in userena_settings . USERENA_FORBIDDEN_USERNAMES : raise forms . ValidationError ( _ ( 'This username is not allowed.' ) ) return self . cleaned_data [ 'username' ] | Validate that the username is alphanumeric and is not already in use . Also validates that the username is not listed in USERENA_FORBIDDEN_USERNAMES list . | 239 | 40 |
247,106 | def save ( self ) : while True : username = sha1 ( str ( random . random ( ) ) . encode ( 'utf-8' ) ) . hexdigest ( ) [ : 5 ] try : get_user_model ( ) . objects . get ( username__iexact = username ) except get_user_model ( ) . DoesNotExist : break self . cleaned_data [ 'username' ] = username return super ( SignupFormOnlyEmail , self ) . save ( ) | Generate a random username before falling back to parent signup form | 107 | 13 |
247,107 | def parse_file ( self , sourcepath ) : # Open input file and read JSON array: with open ( sourcepath , 'r' ) as logfile : jsonlist = logfile . readlines ( ) # Set our attributes for this entry and add it to data.entries: data = { } data [ 'entries' ] = [ ] for line in jsonlist : entry = self . parse_line ( line ) data [ 'entries' ] . append ( entry ) if self . tzone : for e in data [ 'entries' ] : e [ 'tzone' ] = self . tzone # Return the parsed data return data | Parse an object - per - line JSON file into a log data dict | 138 | 15 |
247,108 | def parse_file ( self , sourcepath ) : # Open input file and read JSON array: with open ( sourcepath , 'r' ) as logfile : jsonstr = logfile . read ( ) # Set our attributes for this entry and add it to data.entries: data = { } data [ 'entries' ] = json . loads ( jsonstr ) if self . tzone : for e in data [ 'entries' ] : e [ 'tzone' ] = self . tzone # Return the parsed data return data | Parse single JSON object into a LogData object | 114 | 10 |
247,109 | def run_job ( self ) : try : self . load_parsers ( ) self . load_filters ( ) self . load_outputs ( ) self . config_args ( ) if self . args . list_parsers : self . list_parsers ( ) if self . args . verbosemode : print ( 'Loading input files' ) self . load_inputs ( ) if self . args . verbosemode : print ( 'Running parsers' ) self . run_parse ( ) if self . args . verbosemode : print ( 'Merging data' ) self . data_set [ 'finalized_data' ] = logdissect . utils . merge_logs ( self . data_set [ 'data_set' ] , sort = True ) if self . args . verbosemode : print ( 'Running filters' ) self . run_filters ( ) if self . args . verbosemode : print ( 'Running output' ) self . run_output ( ) except KeyboardInterrupt : sys . exit ( 1 ) | Execute a logdissect job | 229 | 7 |
247,110 | def run_parse ( self ) : # Data set already has source file names from load_inputs parsedset = { } parsedset [ 'data_set' ] = [ ] for log in self . input_files : parsemodule = self . parse_modules [ self . args . parser ] try : if self . args . tzone : parsemodule . tzone = self . args . tzone except NameError : pass parsedset [ 'data_set' ] . append ( parsemodule . parse_file ( log ) ) self . data_set = parsedset del ( parsedset ) | Parse one or more log files | 124 | 7 |
247,111 | def run_output ( self ) : for f in logdissect . output . __formats__ : ouroutput = self . output_modules [ f ] ouroutput . write_output ( self . data_set [ 'finalized_data' ] , args = self . args ) del ( ouroutput ) # Output to terminal if silent mode is not set: if not self . args . silentmode : if self . args . verbosemode : print ( '\n==== ++++ ==== Output: ==== ++++ ====\n' ) for line in self . data_set [ 'finalized_data' ] [ 'entries' ] : print ( line [ 'raw_text' ] ) | Output finalized data | 150 | 3 |
247,112 | def config_args ( self ) : # Module list options: self . arg_parser . add_argument ( '--version' , action = 'version' , version = '%(prog)s ' + str ( __version__ ) ) self . arg_parser . add_argument ( '--verbose' , action = 'store_true' , dest = 'verbosemode' , help = _ ( 'set verbose terminal output' ) ) self . arg_parser . add_argument ( '-s' , action = 'store_true' , dest = 'silentmode' , help = _ ( 'silence terminal output' ) ) self . arg_parser . add_argument ( '--list-parsers' , action = 'store_true' , dest = 'list_parsers' , help = _ ( 'return a list of available parsers' ) ) self . arg_parser . add_argument ( '-p' , action = 'store' , dest = 'parser' , default = 'syslog' , help = _ ( 'select a parser (default: syslog)' ) ) self . arg_parser . add_argument ( '-z' , '--unzip' , action = 'store_true' , dest = 'unzip' , help = _ ( 'include files compressed with gzip' ) ) self . arg_parser . add_argument ( '-t' , action = 'store' , dest = 'tzone' , help = _ ( 'specify timezone offset to UTC (e.g. \'+0500\')' ) ) self . arg_parser . add_argument ( 'files' , # nargs needs to be * not + so --list-filters/etc # will work without file arg metavar = 'file' , nargs = '*' , help = _ ( 'specify input files' ) ) # self.arg_parser.add_argument_group(self.parse_args) self . arg_parser . add_argument_group ( self . filter_args ) self . arg_parser . add_argument_group ( self . output_args ) self . args = self . arg_parser . parse_args ( ) | Set config options | 480 | 3 |
247,113 | def load_inputs ( self ) : for f in self . args . files : if os . path . isfile ( f ) : fparts = str ( f ) . split ( '.' ) if fparts [ - 1 ] == 'gz' : if self . args . unzip : fullpath = os . path . abspath ( str ( f ) ) self . input_files . append ( fullpath ) else : return 0 elif fparts [ - 1 ] == 'bz2' or fparts [ - 1 ] == 'zip' : return 0 else : fullpath = os . path . abspath ( str ( f ) ) self . input_files . append ( fullpath ) else : print ( 'File ' + f + ' not found' ) return 1 | Load the specified inputs | 165 | 4 |
247,114 | def list_parsers ( self , * args ) : print ( '==== Available parsing modules: ====\n' ) for parser in sorted ( self . parse_modules ) : print ( self . parse_modules [ parser ] . name . ljust ( 16 ) + ': ' + self . parse_modules [ parser ] . desc ) sys . exit ( 0 ) | Return a list of available parsing modules | 79 | 7 |
247,115 | def get_utc_date ( entry ) : if entry [ 'numeric_date_stamp' ] == '0' : entry [ 'numeric_date_stamp_utc' ] = '0' return entry else : if '.' in entry [ 'numeric_date_stamp' ] : t = datetime . strptime ( entry [ 'numeric_date_stamp' ] , '%Y%m%d%H%M%S.%f' ) else : t = datetime . strptime ( entry [ 'numeric_date_stamp' ] , '%Y%m%d%H%M%S' ) tdelta = timedelta ( hours = int ( entry [ 'tzone' ] [ 1 : 3 ] ) , minutes = int ( entry [ 'tzone' ] [ 3 : 5 ] ) ) if entry [ 'tzone' ] [ 0 ] == '-' : ut = t + tdelta else : ut = t - tdelta entry [ 'numeric_date_stamp_utc' ] = ut . strftime ( '%Y%m%d%H%M%S.%f' ) return entry | Return datestamp converted to UTC | 260 | 6 |
247,116 | def get_local_tzone ( ) : if localtime ( ) . tm_isdst : if altzone < 0 : tzone = '+' + str ( int ( float ( altzone ) / 60 // 60 ) ) . rjust ( 2 , '0' ) + str ( int ( float ( altzone ) / 60 % 60 ) ) . ljust ( 2 , '0' ) else : tzone = '-' + str ( int ( float ( altzone ) / 60 // 60 ) ) . rjust ( 2 , '0' ) + str ( int ( float ( altzone ) / 60 % 60 ) ) . ljust ( 2 , '0' ) else : if altzone < 0 : tzone = '+' + str ( int ( float ( timezone ) / 60 // 60 ) ) . rjust ( 2 , '0' ) + str ( int ( float ( timezone ) / 60 % 60 ) ) . ljust ( 2 , '0' ) else : tzone = '-' + str ( int ( float ( timezone ) / 60 // 60 ) ) . rjust ( 2 , '0' ) + str ( int ( float ( timezone ) / 60 % 60 ) ) . ljust ( 2 , '0' ) return tzone | Get the current time zone on the local host | 273 | 9 |
247,117 | def merge_logs ( dataset , sort = True ) : ourlog = { } ourlog [ 'entries' ] = [ ] for d in dataset : ourlog [ 'entries' ] = ourlog [ 'entries' ] + d [ 'entries' ] if sort : ourlog [ 'entries' ] . sort ( key = lambda x : x [ 'numeric_date_stamp_utc' ] ) return ourlog | Merge log dictionaries together into one log dictionary | 97 | 10 |
247,118 | def write_output ( self , data , args = None , filename = None , label = None ) : if args : if not args . outlog : return 0 if not filename : filename = args . outlog lastpath = '' with open ( str ( filename ) , 'w' ) as output_file : for entry in data [ 'entries' ] : if args . label : if entry [ 'source_path' ] == lastpath : output_file . write ( entry [ 'raw_text' ] + '\n' ) elif args . label == 'fname' : output_file . write ( '======== ' + entry [ 'source_path' ] . split ( '/' ) [ - 1 ] + ' >>>>\n' + entry [ 'raw_text' ] + '\n' ) elif args . label == 'fpath' : output_file . write ( '======== ' + entry [ 'source_path' ] + ' >>>>\n' + entry [ 'raw_text' ] + '\n' ) else : output_file . write ( entry [ 'raw_text' ] + '\n' ) lastpath = entry [ 'source_path' ] | Write log data to a log file | 259 | 7 |
247,119 | def write_output ( self , data , args = None , filename = None , pretty = False ) : if args : if not args . sojson : return 0 pretty = args . pretty if not filename : filename = args . sojson if pretty : logstring = json . dumps ( data [ 'entries' ] , indent = 2 , sort_keys = True , separators = ( ',' , ': ' ) ) else : logstring = json . dumps ( data [ 'entries' ] , sort_keys = True ) with open ( str ( filename ) , 'w' ) as output_file : output_file . write ( logstring ) | Write log data to a single JSON object | 138 | 8 |
247,120 | def write_output ( self , data , filename = None , args = None ) : if args : if not args . linejson : return 0 if not filename : filename = args . linejson entrylist = [ ] for entry in data [ 'entries' ] : entrystring = json . dumps ( entry , sort_keys = True ) entrylist . append ( entrystring ) with open ( str ( filename ) , 'w' ) as output_file : output_file . write ( '\n' . join ( entrylist ) ) | Write log data to a file with one JSON object per line | 113 | 12 |
247,121 | def parse_file ( self , sourcepath ) : # Get regex objects: self . date_regex = re . compile ( r'{}' . format ( self . format_regex ) ) if self . backup_format_regex : self . backup_date_regex = re . compile ( r'{}' . format ( self . backup_format_regex ) ) data = { } data [ 'entries' ] = [ ] data [ 'parser' ] = self . name data [ 'source_path' ] = sourcepath data [ 'source_file' ] = sourcepath . split ( '/' ) [ - 1 ] # Set our start year: data [ 'source_file_mtime' ] = os . path . getmtime ( data [ 'source_path' ] ) timestamp = datetime . fromtimestamp ( data [ 'source_file_mtime' ] ) data [ 'source_file_year' ] = timestamp . year entryyear = timestamp . year currentmonth = '99' if self . datestamp_type == 'nodate' : self . datedata = { } self . datedata [ 'timestamp' ] = timestamp self . datedata [ 'entry_time' ] = int ( timestamp . strftime ( '%H%M%S' ) ) # Set our timezone if not self . tzone : self . backuptzone = logdissect . utils . get_local_tzone ( ) # Parsing works in reverse. This helps with multi-line entries, # and logs that span multiple years (December to January shift). # Get our lines: fparts = sourcepath . split ( '.' ) if fparts [ - 1 ] == 'gz' : with gzip . open ( sourcepath , 'r' ) as logfile : loglines = reversed ( logfile . readlines ( ) ) else : with open ( str ( sourcepath ) , 'r' ) as logfile : loglines = reversed ( logfile . readlines ( ) ) # Parse our lines: for line in loglines : ourline = line . rstrip ( ) # Send the line to self.parse_line entry = self . parse_line ( ourline ) if entry : if 'date_stamp' in self . fields : # Check for Dec-Jan jump and set the year: if self . datestamp_type == 'standard' : if int ( entry [ 'month' ] ) > int ( currentmonth ) : entryyear = entryyear - 1 currentmonth = entry [ 'month' ] entry [ 'numeric_date_stamp' ] = str ( entryyear ) + entry [ 'month' ] + entry [ 'day' ] + entry [ 'tstamp' ] entry [ 'year' ] = str ( entryyear ) if self . tzone : entry [ 'tzone' ] = self . tzone else : entry [ 'tzone' ] = self . backuptzone entry = logdissect . utils . get_utc_date ( entry ) entry [ 'raw_text' ] = ourline entry [ 'source_path' ] = data [ 'source_path' ] # Append current entry data [ 'entries' ] . append ( entry ) else : continue # Write the entries to the log object data [ 'entries' ] . reverse ( ) return data | Parse a file into a LogData object | 722 | 9 |
247,122 | def parse_line ( self , line ) : match = re . findall ( self . date_regex , line ) if match : fields = self . fields elif self . backup_format_regex and not match : match = re . findall ( self . backup_date_regex , line ) fields = self . backup_fields if match : entry = { } entry [ 'raw_text' ] = line entry [ 'parser' ] = self . name matchlist = list ( zip ( fields , match [ 0 ] ) ) for f , v in matchlist : entry [ f ] = v if 'date_stamp' in entry . keys ( ) : if self . datestamp_type == 'standard' : entry = logdissect . utils . convert_standard_datestamp ( entry ) elif self . datestamp_type == 'iso' : entry = logdissect . utils . convert_iso_datestamp ( entry ) elif self . datestamp_type == 'webaccess' : entry = logdissect . utils . convert_webaccess_datestamp ( entry ) elif self . datestamp_type == 'nodate' : entry , self . datedata = logdissect . utils . convert_nodate_datestamp ( entry , self . datedata ) elif self . datestamp_type == 'unix' : entry = logdissect . utils . convert_unix_datestamp ( entry ) if self . datestamp_type == 'now' : entry = logdissect . utils . convert_now_datestamp ( entry ) entry = self . post_parse_action ( entry ) return entry else : return None | Parse a line into a dictionary | 363 | 7 |
247,123 | def post_parse_action ( self , entry ) : if 'source_host' in entry . keys ( ) : host = self . ip_port_regex . findall ( entry [ 'source_host' ] ) if host : hlist = host [ 0 ] . split ( '.' ) entry [ 'source_host' ] = '.' . join ( hlist [ : 4 ] ) entry [ 'source_port' ] = hlist [ - 1 ] if 'dest_host' in entry . keys ( ) : host = self . ip_port_regex . findall ( entry [ 'dest_host' ] ) if host : hlist = host [ 0 ] . split ( '.' ) entry [ 'dest_host' ] = '.' . join ( hlist [ : 4 ] ) entry [ 'dest_port' ] = hlist [ - 1 ] return entry | separate hosts and ports after entry is parsed | 190 | 9 |
247,124 | def find_partition_multiplex ( graphs , partition_type , * * kwargs ) : n_layers = len ( graphs ) partitions = [ ] layer_weights = [ 1 ] * n_layers for graph in graphs : partitions . append ( partition_type ( graph , * * kwargs ) ) optimiser = Optimiser ( ) improvement = optimiser . optimise_partition_multiplex ( partitions , layer_weights ) return partitions [ 0 ] . membership , improvement | Detect communities for multiplex graphs . | 105 | 7 |
247,125 | def find_partition_temporal ( graphs , partition_type , interslice_weight = 1 , slice_attr = 'slice' , vertex_id_attr = 'id' , edge_type_attr = 'type' , weight_attr = 'weight' , * * kwargs ) : # Create layers G_layers , G_interslice , G = time_slices_to_layers ( graphs , interslice_weight , slice_attr = slice_attr , vertex_id_attr = vertex_id_attr , edge_type_attr = edge_type_attr , weight_attr = weight_attr ) # Optimise partitions arg_dict = { } if 'node_sizes' in partition_type . __init__ . __code__ . co_varnames : arg_dict [ 'node_sizes' ] = 'node_size' if 'weights' in partition_type . __init__ . __code__ . co_varnames : arg_dict [ 'weights' ] = 'weight' arg_dict . update ( kwargs ) partitions = [ ] for H in G_layers : arg_dict [ 'graph' ] = H partitions . append ( partition_type ( * * arg_dict ) ) # We can always take the same interslice partition, as this should have no # cost in the optimisation. partition_interslice = CPMVertexPartition ( G_interslice , resolution_parameter = 0 , node_sizes = 'node_size' , weights = weight_attr ) optimiser = Optimiser ( ) improvement = optimiser . optimise_partition_multiplex ( partitions + [ partition_interslice ] ) # Transform results back into original form. membership = { ( v [ slice_attr ] , v [ vertex_id_attr ] ) : m for v , m in zip ( G . vs , partitions [ 0 ] . membership ) } membership_time_slices = [ ] for slice_idx , H in enumerate ( graphs ) : membership_slice = [ membership [ ( slice_idx , v [ vertex_id_attr ] ) ] for v in H . vs ] membership_time_slices . append ( list ( membership_slice ) ) return membership_time_slices , improvement | Detect communities for temporal graphs . | 501 | 6 |
247,126 | def build_ext ( self ) : try : from setuptools . command . build_ext import build_ext except ImportError : from distutils . command . build_ext import build_ext buildcfg = self class custom_build_ext ( build_ext ) : def run ( self ) : # Print a warning if pkg-config is not available or does not know about igraph if buildcfg . use_pkgconfig : detected = buildcfg . detect_from_pkgconfig ( ) else : detected = False # Check whether we have already compiled igraph in a previous run. # If so, it should be found in igraphcore/include and # igraphcore/lib if os . path . exists ( "igraphcore" ) : buildcfg . use_built_igraph ( ) detected = True # Download and compile igraph if the user did not disable it and # we do not know the libraries from pkg-config yet if not detected : if buildcfg . download_igraph_if_needed and is_unix_like ( ) : detected = buildcfg . download_and_compile_igraph ( ) if detected : buildcfg . use_built_igraph ( ) # Fall back to an educated guess if everything else failed if not detected : buildcfg . use_educated_guess ( ) # Replaces library names with full paths to static libraries # where possible if buildcfg . static_extension : buildcfg . replace_static_libraries ( exclusions = [ "m" ] ) # Prints basic build information buildcfg . print_build_info ( ) ext = first ( extension for extension in self . extensions if extension . name == "louvain._c_louvain" ) buildcfg . configure ( ext ) # Run the original build_ext command build_ext . run ( self ) return custom_build_ext | Returns a class that can be used as a replacement for the build_ext command in distutils and that will download and compile the C core of igraph if needed . | 393 | 34 |
247,127 | def Bipartite ( graph , resolution_parameter_01 , resolution_parameter_0 = 0 , resolution_parameter_1 = 0 , degree_as_node_size = False , types = 'type' , * * kwargs ) : if types is not None : if isinstance ( types , str ) : types = graph . vs [ types ] else : # Make sure it is a list types = list ( types ) if set ( types ) != set ( [ 0 , 1 ] ) : new_type = _ig . UniqueIdGenerator ( ) types = [ new_type [ t ] for t in types ] if set ( types ) != set ( [ 0 , 1 ] ) : raise ValueError ( "More than one type specified." ) if degree_as_node_size : if ( graph . is_directed ( ) ) : raise ValueError ( "This method is not suitable for directed graphs " + "when using degree as node sizes." ) node_sizes = graph . degree ( ) else : node_sizes = [ 1 ] * graph . vcount ( ) partition_01 = CPMVertexPartition ( graph , node_sizes = node_sizes , resolution_parameter = resolution_parameter_01 , * * kwargs ) H_0 = graph . subgraph_edges ( [ ] , delete_vertices = False ) partition_0 = CPMVertexPartition ( H_0 , weights = None , node_sizes = [ s if t == 0 else 0 for v , s , t in zip ( graph . vs , node_sizes , types ) ] , resolution_parameter = resolution_parameter_01 - resolution_parameter_0 , * * kwargs ) H_1 = graph . subgraph_edges ( [ ] , delete_vertices = False ) partition_1 = CPMVertexPartition ( H_1 , weights = None , node_sizes = [ s if t == 1 else 0 for v , s , t in zip ( graph . vs , node_sizes , types ) ] , resolution_parameter = resolution_parameter_01 - resolution_parameter_1 , * * kwargs ) return partition_01 , partition_0 , partition_1 | Create three layers for bipartite partitions . | 489 | 9 |
247,128 | def spacing_file ( path ) : # TODO: read line by line with open ( os . path . abspath ( path ) ) as f : return spacing_text ( f . read ( ) ) | Perform paranoid text spacing from file . | 43 | 8 |
247,129 | def compute ( self , text , # text for which to find the most similar event lang = "eng" ) : # language in which the text is written params = { "lang" : lang , "text" : text , "topClustersCount" : self . _nrOfEventsToReturn } res = self . _er . jsonRequest ( "/json/getEventForText/enqueueRequest" , params ) requestId = res [ "requestId" ] for i in range ( 10 ) : time . sleep ( 1 ) # sleep for 1 second to wait for the clustering to perform computation res = self . _er . jsonRequest ( "/json/getEventForText/testRequest" , { "requestId" : requestId } ) if isinstance ( res , list ) and len ( res ) > 0 : return res return None | compute the list of most similar events for the given text | 178 | 12 |
247,130 | def annotate ( self , text , lang = None , customParams = None ) : params = { "lang" : lang , "text" : text } if customParams : params . update ( customParams ) return self . _er . jsonRequestAnalytics ( "/api/v1/annotate" , params ) | identify the list of entities and nonentities mentioned in the text | 70 | 14 |
247,131 | def sentiment ( self , text , method = "vocabulary" ) : assert method == "vocabulary" or method == "rnn" endpoint = method == "vocabulary" and "sentiment" or "sentimentRNN" return self . _er . jsonRequestAnalytics ( "/api/v1/" + endpoint , { "text" : text } ) | determine the sentiment of the provided text in English language | 77 | 12 |
247,132 | def semanticSimilarity ( self , text1 , text2 , distanceMeasure = "cosine" ) : return self . _er . jsonRequestAnalytics ( "/api/v1/semanticSimilarity" , { "text1" : text1 , "text2" : text2 , "distanceMeasure" : distanceMeasure } ) | determine the semantic similarity of the two provided documents | 71 | 11 |
247,133 | def extractArticleInfo ( self , url , proxyUrl = None , headers = None , cookies = None ) : params = { "url" : url } if proxyUrl : params [ "proxyUrl" ] = proxyUrl if headers : if isinstance ( headers , dict ) : headers = json . dumps ( headers ) params [ "headers" ] = headers if cookies : if isinstance ( cookies , dict ) : cookies = json . dumps ( cookies ) params [ "cookies" ] = cookies return self . _er . jsonRequestAnalytics ( "/api/v1/extractArticleInfo" , params ) | extract all available information about an article available at url url . Returned information will include article title body authors links in the articles ... | 128 | 27 |
247,134 | def trainTopicOnTweets ( self , twitterQuery , useTweetText = True , useIdfNormalization = True , normalization = "linear" , maxTweets = 2000 , maxUsedLinks = 500 , ignoreConceptTypes = [ ] , maxConcepts = 20 , maxCategories = 10 , notifyEmailAddress = None ) : assert maxTweets < 5000 , "we can analyze at most 5000 tweets" params = { "twitterQuery" : twitterQuery , "useTweetText" : useTweetText , "useIdfNormalization" : useIdfNormalization , "normalization" : normalization , "maxTweets" : maxTweets , "maxUsedLinks" : maxUsedLinks , "maxConcepts" : maxConcepts , "maxCategories" : maxCategories } if notifyEmailAddress : params [ "notifyEmailAddress" ] = notifyEmailAddress if len ( ignoreConceptTypes ) > 0 : params [ "ignoreConceptTypes" ] = ignoreConceptTypes return self . _er . jsonRequestAnalytics ( "/api/v1/trainTopicOnTwitter" , params ) | create a new topic and train it using the tweets that match the twitterQuery | 242 | 15 |
247,135 | def trainTopicGetTrainedTopic ( self , uri , maxConcepts = 20 , maxCategories = 10 , ignoreConceptTypes = [ ] , idfNormalization = True ) : return self . _er . jsonRequestAnalytics ( "/api/v1/trainTopic" , { "action" : "getTrainedTopic" , "uri" : uri , "maxConcepts" : maxConcepts , "maxCategories" : maxCategories , "idfNormalization" : idfNormalization } ) | retrieve topic for the topic for which you have already finished training | 117 | 13 |
247,136 | def createTopicPage1 ( ) : topic = TopicPage ( er ) topic . addKeyword ( "renewable energy" , 30 ) topic . addConcept ( er . getConceptUri ( "biofuel" ) , 50 ) topic . addConcept ( er . getConceptUri ( "solar energy" ) , 50 ) topic . addCategory ( er . getCategoryUri ( "renewable" ) , 50 ) # skip articles that are duplicates of other articles topic . articleHasDuplicateFilter ( "skipHasDuplicates" ) # return only articles that are about some event that we have detected topic . articleHasEventFilter ( "skipArticlesWithoutEvent" ) # get first 2 pages of articles sorted by relevance to the topic page arts1 = topic . getArticles ( page = 1 , sortBy = "rel" ) arts2 = topic . getArticles ( page = 2 , sortBy = "rel" ) # get first page of events events1 = topic . getEvents ( page = 1 ) | create a topic page directly | 224 | 5 |
247,137 | def createTopicPage2 ( ) : topic = TopicPage ( er ) topic . addCategory ( er . getCategoryUri ( "renewable" ) , 50 ) topic . addKeyword ( "renewable energy" , 30 ) topic . addConcept ( er . getConceptUri ( "biofuel" ) , 50 ) topic . addConcept ( er . getConceptUri ( "solar energy" ) , 50 ) # require that the results will mention at least one of the concepts and keywords specified # (even though they might have the category about renewable energy, that will not be enough # for an article to be among the results) topic . restrictToSetConceptsAndKeywords ( True ) # limit results to English, German and Spanish results topic . setLanguages ( [ "eng" , "deu" , "spa" ] ) # get results that are at most 3 days old topic . setMaxDaysBack ( 3 ) # require that the articles that will be returned should get at least a total score of 30 points or more # based on the specified list of conditions topic . setArticleThreshold ( 30 ) # get first page of articles sorted by date (from most recent backward) to the topic page arts1 = topic . getArticles ( page = 1 , sortBy = "date" , returnInfo = ReturnInfo ( articleInfo = ArticleInfoFlags ( concepts = True , categories = True ) ) ) for art in arts1 . get ( "articles" , { } ) . get ( "results" , [ ] ) : print ( art ) | create a topic page directly set the article threshold restrict results to set concepts and keywords | 336 | 16 |
247,138 | def count ( self , eventRegistry ) : self . setRequestedResult ( RequestEventArticles ( * * self . queryParams ) ) res = eventRegistry . execQuery ( self ) if "error" in res : print ( res [ "error" ] ) count = res . get ( self . queryParams [ "eventUri" ] , { } ) . get ( "articles" , { } ) . get ( "totalResults" , 0 ) return count | return the number of articles that match the criteria | 102 | 9 |
247,139 | def initWithComplexQuery ( query ) : q = QueryArticles ( ) # provided an instance of ComplexArticleQuery if isinstance ( query , ComplexArticleQuery ) : q . _setVal ( "query" , json . dumps ( query . getQuery ( ) ) ) # provided query as a string containing the json object elif isinstance ( query , six . string_types ) : foo = json . loads ( query ) q . _setVal ( "query" , query ) # provided query as a python dict elif isinstance ( query , dict ) : q . _setVal ( "query" , json . dumps ( query ) ) else : assert False , "The instance of query parameter was not a ComplexArticleQuery, a string or a python dict" return q | create a query using a complex article query | 163 | 8 |
247,140 | def _getNextArticleBatch ( self ) : # try to get more uris, if none self . _articlePage += 1 # if we have already obtained all pages, then exit if self . _totalPages != None and self . _articlePage > self . _totalPages : return self . setRequestedResult ( RequestArticlesInfo ( page = self . _articlePage , sortBy = self . _sortBy , sortByAsc = self . _sortByAsc , returnInfo = self . _returnInfo ) ) if self . _er . _verboseOutput : print ( "Downloading article page %d..." % ( self . _articlePage ) ) res = self . _er . execQuery ( self ) if "error" in res : print ( "Error while obtaining a list of articles: " + res [ "error" ] ) else : self . _totalPages = res . get ( "articles" , { } ) . get ( "pages" , 0 ) results = res . get ( "articles" , { } ) . get ( "results" , [ ] ) self . _articleList . extend ( results ) | download next batch of articles based on the article uris in the uri list | 243 | 16 |
247,141 | def initWithComplexQuery ( query ) : q = QueryEvents ( ) # provided an instance of ComplexEventQuery if isinstance ( query , ComplexEventQuery ) : q . _setVal ( "query" , json . dumps ( query . getQuery ( ) ) ) # provided query as a string containing the json object elif isinstance ( query , six . string_types ) : foo = json . loads ( query ) q . _setVal ( "query" , query ) # provided query as a python dict elif isinstance ( query , dict ) : q . _setVal ( "query" , json . dumps ( query ) ) # unrecognized value provided else : assert False , "The instance of query parameter was not a ComplexEventQuery, a string or a python dict" return q | create a query using a complex event query | 167 | 8 |
247,142 | def count ( self , eventRegistry ) : self . setRequestedResult ( RequestEventsInfo ( ) ) res = eventRegistry . execQuery ( self ) if "error" in res : print ( res [ "error" ] ) count = res . get ( "events" , { } ) . get ( "totalResults" , 0 ) return count | return the number of events that match the criteria | 75 | 9 |
247,143 | def _setFlag ( self , name , val , defVal ) : if not hasattr ( self , "flags" ) : self . flags = { } if val != defVal : self . flags [ name ] = val | set the objects property propName if the dictKey key exists in dict and it is not the same as default value defVal | 47 | 25 |
247,144 | def _setVal ( self , name , val , defVal = None ) : if val == defVal : return if not hasattr ( self , "vals" ) : self . vals = { } self . vals [ name ] = val | set value of name to val in case the val ! = defVal | 52 | 14 |
247,145 | def _getVals ( self , prefix = "" ) : if not hasattr ( self , "vals" ) : self . vals = { } dict = { } for key in list ( self . vals . keys ( ) ) : # if no prefix then lower the first letter if prefix == "" : newkey = key [ : 1 ] . lower ( ) + key [ 1 : ] if key else "" dict [ newkey ] = self . vals [ key ] else : newkey = key [ : 1 ] . upper ( ) + key [ 1 : ] if key else "" dict [ prefix + newkey ] = self . vals [ key ] return dict | return the values in the vals dict in case prefix is change the first letter of the name to lowercase otherwise use prefix + name as the new name | 141 | 31 |
247,146 | def loadFromFile ( fileName ) : assert os . path . exists ( fileName ) , "File " + fileName + " does not exist" conf = json . load ( open ( fileName ) ) return ReturnInfo ( articleInfo = ArticleInfoFlags ( * * conf . get ( "articleInfo" , { } ) ) , eventInfo = EventInfoFlags ( * * conf . get ( "eventInfo" , { } ) ) , sourceInfo = SourceInfoFlags ( * * conf . get ( "sourceInfo" , { } ) ) , categoryInfo = CategoryInfoFlags ( * * conf . get ( "categoryInfo" , { } ) ) , conceptInfo = ConceptInfoFlags ( * * conf . get ( "conceptInfo" , { } ) ) , locationInfo = LocationInfoFlags ( * * conf . get ( "locationInfo" , { } ) ) , storyInfo = StoryInfoFlags ( * * conf . get ( "storyInfo" , { } ) ) , conceptClassInfo = ConceptClassInfoFlags ( * * conf . get ( "conceptClassInfo" , { } ) ) , conceptFolderInfo = ConceptFolderInfoFlags ( * * conf . get ( "conceptFolderInfo" , { } ) ) ) | load the configuration for the ReturnInfo from a fileName | 261 | 11 |
247,147 | def loadTopicPageFromER ( self , uri ) : params = { "action" : "getTopicPageJson" , "includeConceptDescription" : True , "includeTopicPageDefinition" : True , "includeTopicPageOwner" : True , "uri" : uri } self . topicPage = self . _createEmptyTopicPage ( ) self . concept = self . eventRegistry . jsonRequest ( "/json/topicPage" , params ) self . topicPage . update ( self . concept . get ( "topicPage" , { } ) ) | load an existing topic page from Event Registry based on the topic page URI | 120 | 14 |
247,148 | def loadTopicPageFromFile ( self , fname ) : assert os . path . exists ( fname ) f = open ( fname , "r" , encoding = "utf-8" ) self . topicPage = json . load ( f ) | load topic page from an existing file | 53 | 7 |
247,149 | def saveTopicPageDefinitionToFile ( self , fname ) : open ( fname , "w" , encoding = "utf-8" ) . write ( json . dumps ( self . topicPage , indent = 4 , sort_keys = True ) ) | save the topic page definition to a file | 54 | 8 |
247,150 | def setArticleThreshold ( self , value ) : assert isinstance ( value , int ) assert value >= 0 self . topicPage [ "articleTreshWgt" ] = value | what is the minimum total weight that an article has to have in order to get it among the results? | 38 | 21 |
247,151 | def setEventThreshold ( self , value ) : assert isinstance ( value , int ) assert value >= 0 self . topicPage [ "eventTreshWgt" ] = value | what is the minimum total weight that an event has to have in order to get it among the results? | 38 | 21 |
247,152 | def setMaxDaysBack ( self , maxDaysBack ) : assert isinstance ( maxDaysBack , int ) , "maxDaysBack value has to be a positive integer" assert maxDaysBack >= 1 self . topicPage [ "maxDaysBack" ] = maxDaysBack | what is the maximum allowed age of the results? | 57 | 10 |
247,153 | def addConcept ( self , conceptUri , weight , label = None , conceptType = None ) : assert isinstance ( weight , ( float , int ) ) , "weight value has to be a positive or negative integer" concept = { "uri" : conceptUri , "wgt" : weight } if label != None : concept [ "label" ] = label if conceptType != None : concept [ "type" ] = conceptType self . topicPage [ "concepts" ] . append ( concept ) | add a relevant concept to the topic page | 109 | 8 |
247,154 | def addKeyword ( self , keyword , weight ) : assert isinstance ( weight , ( float , int ) ) , "weight value has to be a positive or negative integer" self . topicPage [ "keywords" ] . append ( { "keyword" : keyword , "wgt" : weight } ) | add a relevant keyword to the topic page | 66 | 8 |
247,155 | def addCategory ( self , categoryUri , weight ) : assert isinstance ( weight , ( float , int ) ) , "weight value has to be a positive or negative integer" self . topicPage [ "categories" ] . append ( { "uri" : categoryUri , "wgt" : weight } ) | add a relevant category to the topic page | 68 | 8 |
247,156 | def addSource ( self , sourceUri , weight ) : assert isinstance ( weight , ( float , int ) ) , "weight value has to be a positive or negative integer" self . topicPage [ "sources" ] . append ( { "uri" : sourceUri , "wgt" : weight } ) | add a news source to the topic page | 68 | 8 |
247,157 | def addSourceLocation ( self , sourceLocationUri , weight ) : assert isinstance ( weight , ( float , int ) ) , "weight value has to be a positive or negative integer" self . topicPage [ "sourceLocations" ] . append ( { "uri" : sourceLocationUri , "wgt" : weight } ) | add a list of relevant sources by identifying them by their geographic location | 72 | 13 |
247,158 | def addSourceGroup ( self , sourceGroupUri , weight ) : assert isinstance ( weight , ( float , int ) ) , "weight value has to be a positive or negative integer" self . topicPage [ "sourceGroups" ] . append ( { "uri" : sourceGroupUri , "wgt" : weight } ) | add a list of relevant sources by specifying a whole source group to the topic page | 72 | 16 |
247,159 | def addLocation ( self , locationUri , weight ) : assert isinstance ( weight , ( float , int ) ) , "weight value has to be a positive or negative integer" self . topicPage [ "locations" ] . append ( { "uri" : locationUri , "wgt" : weight } ) | add relevant location to the topic page | 68 | 7 |
247,160 | def setLanguages ( self , languages ) : if isinstance ( languages , six . string_types ) : languages = [ languages ] for lang in languages : assert len ( lang ) == 3 , "Expected to get language in ISO3 code" self . topicPage [ "langs" ] = languages | restrict the results to the list of specified languages | 64 | 10 |
247,161 | def getArticles ( self , page = 1 , count = 100 , sortBy = "rel" , sortByAsc = False , returnInfo = ReturnInfo ( ) ) : assert page >= 1 assert count <= 100 params = { "action" : "getArticlesForTopicPage" , "resultType" : "articles" , "dataType" : self . topicPage [ "dataType" ] , "articlesCount" : count , "articlesSortBy" : sortBy , "articlesSortByAsc" : sortByAsc , "page" : page , "topicPage" : json . dumps ( self . topicPage ) } params . update ( returnInfo . getParams ( "articles" ) ) return self . eventRegistry . jsonRequest ( "/json/article" , params ) | return a list of articles that match the topic page | 171 | 10 |
247,162 | def AND ( queryArr , exclude = None ) : assert isinstance ( queryArr , list ) , "provided argument as not a list" assert len ( queryArr ) > 0 , "queryArr had an empty list" q = CombinedQuery ( ) q . setQueryParam ( "$and" , [ ] ) for item in queryArr : assert isinstance ( item , ( CombinedQuery , BaseQuery ) ) , "item in the list was not a CombinedQuery or BaseQuery instance" q . getQuery ( ) [ "$and" ] . append ( item . getQuery ( ) ) if exclude != None : assert isinstance ( exclude , ( CombinedQuery , BaseQuery ) ) , "exclude parameter was not a CombinedQuery or BaseQuery instance" q . setQueryParam ( "$not" , exclude . getQuery ( ) ) return q | create a combined query with multiple items on which to perform an AND operation | 180 | 14 |
247,163 | async def start_pairing ( self ) : self . srp . initialize ( ) msg = messages . crypto_pairing ( { tlv8 . TLV_METHOD : b'\x00' , tlv8 . TLV_SEQ_NO : b'\x01' } ) resp = await self . protocol . send_and_receive ( msg , generate_identifier = False ) pairing_data = _get_pairing_data ( resp ) if tlv8 . TLV_BACK_OFF in pairing_data : time = int . from_bytes ( pairing_data [ tlv8 . TLV_BACK_OFF ] , byteorder = 'big' ) raise Exception ( 'back off {0}s' . format ( time ) ) self . _atv_salt = pairing_data [ tlv8 . TLV_SALT ] self . _atv_pub_key = pairing_data [ tlv8 . TLV_PUBLIC_KEY ] | Start pairing procedure . | 215 | 4 |
247,164 | async def finish_pairing ( self , pin ) : self . srp . step1 ( pin ) pub_key , proof = self . srp . step2 ( self . _atv_pub_key , self . _atv_salt ) msg = messages . crypto_pairing ( { tlv8 . TLV_SEQ_NO : b'\x03' , tlv8 . TLV_PUBLIC_KEY : pub_key , tlv8 . TLV_PROOF : proof } ) resp = await self . protocol . send_and_receive ( msg , generate_identifier = False ) pairing_data = _get_pairing_data ( resp ) atv_proof = pairing_data [ tlv8 . TLV_PROOF ] log_binary ( _LOGGER , 'Device' , Proof = atv_proof ) encrypted_data = self . srp . step3 ( ) msg = messages . crypto_pairing ( { tlv8 . TLV_SEQ_NO : b'\x05' , tlv8 . TLV_ENCRYPTED_DATA : encrypted_data } ) resp = await self . protocol . send_and_receive ( msg , generate_identifier = False ) pairing_data = _get_pairing_data ( resp ) encrypted_data = pairing_data [ tlv8 . TLV_ENCRYPTED_DATA ] return self . srp . step4 ( encrypted_data ) | Finish pairing process . | 326 | 4 |
247,165 | async def verify_credentials ( self ) : _ , public_key = self . srp . initialize ( ) msg = messages . crypto_pairing ( { tlv8 . TLV_SEQ_NO : b'\x01' , tlv8 . TLV_PUBLIC_KEY : public_key } ) resp = await self . protocol . send_and_receive ( msg , generate_identifier = False ) resp = _get_pairing_data ( resp ) session_pub_key = resp [ tlv8 . TLV_PUBLIC_KEY ] encrypted = resp [ tlv8 . TLV_ENCRYPTED_DATA ] log_binary ( _LOGGER , 'Device' , Public = self . credentials . ltpk , Encrypted = encrypted ) encrypted_data = self . srp . verify1 ( self . credentials , session_pub_key , encrypted ) msg = messages . crypto_pairing ( { tlv8 . TLV_SEQ_NO : b'\x03' , tlv8 . TLV_ENCRYPTED_DATA : encrypted_data } ) resp = await self . protocol . send_and_receive ( msg , generate_identifier = False ) # TODO: check status code self . _output_key , self . _input_key = self . srp . verify2 ( ) | Verify credentials with device . | 299 | 6 |
247,166 | def lookup_tag ( name ) : return next ( ( _TAGS [ t ] for t in _TAGS if t == name ) , DmapTag ( _read_unknown , 'unknown tag' ) ) | Look up a tag based on its key . Returns a DmapTag . | 45 | 15 |
247,167 | def connect_to_apple_tv ( details , loop , protocol = None , session = None ) : service = _get_service_used_to_connect ( details , protocol ) # If no session is given, create a default one if session is None : session = ClientSession ( loop = loop ) # AirPlay service is the same for both DMAP and MRP airplay = _setup_airplay ( loop , session , details ) # Create correct implementation depending on protocol if service . protocol == PROTOCOL_DMAP : return DmapAppleTV ( loop , session , details , airplay ) return MrpAppleTV ( loop , session , details , airplay ) | Connect and logins to an Apple TV . | 142 | 9 |
247,168 | def add_service ( self , zeroconf , service_type , name ) : self . lock . acquire ( ) try : self . _internal_add ( zeroconf , service_type , name ) finally : self . lock . release ( ) | Handle callback from zeroconf when a service has been discovered . | 55 | 14 |
247,169 | def add_hs_service ( self , info , address ) : if self . protocol and self . protocol != PROTOCOL_DMAP : return name = info . properties [ b'Name' ] . decode ( 'utf-8' ) hsgid = info . properties [ b'hG' ] . decode ( 'utf-8' ) self . _handle_service ( address , name , conf . DmapService ( hsgid , port = info . port ) ) | Add a new device to discovered list . | 102 | 8 |
247,170 | def add_non_hs_service ( self , info , address ) : if self . protocol and self . protocol != PROTOCOL_DMAP : return name = info . properties [ b'CtlN' ] . decode ( 'utf-8' ) self . _handle_service ( address , name , conf . DmapService ( None , port = info . port ) ) | Add a new device without Home Sharing to discovered list . | 81 | 11 |
247,171 | def add_mrp_service ( self , info , address ) : if self . protocol and self . protocol != PROTOCOL_MRP : return name = info . properties [ b'Name' ] . decode ( 'utf-8' ) self . _handle_service ( address , name , conf . MrpService ( info . port ) ) | Add a new MediaRemoteProtocol device to discovered list . | 74 | 12 |
247,172 | def add_airplay_service ( self , info , address ) : name = info . name . replace ( '._airplay._tcp.local.' , '' ) self . _handle_service ( address , name , conf . AirPlayService ( info . port ) ) | Add a new AirPlay device to discovered list . | 58 | 10 |
247,173 | def usable_service ( self ) : services = self . _services for protocol in self . _supported_protocols : if protocol in services and services [ protocol ] . is_usable ( ) : return services [ protocol ] return None | Return a usable service or None if there is none . | 49 | 11 |
247,174 | def superseeded_by ( self , other_service ) : if not other_service or other_service . __class__ != self . __class__ or other_service . protocol != self . protocol or other_service . port != self . port : return False # If this service does not have a login id but the other one does, then # we should return True here return not self . device_credentials and other_service . device_credentials | Return True if input service has login id and this has not . | 98 | 13 |
247,175 | async def print_what_is_playing ( loop ) : print ( 'Discovering devices on network...' ) atvs = await pyatv . scan_for_apple_tvs ( loop , timeout = 5 ) if not atvs : print ( 'no device found' , file = sys . stderr ) return print ( 'Connecting to {0}' . format ( atvs [ 0 ] . address ) ) atv = pyatv . connect_to_apple_tv ( atvs [ 0 ] , loop ) try : playing = await atv . metadata . playing ( ) print ( 'Currently playing:' ) print ( playing ) finally : # Do not forget to logout await atv . logout ( ) | Find a device and print what is playing . | 156 | 9 |
247,176 | async def start ( self , * * kwargs ) : zeroconf = kwargs [ 'zeroconf' ] self . _name = kwargs [ 'name' ] self . _pairing_guid = kwargs . get ( 'pairing_guid' , None ) or self . _generate_random_guid ( ) self . _web_server = web . Server ( self . handle_request , loop = self . _loop ) self . _server = await self . _loop . create_server ( self . _web_server , '0.0.0.0' ) # Get the allocated (random port) and include it in zeroconf service allocated_port = self . _server . sockets [ 0 ] . getsockname ( ) [ 1 ] _LOGGER . debug ( 'Started pairing web server at port %d' , allocated_port ) self . _setup_zeroconf ( zeroconf , allocated_port ) | Start the pairing server and publish service . | 215 | 8 |
247,177 | async def stop ( self , * * kwargs ) : _LOGGER . debug ( 'Shutting down pairing server' ) if self . _web_server is not None : await self . _web_server . shutdown ( ) self . _server . close ( ) if self . _server is not None : await self . _server . wait_closed ( ) | Stop pairing server and unpublish service . | 78 | 9 |
247,178 | async def handle_request ( self , request ) : service_name = request . rel_url . query [ 'servicename' ] received_code = request . rel_url . query [ 'pairingcode' ] . lower ( ) _LOGGER . info ( 'Got pairing request from %s with code %s' , service_name , received_code ) if self . _verify_pin ( received_code ) : cmpg = tags . uint64_tag ( 'cmpg' , int ( self . _pairing_guid , 16 ) ) cmnm = tags . string_tag ( 'cmnm' , self . _name ) cmty = tags . string_tag ( 'cmty' , 'iPhone' ) response = tags . container_tag ( 'cmpa' , cmpg + cmnm + cmty ) self . _has_paired = True return web . Response ( body = response ) # Code did not match, generate an error return web . Response ( status = 500 ) | Respond to request if PIN is correct . | 222 | 9 |
247,179 | def log_binary ( logger , message , * * kwargs ) : if logger . isEnabledFor ( logging . DEBUG ) : output = ( '{0}={1}' . format ( k , binascii . hexlify ( bytearray ( v ) ) . decode ( ) ) for k , v in sorted ( kwargs . items ( ) ) ) logger . debug ( '%s (%s)' , message , ', ' . join ( output ) ) | Log binary data if debug is enabled . | 102 | 8 |
247,180 | def _extract_command_with_args ( cmd ) : def _isint ( value ) : try : int ( value ) return True except ValueError : return False equal_sign = cmd . find ( '=' ) if equal_sign == - 1 : return cmd , [ ] command = cmd [ 0 : equal_sign ] args = cmd [ equal_sign + 1 : ] . split ( ',' ) converted = [ x if not _isint ( x ) else int ( x ) for x in args ] return command , converted | Parse input command with arguments . | 113 | 7 |
247,181 | def main ( ) : # Helper method so that the coroutine exits cleanly if an exception # happens (which would leave resources dangling) async def _run_application ( loop ) : try : return await cli_handler ( loop ) except KeyboardInterrupt : pass # User pressed Ctrl+C, just ignore it except SystemExit : pass # sys.exit() was used - do nothing except : # pylint: disable=bare-except # noqa import traceback traceback . print_exc ( file = sys . stderr ) sys . stderr . writelines ( '\n>>> An error occurred, full stack trace above\n' ) return 1 try : loop = asyncio . get_event_loop ( ) return loop . run_until_complete ( _run_application ( loop ) ) except KeyboardInterrupt : pass return 1 | Start the asyncio event loop and runs the application . | 180 | 11 |
247,182 | async def commands ( self ) : _print_commands ( 'Remote control' , interface . RemoteControl ) _print_commands ( 'Metadata' , interface . Metadata ) _print_commands ( 'Playing' , interface . Playing ) _print_commands ( 'AirPlay' , interface . AirPlay ) _print_commands ( 'Device' , DeviceCommands ) _print_commands ( 'Global' , self . __class__ ) return 0 | Print a list with available commands . | 102 | 7 |
247,183 | async def help ( self ) : if len ( self . args . command ) != 2 : print ( 'Which command do you want help with?' , file = sys . stderr ) return 1 iface = [ interface . RemoteControl , interface . Metadata , interface . Playing , interface . AirPlay , self . __class__ , DeviceCommands ] for cmd in iface : for key , value in cmd . __dict__ . items ( ) : if key . startswith ( '_' ) or key != self . args . command [ 1 ] : continue if inspect . isfunction ( value ) : signature = inspect . signature ( value ) else : signature = ' (property)' print ( 'COMMAND:\n>> {0}{1}\n\nHELP:\n{2}' . format ( key , signature , inspect . getdoc ( value ) ) ) return 0 | Print help text for a command . | 189 | 7 |
247,184 | async def scan ( self ) : atvs = await pyatv . scan_for_apple_tvs ( self . loop , timeout = self . args . scan_timeout , only_usable = False ) _print_found_apple_tvs ( atvs ) return 0 | Scan for Apple TVs on the network . | 60 | 8 |
247,185 | async def cli ( self ) : print ( 'Enter commands and press enter' ) print ( 'Type help for help and exit to quit' ) while True : command = await _read_input ( self . loop , 'pyatv> ' ) if command . lower ( ) == 'exit' : break elif command == 'cli' : print ( 'Command not availble here' ) continue await _handle_device_command ( self . args , command , self . atv , self . loop ) | Enter commands in a simple CLI . | 108 | 7 |
247,186 | async def artwork_save ( self ) : artwork = await self . atv . metadata . artwork ( ) if artwork is not None : with open ( 'artwork.png' , 'wb' ) as file : file . write ( artwork ) else : print ( 'No artwork is currently available.' ) return 1 return 0 | Download artwork and save it to artwork . png . | 68 | 11 |
247,187 | async def push_updates ( self ) : print ( 'Press ENTER to stop' ) self . atv . push_updater . start ( ) await self . atv . login ( ) await self . loop . run_in_executor ( None , sys . stdin . readline ) self . atv . push_updater . stop ( ) return 0 | Listen for push updates . | 81 | 5 |
247,188 | async def auth ( self ) : credentials = await self . atv . airplay . generate_credentials ( ) await self . atv . airplay . load_credentials ( credentials ) try : await self . atv . airplay . start_authentication ( ) pin = await _read_input ( self . loop , 'Enter PIN on screen: ' ) await self . atv . airplay . finish_authentication ( pin ) print ( 'You may now use these credentials:' ) print ( credentials ) return 0 except exceptions . DeviceAuthenticationError : logging . exception ( 'Failed to authenticate - invalid PIN?' ) return 1 | Perform AirPlay device authentication . | 138 | 7 |
247,189 | async def pair ( self ) : # Connect using the specified protocol # TODO: config should be stored elsewhere so that API is same for both protocol = self . atv . service . protocol if protocol == const . PROTOCOL_DMAP : await self . atv . pairing . start ( zeroconf = Zeroconf ( ) , name = self . args . remote_name , pairing_guid = self . args . pairing_guid ) elif protocol == const . PROTOCOL_MRP : await self . atv . pairing . start ( ) # Ask for PIN if present or just wait for pairing to end if self . atv . pairing . device_provides_pin : pin = await _read_input ( self . loop , 'Enter PIN on screen: ' ) self . atv . pairing . pin ( pin ) else : self . atv . pairing . pin ( self . args . pin_code ) print ( 'Use {0} to pair with "{1}" (press ENTER to stop)' . format ( self . args . pin_code , self . args . remote_name ) ) if self . args . pin_code is None : print ( 'Use any pin to pair with "{}" (press ENTER to stop)' . format ( self . args . remote_name ) ) else : print ( 'Use pin {} to pair with "{}" (press ENTER to stop)' . format ( self . args . pin_code , self . args . remote_name ) ) await self . loop . run_in_executor ( None , sys . stdin . readline ) await self . atv . pairing . stop ( ) # Give some feedback to the user if self . atv . pairing . has_paired : print ( 'Pairing seems to have succeeded, yey!' ) print ( 'You may now use these credentials: {0}' . format ( self . atv . pairing . credentials ) ) else : print ( 'Pairing failed!' ) return 1 return 0 | Pair pyatv as a remote control with an Apple TV . | 427 | 14 |
247,190 | def media_kind ( kind ) : if kind in [ 1 ] : return const . MEDIA_TYPE_UNKNOWN if kind in [ 3 , 7 , 11 , 12 , 13 , 18 , 32 ] : return const . MEDIA_TYPE_VIDEO if kind in [ 2 , 4 , 10 , 14 , 17 , 21 , 36 ] : return const . MEDIA_TYPE_MUSIC if kind in [ 8 , 64 ] : return const . MEDIA_TYPE_TV raise exceptions . UnknownMediaKind ( 'Unknown media kind: ' + str ( kind ) ) | Convert iTunes media kind to API representation . | 120 | 9 |
247,191 | def media_type_str ( mediatype ) : if mediatype == const . MEDIA_TYPE_UNKNOWN : return 'Unknown' if mediatype == const . MEDIA_TYPE_VIDEO : return 'Video' if mediatype == const . MEDIA_TYPE_MUSIC : return 'Music' if mediatype == const . MEDIA_TYPE_TV : return 'TV' return 'Unsupported' | Convert internal API media type to string . | 92 | 9 |
247,192 | def playstate ( state ) : # pylint: disable=too-many-return-statements if state is None : return const . PLAY_STATE_NO_MEDIA if state == 0 : return const . PLAY_STATE_IDLE if state == 1 : return const . PLAY_STATE_LOADING if state == 3 : return const . PLAY_STATE_PAUSED if state == 4 : return const . PLAY_STATE_PLAYING if state == 5 : return const . PLAY_STATE_FAST_FORWARD if state == 6 : return const . PLAY_STATE_FAST_BACKWARD raise exceptions . UnknownPlayState ( 'Unknown playstate: ' + str ( state ) ) | Convert iTunes playstate to API representation . | 148 | 9 |
247,193 | def playstate_str ( state ) : if state == const . PLAY_STATE_NO_MEDIA : return 'No media' if state == const . PLAY_STATE_IDLE : return 'Idle' if state == const . PLAY_STATE_LOADING : return 'Loading' if state == const . PLAY_STATE_PAUSED : return 'Paused' if state == const . PLAY_STATE_PLAYING : return 'Playing' if state == const . PLAY_STATE_FAST_FORWARD : return 'Fast forward' if state == const . PLAY_STATE_FAST_BACKWARD : return 'Fast backward' return 'Unsupported' | Convert internal API playstate to string . | 140 | 9 |
247,194 | def repeat_str ( state ) : if state == const . REPEAT_STATE_OFF : return 'Off' if state == const . REPEAT_STATE_TRACK : return 'Track' if state == const . REPEAT_STATE_ALL : return 'All' return 'Unsupported' | Convert internal API repeat state to string . | 65 | 9 |
247,195 | def protocol_str ( protocol ) : if protocol == const . PROTOCOL_MRP : return 'MRP' if protocol == const . PROTOCOL_DMAP : return 'DMAP' if protocol == const . PROTOCOL_AIRPLAY : return 'AirPlay' return 'Unknown' | Convert internal API protocol to string . | 63 | 8 |
247,196 | def first ( dmap_data , * path ) : if not ( path and isinstance ( dmap_data , list ) ) : return dmap_data for key in dmap_data : if path [ 0 ] in key : return first ( key [ path [ 0 ] ] , * path [ 1 : ] ) return None | Look up a value given a path in some parsed DMAP data . | 70 | 14 |
247,197 | def pprint ( data , tag_lookup , indent = 0 ) : output = '' if isinstance ( data , dict ) : for key , value in data . items ( ) : tag = tag_lookup ( key ) if isinstance ( value , ( dict , list ) ) and tag . type is not read_bplist : output += '{0}{1}: {2}\n' . format ( indent * ' ' , key , tag ) output += pprint ( value , tag_lookup , indent + 2 ) else : output += '{0}{1}: {2} {3}\n' . format ( indent * ' ' , key , str ( value ) , tag ) elif isinstance ( data , list ) : for elem in data : output += pprint ( elem , tag_lookup , indent ) else : raise exceptions . InvalidDmapDataError ( 'invalid dmap data: ' + str ( data ) ) return output | Return a pretty formatted string of parsed DMAP data . | 206 | 11 |
247,198 | def retrieve_commands ( obj ) : commands = { } # Name and help for func in obj . __dict__ : if not inspect . isfunction ( obj . __dict__ [ func ] ) and not isinstance ( obj . __dict__ [ func ] , property ) : continue if func . startswith ( '_' ) : continue commands [ func ] = _get_first_sentence_in_pydoc ( obj . __dict__ [ func ] ) return commands | Retrieve all commands and help texts from an API object . | 103 | 12 |
247,199 | def hash ( self ) : base = '{0}{1}{2}{3}' . format ( self . title , self . artist , self . album , self . total_time ) return hashlib . sha256 ( base . encode ( 'utf-8' ) ) . hexdigest ( ) | Create a unique hash for what is currently playing . | 65 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.