idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
52,200 | def send ( self , request , queryset ) : send_outward_mails . delay ( queryset ) messages . info ( request , _ ( 'Message sent successfully' ) , fail_silently = True ) | Send action available in change outward list |
52,201 | def post ( self , request , * args , ** kwargs ) : try : self . get_object ( ** kwargs ) except Http404 : return Response ( { 'detail' : _ ( 'Not Found' ) } , status = 404 ) if not self . is_contactable ( ) : return Response ( { 'detail' : _ ( 'This resource cannot be contacted' ) } , status = 400 ) content_type = Cont... | Contact node owner . |
52,202 | def get ( self , request , * args , ** kwargs ) : serializer = self . serializer_reader_class if request . user . is_authenticated ( ) : return Response ( serializer ( request . user , context = self . get_serializer_context ( ) ) . data ) else : return Response ( { 'detail' : _ ( 'Authentication credentials were not p... | return profile of current user if authenticated otherwise 401 |
52,203 | def post ( self , request , format = None ) : serializer_class = self . get_serializer_class ( ) serializer = serializer_class ( data = request . data , instance = request . user ) if serializer . is_valid ( ) : serializer . save ( ) return Response ( { 'detail' : _ ( u'Password successfully changed' ) } ) return Respo... | validate password change operation and return result |
52,204 | def retrieve_data ( self ) : url = self . config . get ( 'url' ) timeout = float ( self . config . get ( 'timeout' , 10 ) ) self . data = requests . get ( url , verify = self . verify_ssl , timeout = timeout ) . content | retrieve data from an HTTP URL |
52,205 | def get_text ( item , tag , default = False ) : try : xmlnode = item . getElementsByTagName ( tag ) [ 0 ] . firstChild except IndexError as e : if default is not False : return default else : raise IndexError ( e ) if xmlnode is not None : return unicode ( xmlnode . nodeValue ) else : return '' | returns text content of an xml tag |
52,206 | def _convert_item ( self , item ) : item = self . parse_item ( item ) if not item [ 'name' ] : raise Exception ( 'Expected property %s not found in item %s.' % ( self . keys [ 'name' ] , item ) ) elif len ( item [ 'name' ] ) > 75 : item [ 'name' ] = item [ 'name' ] [ : 75 ] if not item [ 'status' ] : item [ 'status' ] ... | take a parsed item as input and returns a python dictionary the keys will be saved into the Node model either in their respective fields or in the hstore data field |
52,207 | def get_queryset ( self ) : return self . queryset . all ( ) . accessible_to ( user = self . request . user ) | Returns only objects which are accessible to the current user . If user is not authenticated all public objects will be returned . |
52,208 | def patch ( self , request , * args , ** kwargs ) : with reversion . create_revision ( ) : reversion . set_user ( request . user ) reversion . set_comment ( 'changed through the RESTful API from ip %s' % request . META [ 'REMOTE_ADDR' ] ) kwargs [ 'partial' ] = True return self . update ( request , * args , ** kwargs ) | custom patch method to support django - reversion |
52,209 | def save ( self , * args , ** kwargs ) : adding_new = False if not self . pk or ( not self . cpu and not self . ram ) : if self . model . cpu : self . cpu = self . model . cpu if self . model . ram : self . ram = self . model . ram adding_new = True super ( DeviceToModelRel , self ) . save ( * args , ** kwargs ) try : ... | when creating a new record fill CPU and RAM info if available |
52,210 | def clean ( self , * args , ** kwargs ) : if self . from_user and self . from_user_id == self . to_user_id : raise ValidationError ( _ ( 'A user cannot send a notification to herself/himself' ) ) | from_user and to_user must differ |
52,211 | def save ( self , * args , ** kwargs ) : created = self . pk is None if self . check_user_settings ( medium = 'web' ) : super ( Notification , self ) . save ( * args , ** kwargs ) if created : self . send_notifications ( ) | custom save method to send email and push notification |
52,212 | def send_email ( self ) : if self . check_user_settings ( ) : send_mail ( _ ( self . type ) , self . email_message , settings . DEFAULT_FROM_EMAIL , [ self . to_user . email ] ) return True else : return False | send email notification according to user settings |
52,213 | def check_user_settings ( self , medium = 'email' ) : if self . type == 'custom' : return True try : user_settings = getattr ( self . to_user , '%s_notification_settings' % medium ) except ObjectDoesNotExist : return False user_setting_type = getattr ( user_settings . __class__ , self . type ) . user_setting_type if us... | Ensure user is ok with receiving this notification through the specified medium . Available mediums are web and email while mobile notifications will hopefully be implemented in the future . |
52,214 | def email_message ( self ) : url = settings . SITE_URL hello_text = __ ( "Hi %s," % self . to_user . get_full_name ( ) ) action_text = __ ( "\n\nMore details here: %s" ) % url explain_text = __ ( "This is an automatic notification sent from from %s.\n" "If you want to stop receiving this notification edit your" "email ... | compose complete email message text |
52,215 | def generate_key ( self , email ) : salt = sha1 ( str ( random ( ) ) ) . hexdigest ( ) [ : 5 ] return sha1 ( salt + email ) . hexdigest ( ) | Generate a new email confirmation key and return it . |
52,216 | def create_emailconfirmation ( self , email_address ) : "Create an email confirmation obj from the given email address obj" confirmation_key = self . generate_key ( email_address . email ) confirmation = self . create ( email_address = email_address , created_at = now ( ) , key = confirmation_key , ) return confirmatio... | Create an email confirmation obj from the given email address obj |
52,217 | def user_loggedin ( sender , ** kwargs ) : values = { 'value' : 1 , 'path' : kwargs [ 'request' ] . path , 'user_id' : str ( kwargs [ 'user' ] . pk ) , 'username' : kwargs [ 'user' ] . username , } write ( 'user_logins' , values = values ) | collect metrics about user logins |
52,218 | def user_deleted ( sender , ** kwargs ) : if kwargs . get ( 'created' ) : write ( 'user_variations' , { 'variation' : 1 } , tags = { 'action' : 'created' } ) write ( 'user_count' , { 'total' : User . objects . count ( ) } ) | collect metrics about new users signing up |
52,219 | def _node_rating_count ( self ) : try : return self . noderatingcount except ObjectDoesNotExist : node_rating_count = NodeRatingCount ( node = self ) node_rating_count . save ( ) return node_rating_count | Return node_rating_count record or create it if it does not exist |
52,220 | def _node_participation_settings ( self ) : try : return self . node_participation_settings except ObjectDoesNotExist : node_participation_settings = NodeParticipationSettings ( node = self ) node_participation_settings . save ( ) return node_participation_settings | Return node_participation_settings record or create it if it does not exist |
52,221 | def _action_allowed ( self , action ) : if getattr ( self . layer . participation_settings , '{0}_allowed' . format ( action ) ) is False : return False else : return getattr ( self . participation_settings , '{0}_allowed' . format ( action ) ) | participation actions can be disabled on layer level or disabled on a per node basis |
52,222 | def create_node_rating_counts_settings ( sender , ** kwargs ) : created = kwargs [ 'created' ] node = kwargs [ 'instance' ] if created : create_related_object . delay ( NodeRatingCount , { 'node' : node } ) create_related_object . delay ( NodeParticipationSettings , { 'node' : node } ) | create node rating count and settings |
52,223 | def create_layer_rating_settings ( sender , ** kwargs ) : created = kwargs [ 'created' ] layer = kwargs [ 'instance' ] if created : create_related_object . delay ( LayerParticipationSettings , { 'layer' : layer } ) | create layer rating settings |
52,224 | def needs_confirmation ( self ) : if EMAIL_CONFIRMATION : self . is_active = False self . save ( ) return True else : return False | set is_active to False if needs email confirmation |
52,225 | def change_password ( self , new_password ) : self . set_password ( new_password ) self . save ( ) password_changed . send ( sender = self . __class__ , user = self ) | Changes password and sends a signal |
52,226 | def add_notifications ( myclass ) : for key , value in TEXTS . items ( ) : if 'custom' in [ key , value ] : continue field_type = USER_SETTING [ key ] [ 'type' ] if field_type == 'boolean' : field = models . BooleanField ( _ ( key ) , default = DEFAULT_BOOLEAN ) elif field_type == 'distance' : field = models . IntegerF... | Decorator which adds fields dynamically to User Notification Settings models . |
52,227 | def validate ( self , attrs ) : user = authenticate ( ** self . user_credentials ( attrs ) ) if user : if user . is_active : self . instance = user else : raise serializers . ValidationError ( _ ( "This account is currently inactive." ) ) else : error = _ ( "Invalid login credentials." ) raise serializers . ValidationE... | checks if login credentials are correct |
52,228 | def get_details ( self , obj ) : return reverse ( 'api_user_social_links_detail' , args = [ obj . user . username , obj . pk ] , request = self . context . get ( 'request' ) , format = self . context . get ( 'format' ) ) | return detail url |
52,229 | def get_location ( self , obj ) : if not obj . city and not obj . country : return None elif obj . city and obj . country : return '%s, %s' % ( obj . city , obj . country ) elif obj . city or obj . country : return obj . city or obj . country | return user s location |
52,230 | def validate_current_password ( self , value ) : if self . instance and self . instance . has_usable_password ( ) and not self . instance . check_password ( value ) : raise serializers . ValidationError ( _ ( 'Current password is not correct' ) ) return value | current password check |
52,231 | def create_for_user ( self , user ) : if type ( user ) is unicode : from . profile import Profile as User user = User . objects . get ( email = user ) temp_key = token_generator . make_token ( user ) password_reset = PasswordReset ( user = user , temp_key = temp_key ) password_reset . save ( ) subject = _ ( "Password r... | create password reset for specified user |
52,232 | def handle ( self , * args , ** options ) : self . options = options delete = False try : self . stdout . write ( '\r\n' ) self . verbosity = int ( self . options . get ( 'verbosity' ) ) self . verbose ( 'disabling signals (notififcations, websocket alerts)' ) pause_disconnectable_signals ( ) self . check_status_mappin... | execute synchronize command |
52,233 | def check_status_mapping ( self ) : self . verbose ( 'checking status mapping...' ) if not self . status_mapping : self . message ( 'no status mapping found' ) return for old_val , new_val in self . status_mapping . iteritems ( ) : try : if isinstance ( new_val , basestring ) : lookup = { 'slug' : new_val } else : look... | ensure status map does not contain status values which are not present in DB |
52,234 | def retrieve_nodes ( self ) : self . verbose ( 'retrieving nodes from old mysql DB...' ) self . old_nodes = list ( OldNode . objects . all ( ) ) self . message ( 'retrieved %d nodes' % len ( self . old_nodes ) ) | retrieve nodes from old mysql DB |
52,235 | def extract_users ( self ) : email_set = set ( ) users_dict = { } self . verbose ( 'going to extract user information from retrieved nodes...' ) for node in self . old_nodes : email_set . add ( node . email ) if node . email not in users_dict : users_dict [ node . email ] = { 'owner' : node . owner } self . email_set =... | extract user info |
52,236 | def import_admins ( self ) : self . message ( 'saving admins into local DB' ) saved_admins = [ ] for olduser in OldUser . objects . all ( ) : try : user = User . objects . get ( Q ( username = olduser . username ) | Q ( email = olduser . email ) ) except User . DoesNotExist : user = User ( ) except User . MultipleObjec... | save admins to local DB |
52,237 | def import_users ( self ) : self . message ( 'saving users into local DB' ) saved_users = self . saved_admins for email in self . email_set : owner = self . users_dict [ email ] . get ( 'owner' ) if owner . strip ( ) == '' : owner , domain = email . split ( '@' ) owner = owner . replace ( '.' , ' ' ) if ' ' in owner : ... | save users to local DB |
52,238 | def check_deleted_nodes ( self ) : imported_nodes = Node . objects . filter ( data__contains = [ 'imported' ] ) deleted_nodes = [ ] for node in imported_nodes : if OldNode . objects . filter ( pk = node . pk ) . count ( ) == 0 : user = node . user deleted_nodes . append ( node ) node . delete ( ) if user . node_set . c... | delete imported nodes that are not present in the old database |
52,239 | def create_settings ( sender , ** kwargs ) : created = kwargs [ 'created' ] user = kwargs [ 'instance' ] if created : UserWebNotificationSettings . objects . create ( user = user ) UserEmailNotificationSettings . objects . create ( user = user ) | create user notification settings on user creation |
52,240 | def parse ( self ) : try : self . parsed_data = json . loads ( self . data ) except UnicodeError as e : self . parsed_data = json . loads ( self . data . decode ( 'latin1' ) ) except Exception as e : raise Exception ( 'Error while converting response from JSON to python. %s' % e ) if self . parsed_data . get ( 'type' ,... | parse geojson and ensure is collection |
52,241 | def retrieve_old_notifications ( self ) : date = ago ( days = DELETE_OLD ) return Notification . objects . filter ( added__lte = date ) | Retrieve notifications older than X days where X is specified in settings |
52,242 | def push_changes_to_external_layers ( node , external_layer , operation ) : from nodeshot . core . nodes . models import Node if not isinstance ( node , basestring ) : node = Node . objects . get ( pk = node . pk ) synchronizer = import_by_path ( external_layer . synchronizer_path ) instance = synchronizer ( external_l... | Sync other applications through their APIs by performing updates adds or deletes . This method is designed to be performed asynchronously avoiding blocking the user when he changes data on the local DB . |
52,243 | def send_message ( message , pipe = 'public' ) : if pipe not in [ 'public' , 'private' ] : raise ValueError ( 'pipe argument can be only "public" or "private"' ) else : pipe = pipe . upper ( ) pipe_path = PUBLIC_PIPE if pipe == 'PUBLIC' else PRIVATE_PIPE pipeout = open ( pipe_path , 'a' ) pipeout . write ( '%s\n' % mes... | writes message to pipe |
52,244 | def create_user ( backend , details , response , uid , username , user = None , * args , ** kwargs ) : if user : return { 'user' : user } if not username : return None email = details . get ( 'email' ) original_email = None if not email : message = _ ( ) raise AuthFailed ( backend , message ) if email and len ( email )... | Creates user . Depends on get_username pipeline . |
52,245 | def load_extra_data ( backend , details , response , uid , user , social_user = None , * args , ** kwargs ) : social_user = social_user or UserSocialAuth . get_social_auth ( backend . name , uid ) if kwargs [ 'is_new' ] and EMAIL_CONFIRMATION : from . . models import EmailAddress if EmailAddress . objects . filter ( em... | Load extra data from provider and store it on current UserSocialAuth extra_data field . |
52,246 | def send ( self ) : if self . content_type . name == 'node' : to = [ self . to . user . email ] elif self . content_type . name == 'layer' : to = [ self . to . email ] for mantainer in self . to . mantainers . all ( ) . only ( 'email' ) : to += [ mantainer . email ] else : to = [ self . to . email ] context = { 'sender... | Sends the email to the recipient If the sending fails will set the status of the instance to error and will log the error according to your project s django - logging configuration |
52,247 | def slice ( self , order_by = 'pk' , n = None ) : if n is not None and n < 0 : raise ValueError ( 'slice parameter cannot be negative' ) queryset = self . order_by ( order_by ) if n is None : return queryset [ 0 ] else : return queryset [ 0 : n ] | return n objects according to specified ordering |
52,248 | def access_level_up_to ( self , access_level ) : if isinstance ( access_level , int ) : value = access_level else : value = ACCESS_LEVELS . get ( access_level ) return self . filter ( access_level__lte = value ) | returns all items that have an access level equal or lower than the one specified |
52,249 | def save ( self , * args , ** kwargs ) : ignore_default_check = kwargs . pop ( 'ignore_default_check' , False ) if self . is_default != self . _current_is_default and self . is_default is True : for status in self . __class__ . objects . filter ( is_default = True ) : status . is_default = False status . save ( ignore_... | intercepts changes to is_default |
52,250 | def ready ( self ) : from . models import LayerExternal from nodeshot . core . layers . views import LayerNodeListMixin def get_nodes ( self , request , * args , ** kwargs ) : try : external = self . layer . external except LayerExternal . DoesNotExist : external = False if external and self . layer . is_external and h... | patch LayerNodesList view to support external layers |
52,251 | def init_celery ( project_name ) : os . environ . setdefault ( 'DJANGO_SETTINGS_MODULE' , '%s.settings' % project_name ) app = Celery ( project_name ) app . config_from_object ( 'django.conf:settings' ) app . autodiscover_tasks ( settings . INSTALLED_APPS , related_name = 'tasks' ) return app | init celery app without the need of redundant code |
52,252 | def send ( self ) : if self . status is OUTWARD_STATUS . get ( 'sent' ) : return False recipients = self . get_recipients ( ) emails = [ ] if OUTWARD_HTML : html_content = self . message EmailClass = EmailMultiAlternatives else : EmailClass = EmailMessage message = strip_tags ( self . message ) for recipient in recipie... | Sends the email to the recipients |
52,253 | def add_validation_method ( cls , method ) : method_name = method . func_name cls . _additional_validation . append ( method_name ) setattr ( cls , method_name , method ) | Extend validation of Node by adding a function to the _additional_validation list . The additional validation function will be called by the clean method |
52,254 | def point ( self ) : if not self . geometry : raise ValueError ( 'geometry attribute must be set before trying to get point property' ) if self . geometry . geom_type == 'Point' : return self . geometry else : try : return self . geometry . point_on_surface except GEOSException : return self . geometry . centroid | returns location of node . If node geometry is not a point a center point will be returned |
52,255 | def perform_create ( self , serializer ) : if serializer . instance is None : serializer . save ( user = self . request . user ) | determine user when node is added |
52,256 | def get_queryset ( self ) : queryset = super ( NodeList , self ) . get_queryset ( ) . select_related ( 'status' , 'user' , 'layer' ) search = self . request . query_params . get ( 'search' , None ) layers = self . request . query_params . get ( 'layers' , None ) if search is not None : search_query = ( Q ( name__iconta... | Optionally restricts the returned nodes by filtering against a search query parameter in the URL . |
52,257 | def create_notifications ( users , notification_model , notification_type , related_object ) : Notification = notification_model additional = related_object . __dict__ if related_object else '' notification_text = TEXTS [ notification_type ] % additional for user in users : n = Notification ( to_user = user , type = no... | create notifications in a background job to avoid slowing down users |
52,258 | def save ( self , * args , ** kwargs ) : self . type = INTERFACE_TYPES . get ( 'ethernet' ) super ( Ethernet , self ) . save ( * args , ** kwargs ) | automatically set Interface . type to ethernet |
52,259 | def root_endpoint ( request , format = None ) : endpoints = [ ] for urlmodule in urlpatterns : if hasattr ( urlmodule , 'urlconf_module' ) : is_urlconf_module = True else : is_urlconf_module = False if is_urlconf_module : for url in urlmodule . urlconf_module . urlpatterns : if url . name in [ 'django.swagger.resources... | List of all the available resources of this RESTful API . |
52,260 | def update_count ( self ) : node_rating_count = self . node . rating_count node_rating_count . comment_count = self . node . comment_set . count ( ) node_rating_count . save ( ) | updates comment count |
52,261 | def clean ( self , * args , ** kwargs ) : if not self . pk : node = self . node if node . participation_settings . comments_allowed is False : raise ValidationError ( "Comments not allowed for this node" ) if 'nodeshot.core.layers' in settings . INSTALLED_APPS : layer = node . layer if layer . participation_settings . ... | Check if comments can be inserted for parent node or parent layer |
52,262 | def retrieve_layers ( self , * args , ** options ) : queryset = Q ( ) if len ( args ) < 1 : all_layers = Layer . objects . published ( ) . external ( ) if options [ 'exclude' ] : exclude_list = options [ 'exclude' ] . replace ( ' ' , '' ) . split ( ',' ) return all_layers . exclude ( slug__in = exclude_list ) else : se... | Retrieve specified layers or all external layers if no layer specified . |
52,263 | def handle ( self , * args , ** options ) : self . verbosity = int ( options . get ( 'verbosity' ) ) self . stdout . write ( '\r\n' ) layers = self . retrieve_layers ( * args , ** options ) if len ( layers ) < 1 : self . stdout . write ( 'no layers to process\n\r' ) return else : self . verbose ( 'going to process %d l... | execute sync command |
52,264 | def save_external_nodes ( sender , ** kwargs ) : node = kwargs [ 'instance' ] operation = 'add' if kwargs [ 'created' ] is True else 'change' if node . layer . is_external is False or not hasattr ( node . layer , 'external' ) or node . layer . external . synchronizer_path is None : return False push_changes_to_external... | sync by creating nodes in external layers when needed |
52,265 | def delete_external_nodes ( sender , ** kwargs ) : node = kwargs [ 'instance' ] if node . layer . is_external is False or not hasattr ( node . layer , 'external' ) or node . layer . external . synchronizer_path is None : return False if hasattr ( node , 'external' ) and node . external . external_id : push_changes_to_e... | sync by deleting nodes from external layers when needed |
52,266 | def save ( self , * args , ** kwargs ) : if not self . pk : old_votes = Vote . objects . filter ( user = self . user , node = self . node ) for old_vote in old_votes : old_vote . delete ( ) super ( Vote , self ) . save ( * args , ** kwargs ) | ensure users cannot vote the same node multiple times but let users change their votes |
52,267 | def update_count ( self ) : node_rating_count = self . node . rating_count node_rating_count . likes = self . node . vote_set . filter ( vote = 1 ) . count ( ) node_rating_count . dislikes = self . node . vote_set . filter ( vote = - 1 ) . count ( ) node_rating_count . save ( ) | updates likes and dislikes count |
52,268 | def clean ( self , * args , ** kwargs ) : if not self . pk : if self . node . participation_settings . voting_allowed is not True : raise ValidationError ( "Voting not allowed for this node" ) if 'nodeshot.core.layers' in settings . INSTALLED_APPS : layer = self . node . layer if layer . participation_settings . voting... | Check if votes can be inserted for parent node or parent layer |
52,269 | def get_queryset ( self ) : queryset = super ( DeviceList , self ) . get_queryset ( ) search = self . request . query_params . get ( 'search' , None ) if search is not None : search_query = ( Q ( name__icontains = search ) | Q ( description__icontains = search ) ) queryset = queryset . filter ( search_query ) return qu... | Optionally restricts the returned devices by filtering against a search query parameter in the URL . |
52,270 | def save ( self , * args , ** kwargs ) : auto_update = kwargs . get ( 'auto_update' , True ) if auto_update : self . updated = now ( ) if 'auto_update' in kwargs : kwargs . pop ( 'auto_update' ) super ( BaseDate , self ) . save ( * args , ** kwargs ) | automatically update updated date field |
52,271 | def save ( self , * args , ** kwargs ) : if self . order == '' or self . order is None : try : self . order = self . get_auto_order_queryset ( ) . order_by ( "-order" ) [ 0 ] . order + 1 except IndexError : self . order = 0 super ( BaseOrdered , self ) . save ( ) | if order left blank |
52,272 | def check_dependencies ( dependencies , module ) : if type ( dependencies ) == str : dependencies = [ dependencies ] elif type ( dependencies ) != list : raise TypeError ( 'dependencies argument must be of type list or string' ) for dependency in dependencies : if dependency not in settings . INSTALLED_APPS : raise Dep... | Ensure dependencies of a module are listed in settings . INSTALLED_APPS |
52,273 | def get_key_by_value ( dictionary , search_value ) : for key , value in dictionary . iteritems ( ) : if value == search_value : return ugettext ( key ) | searchs a value in a dicionary and returns the key of the first occurrence |
52,274 | def get_layer ( self ) : if self . layer : return try : self . layer = Layer . objects . get ( slug = self . kwargs [ 'slug' ] ) except Layer . DoesNotExist : raise Http404 ( _ ( 'Layer not found' ) ) | retrieve layer from DB |
52,275 | def get_queryset ( self ) : self . get_layer ( ) return super ( LayerNodeListMixin , self ) . get_queryset ( ) . filter ( layer_id = self . layer . id ) | extend parent class queryset by filtering nodes of the specified layer |
52,276 | def get ( self , request , * args , ** kwargs ) : self . get_layer ( ) nodes = self . get_nodes ( request , * args , ** kwargs ) return Response ( nodes ) | Retrieve list of nodes of the specified layer |
52,277 | def save ( self , * args , ** kwargs ) : self . protocol = 'ipv%d' % self . address . version super ( Ip , self ) . save ( * args , ** kwargs ) | Determines ip protocol version automatically . Stores address in interface shortcuts for convenience . |
52,278 | def allow_relation ( self , obj1 , obj2 , ** hints ) : if obj1 . _meta . app_label != 'oldimporter' and obj2 . _meta . app_label != 'oldimporter' : return True return None | Relations between objects are allowed between nodeshot2 objects only |
52,279 | def allow_migrate ( self , db , model ) : if db != 'old_nodeshot' or model . _meta . app_label != 'oldimporter' : return False return True | Make sure the old_nodeshot app only appears in the old_nodeshot database |
52,280 | def metric_details ( request , pk , format = None ) : metric = get_object_or_404 ( Metric , pk = pk ) if request . method == 'GET' : try : results = metric . select ( q = request . query_params . get ( 'q' , metric . query ) ) except InfluxDBClientError as e : return Response ( { 'detail' : e . content } , status = e .... | Get or write metric values |
52,281 | def add_client ( self , user_id = None ) : if user_id is None : self . channel = 'public' user_id = uuid . uuid1 ( ) . hex else : self . channel = 'private' self . id = user_id self . channels [ self . channel ] [ self . id ] = self print 'Client connected to the %s channel.' % self . channel | Adds current instance to public or private channel . If user_id is specified it will be added to the private channel If user_id is not specified it will be added to the public one instead . |
52,282 | def broadcast ( cls , message ) : clients = cls . get_clients ( ) for id , client in clients . iteritems ( ) : client . send_message ( message ) | broadcast message to all connected clients |
52,283 | def send_private_message ( self , user_id , message ) : try : client = self . channels [ 'private' ] [ str ( user_id ) ] except KeyError : print '====debug====' print self . channels [ 'private' ] print 'client with id %s not found' % user_id return False client . send_message ( message ) print 'message sent to client ... | Send a message to a specific client . Returns True if successful False otherwise |
52,284 | def get_clients ( self ) : public = self . channels [ 'public' ] private = self . channels [ 'private' ] return dict ( public . items ( ) + private . items ( ) ) | return a merge of public and private clients |
52,285 | def open ( self ) : print 'Connection opened.' user_id = self . get_argument ( "user_id" , None ) self . add_client ( user_id ) self . send_message ( "Welcome to nodeshot websocket server." ) client_count = len ( self . get_clients ( ) . keys ( ) ) new_client_message = 'New client connected, now we have %d %s!' % ( cli... | method which is called every time a new client connects |
52,286 | def on_close ( self ) : print 'Connection closed.' self . remove_client ( ) client_count = len ( self . get_clients ( ) . keys ( ) ) new_client_message = '1 client disconnected, now we have %d %s!' % ( client_count , 'client' if client_count <= 1 else 'clients' ) self . broadcast ( new_client_message ) | method which is called every time a client disconnects |
52,287 | def create_database ( ) : db = get_db ( ) response = db . query ( 'SHOW DATABASES' ) items = list ( response . get_points ( 'databases' ) ) databases = [ database [ 'name' ] for database in items ] if settings . INFLUXDB_DATABASE not in databases : db . create_database ( settings . INFLUXDB_DATABASE ) print ( 'Created ... | creates database if necessary |
52,288 | def save ( self , * args , ** kwargs ) : if not self . pk : old_ratings = Rating . objects . filter ( user = self . user , node = self . node ) for old_rating in old_ratings : old_rating . delete ( ) super ( Rating , self ) . save ( * args , ** kwargs ) | ensure users cannot rate the same node multiple times but let users change their rating |
52,289 | def update_count ( self ) : node_rating_count = self . node . rating_count node_rating_count . rating_count = self . node . rating_set . count ( ) node_rating_count . rating_avg = self . node . rating_set . aggregate ( rate = Avg ( 'value' ) ) [ 'rate' ] if node_rating_count . rating_avg is None : node_rating_count . r... | updates rating count and rating average |
52,290 | def clean ( self , * args , ** kwargs ) : if not self . pk : node = self . node layer = Layer . objects . get ( pk = node . layer_id ) if layer . participation_settings . rating_allowed is not True : raise ValidationError ( "Rating not allowed for this layer" ) if node . participation_settings . rating_allowed is not T... | Check if rating can be inserted for parent node or parent layer |
52,291 | def save ( self , * args , ** kwargs ) : created = type ( self . pk ) is not int super ( UpdateCountsMixin , self ) . save ( * args , ** kwargs ) if created : self . update_count ( ) | custom save method to update counts |
52,292 | def delete ( self , * args , ** kwargs ) : super ( UpdateCountsMixin , self ) . delete ( * args , ** kwargs ) self . update_count ( ) | custom delete method to update counts |
52,293 | def update_topology ( ) : for topology in Topology . objects . all ( ) : try : topology . update ( ) except Exception as e : msg = 'Failed to update {}' . format ( topology . __repr__ ( ) ) logger . exception ( msg ) print ( '{0}: {1}\n' 'see networking.log for more information\n' . format ( msg , e . __class__ ) ) | updates all the topology sends logs to the nodeshot . networking logger |
52,294 | def backend_class ( self ) : if not self . backend : return None if not self . __backend_class : self . __backend_class = self . _get_netengine_backend ( ) return self . __backend_class | returns python netengine backend class importing it if needed |
52,295 | def netengine ( self ) : if not self . backend : return None if not self . __netengine : NetengineBackend = self . backend_class arguments = self . _build_netengine_arguments ( ) self . __netengine = NetengineBackend ( ** arguments ) return self . __netengine | access netengine instance |
52,296 | def _validate_backend ( self ) : try : self . backend_class except ( ImportError , AttributeError ) as e : raise ValidationError ( _ ( 'No valid backend found, got the following python exception: "%s"' ) % e ) | ensure backend string representation is correct |
52,297 | def _validate_config ( self ) : if not self . backend : return if len ( self . REQUIRED_CONFIG_KEYS ) < 1 : return self . config = self . config or { } required_keys_set = set ( self . REQUIRED_CONFIG_KEYS ) config_keys_set = set ( self . config . keys ( ) ) missing_required_keys = required_keys_set - config_keys_set u... | ensure REQUIRED_CONFIG_KEYS are filled |
52,298 | def _validate_duplicates ( self ) : if not self . id : duplicates = [ ] self . netengine_dict = self . netengine . to_dict ( ) for interface in self . netengine_dict [ 'interfaces' ] : if interface [ 'mac_address' ] in duplicates : continue if Interface . objects . filter ( mac__iexact = interface [ 'mac_address' ] ) .... | Ensure we re not creating a device that already exists Runs only when the DeviceConnector object is created not when is updated |
52,299 | def _get_netengine_arguments ( self , required = False ) : backend_class = self . _get_netengine_backend ( ) argspec = inspect . getargspec ( backend_class . __init__ ) args = argspec . args for argument_name in [ 'self' , 'host' , 'port' ] : args . remove ( argument_name ) if required : default_values = list ( argspec... | returns list of available config params returns list of required config params if required is True for internal use only |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.