idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
235,500 | def get_field_for_object ( field_type , field_id , form ) : field_name = field_type + '_' + str ( field_id ) return form . __getitem__ ( field_name ) | This tag allows one to get a specific series or event form field in registration views . | 50 | 17 |
235,501 | def template_exists ( template_name ) : try : template . loader . get_template ( template_name ) return True except template . TemplateDoesNotExist : return False | Determine if a given template exists so that it can be loaded if so or a default alternative can be used if not . | 38 | 26 |
235,502 | def numRegisteredForRole ( event , role ) : if not isinstance ( event , Event ) or not isinstance ( role , DanceRole ) : return None return event . numRegisteredForRole ( role ) | This tag allows one to access the number of registrations for any dance role . | 43 | 15 |
235,503 | def soldOutForRole ( event , role ) : if not isinstance ( event , Event ) or not isinstance ( role , DanceRole ) : return None return event . soldOutForRole ( role ) | This tag allows one to determine whether any event is sold out for any particular role . | 43 | 17 |
235,504 | def numRegisteredForRoleName ( event , roleName ) : if not isinstance ( event , Event ) : return None try : role = DanceRole . objects . get ( name = roleName ) except ObjectDoesNotExist : return None return event . numRegisteredForRole ( role ) | This tag allows one to access the number of registrations for any dance role using only the role s name . | 60 | 21 |
235,505 | def create_new_code ( cls , * * kwargs ) : prefix = kwargs . pop ( 'prefix' , '' ) new = False while not new : # Standard is a ten-letter random string of uppercase letters random_string = '' . join ( random . choice ( string . ascii_uppercase ) for z in range ( 10 ) ) if not Voucher . objects . filter ( voucherId = '%s%s' % ( prefix , random_string ) ) . exists ( ) : new = True return Voucher . objects . create ( voucherId = '%s%s' % ( prefix , random_string ) , * * kwargs ) | Creates a new Voucher with a unique voucherId | 151 | 12 |
235,506 | def updateTransactionParty ( sender , instance , * * kwargs ) : if 'loaddata' in sys . argv or ( 'raw' in kwargs and kwargs [ 'raw' ] ) : return logger . debug ( 'TransactionParty signal fired for %s %s.' % ( instance . __class__ . __name__ , instance . id ) ) party = getattr ( instance , 'transactionparty' , None ) if party : party . save ( updateBy = instance ) | If a User StaffMember or Location is updated and there exists an associated TransactionParty then the name and other attributes of that party should be updated to reflect the new information . | 106 | 34 |
235,507 | def updateSquareFees ( paymentRecord ) : fees = paymentRecord . netFees invoice = paymentRecord . invoice invoice . fees = fees invoice . save ( ) invoice . allocateFees ( ) return fees | The Square Checkout API does not calculate fees immediately so this task is called to be asynchronously run 1 minute after the initial transaction so that any Invoice or ExpenseItem associated with this transaction also remains accurate . | 43 | 44 |
235,508 | def getClassTypeMonthlyData ( year = None , series = None , typeLimit = None ) : # If no year specified, report current year to date. if not year : year = timezone . now ( ) . year role_list = DanceRole . objects . distinct ( ) # Report data on all students registered unless otherwise specified if series not in [ 'registrations' , 'studenthours' ] and series not in [ x . pluralName for x in role_list ] : series = 'registrations' when_all = { 'eventregistration__dropIn' : False , 'eventregistration__cancelled' : False , } annotations = { 'registrations' : Sum ( Case ( When ( Q ( * * when_all ) , then = 1 ) , output_field = FloatField ( ) ) ) } for this_role in role_list : annotations [ this_role . pluralName ] = Sum ( Case ( When ( Q ( Q ( * * when_all ) & Q ( eventregistration__role = this_role ) ) , then = 1 ) , output_field = FloatField ( ) ) ) series_counts = Series . objects . filter ( year = year ) . annotate ( * * annotations ) . annotate ( studenthours = F ( 'duration' ) * F ( 'registrations' ) ) . select_related ( 'classDescription__danceTypeLevel__danceType' , 'classDescription__danceTypeLevel' ) # If no limit specified on number of types, then do not aggregate dance types. # Otherwise, report the typeLimit most common types individually, and report all # others as other. This gets tuples of names and counts dance_type_counts = [ ( dance_type , count ) for dance_type , count in Counter ( [ x . classDescription . danceTypeLevel for x in series_counts ] ) . items ( ) ] dance_type_counts . sort ( key = lambda k : k [ 1 ] , reverse = True ) if typeLimit : dance_types = [ x [ 0 ] for x in dance_type_counts [ : typeLimit ] ] else : dance_types = [ x [ 0 ] for x in dance_type_counts ] results = [ ] # Month by month, calculate the result data for month in range ( 1 , 13 ) : this_month_result = { 'month' : month , 'month_name' : month_name [ month ] , } for dance_type in dance_types : this_month_result [ dance_type . __str__ ( ) ] = series_counts . filter ( classDescription__danceTypeLevel = dance_type , month = month ) . aggregate ( Sum ( series ) ) [ '%s__sum' % series ] if typeLimit : this_month_result [ 'Other' ] = series_counts . filter ( month = month ) . exclude ( classDescription__danceTypeLevel__in = dance_types ) . aggregate ( Sum ( series ) ) [ '%s__sum' % series ] results . append ( this_month_result ) # Now get totals totals_result = { 'month' : 'Totals' , 'month_name' : 'totals' , } for dance_type in dance_types : totals_result [ dance_type . __str__ ( ) ] = series_counts . filter ( classDescription__danceTypeLevel = dance_type ) . aggregate ( Sum ( series ) ) [ '%s__sum' % series ] if typeLimit : totals_result [ 'Other' ] = series_counts . exclude ( classDescription__danceTypeLevel__in = dance_types ) . aggregate ( Sum ( series ) ) [ '%s__sum' % series ] results . append ( totals_result ) return results | To break out by class type and month simultaneously get data for each series and aggregate by class type . | 827 | 20 |
235,509 | def form_valid ( self , form ) : startDate = form . cleaned_data [ 'startDate' ] endDate = form . cleaned_data [ 'endDate' ] startTime = form . cleaned_data [ 'startTime' ] endTime = form . cleaned_data [ 'endTime' ] instructor = form . cleaned_data [ 'instructorId' ] interval_minutes = getConstant ( 'privateLessons__lessonLengthInterval' ) this_date = startDate while this_date <= endDate : this_time = startTime while this_time < endTime : InstructorAvailabilitySlot . objects . create ( instructor = instructor , startTime = ensure_localtime ( datetime . combine ( this_date , this_time ) ) , duration = interval_minutes , location = form . cleaned_data . get ( 'location' ) , room = form . cleaned_data . get ( 'room' ) , pricingTier = form . cleaned_data . get ( 'pricingTier' ) , ) this_time = ( ensure_localtime ( datetime . combine ( this_date , this_time ) ) + timedelta ( minutes = interval_minutes ) ) . time ( ) this_date += timedelta ( days = 1 ) return JsonResponse ( { 'valid' : True } ) | Create slots and return success message . | 285 | 7 |
235,510 | def form_valid ( self , form ) : slotIds = form . cleaned_data [ 'slotIds' ] deleteSlot = form . cleaned_data . get ( 'deleteSlot' , False ) these_slots = InstructorAvailabilitySlot . objects . filter ( id__in = slotIds ) if deleteSlot : these_slots . delete ( ) else : for this_slot in these_slots : this_slot . location = form . cleaned_data [ 'updateLocation' ] this_slot . room = form . cleaned_data [ 'updateRoom' ] this_slot . status = form . cleaned_data [ 'updateStatus' ] this_slot . pricingTier = form . cleaned_data . get ( 'updatePricing' ) this_slot . save ( ) return JsonResponse ( { 'valid' : True } ) | Modify or delete the availability slot as requested and return success message . | 182 | 14 |
235,511 | def get_form_kwargs ( self , * * kwargs ) : kwargs = super ( BookPrivateLessonView , self ) . get_form_kwargs ( * * kwargs ) kwargs [ 'user' ] = self . request . user if hasattr ( self . request , 'user' ) else None return kwargs | Pass the current user to the form to render the payAtDoor field if applicable . | 77 | 18 |
235,512 | def dispatch ( self , request , * args , * * kwargs ) : lessonSession = request . session . get ( PRIVATELESSON_VALIDATION_STR , { } ) try : self . lesson = PrivateLessonEvent . objects . get ( id = lessonSession . get ( 'lesson' ) ) except ( ValueError , ObjectDoesNotExist ) : messages . error ( request , _ ( 'Invalid lesson identifier passed to sign-up form.' ) ) return HttpResponseRedirect ( reverse ( 'bookPrivateLesson' ) ) expiry = parse_datetime ( lessonSession . get ( 'expiry' , '' ) , ) if not expiry or expiry < timezone . now ( ) : messages . info ( request , _ ( 'Your registration session has expired. Please try again.' ) ) return HttpResponseRedirect ( reverse ( 'bookPrivateLesson' ) ) self . payAtDoor = lessonSession . get ( 'payAtDoor' , False ) return super ( PrivateLessonStudentInfoView , self ) . dispatch ( request , * args , * * kwargs ) | Handle the session data passed by the prior view . | 243 | 10 |
235,513 | def get_object ( self , queryset = None ) : return get_object_or_404 ( GuestList . objects . filter ( id = self . kwargs . get ( 'guestlist_id' ) ) ) | Get the guest list from the URL | 50 | 7 |
235,514 | def get_context_data ( self , * * kwargs ) : event = Event . objects . filter ( id = self . kwargs . get ( 'event_id' ) ) . first ( ) if self . kwargs . get ( 'event_id' ) and not self . object . appliesToEvent ( event ) : raise Http404 ( _ ( 'Invalid event.' ) ) # Use the most current event if nothing has been specified. if not event : event = self . object . currentEvent context = { 'guestList' : self . object , 'event' : event , 'names' : self . object . getListForEvent ( event ) , } context . update ( kwargs ) return super ( GuestListView , self ) . get_context_data ( * * context ) | Add the list of names for the given guest list | 174 | 10 |
235,515 | def getBasePrice ( self , * * kwargs ) : if not self . pricingTier : return None return self . pricingTier . getBasePrice ( * * kwargs ) * max ( self . numSlots , 1 ) | This method overrides the method of the base Event class by checking the pricingTier associated with this PrivateLessonEvent and getting the appropriate price for it . | 50 | 31 |
235,516 | def customers ( self ) : return Customer . objects . filter ( Q ( privatelessoncustomer__lesson = self ) | Q ( registration__eventregistration__event = self ) ) . distinct ( ) | List both any individuals signed up via the registration and payment system and any individuals signed up without payment . | 44 | 20 |
235,517 | def save ( self , * args , * * kwargs ) : if not self . status : self . status == Event . RegStatus . hidden super ( PrivateLessonEvent , self ) . save ( * args , * * kwargs ) | Set registration status to hidden if it is not specified otherwise | 52 | 11 |
235,518 | def availableDurations ( self ) : potential_slots = InstructorAvailabilitySlot . objects . filter ( instructor = self . instructor , location = self . location , room = self . room , pricingTier = self . pricingTier , startTime__gte = self . startTime , startTime__lte = self . startTime + timedelta ( minutes = getConstant ( 'privateLessons__maximumLessonLength' ) ) , ) . exclude ( id = self . id ) . order_by ( 'startTime' ) duration_list = [ self . duration , ] last_start = self . startTime last_duration = self . duration max_duration = self . duration for slot in potential_slots : if max_duration + slot . duration > getConstant ( 'privateLessons__maximumLessonLength' ) : break if ( slot . startTime == last_start + timedelta ( minutes = last_duration ) and slot . isAvailable ) : duration_list . append ( max_duration + slot . duration ) last_start = slot . startTime last_duration = slot . duration max_duration += slot . duration return duration_list | A lesson can always be booked for the length of a single slot but this method checks if multiple slots are available . This method requires that slots are non - overlapping which needs to be enforced on slot save . | 244 | 41 |
235,519 | def availableRoles ( self ) : if not hasattr ( self . instructor , 'instructorprivatelessondetails' ) : return [ ] return [ [ x . id , x . name ] for x in self . instructor . instructorprivatelessondetails . roles . all ( ) ] | Some instructors only offer private lessons for certain roles so we should only allow booking for the roles that have been selected for the instructor . | 63 | 26 |
235,520 | def checkIfAvailable ( self , dateTime = timezone . now ( ) ) : return ( self . startTime >= dateTime + timedelta ( days = getConstant ( 'privateLessons__closeBookingDays' ) ) and self . startTime <= dateTime + timedelta ( days = getConstant ( 'privateLessons__openBookingDays' ) ) and not self . eventRegistration and ( self . status == self . SlotStatus . available or ( self . status == self . SlotStatus . tentative and getattr ( getattr ( self . temporaryEventRegistration , 'registration' , None ) , 'expirationDate' , timezone . now ( ) ) <= timezone . now ( ) ) ) ) | Available slots are available but also tentative slots that have been held as tentative past their expiration date | 153 | 18 |
235,521 | def json_event_feed ( request , location_id = None , room_id = None ) : if not getConstant ( 'calendar__privateCalendarFeedEnabled' ) or not request . user . is_staff : return JsonResponse ( { } ) this_user = request . user startDate = request . GET . get ( 'start' , '' ) endDate = request . GET . get ( 'end' , '' ) timeZone = request . GET . get ( 'timezone' , getattr ( settings , 'TIME_ZONE' , 'UTC' ) ) time_filter_dict_events = { } if startDate : time_filter_dict_events [ 'startTime__gte' ] = ensure_timezone ( datetime . strptime ( startDate , '%Y-%m-%d' ) ) if endDate : time_filter_dict_events [ 'endTime__lte' ] = ensure_timezone ( datetime . strptime ( endDate , '%Y-%m-%d' ) ) + timedelta ( days = 1 ) instructor_groups = list ( this_user . groups . all ( ) . values_list ( 'id' , flat = True ) ) filters = Q ( event__privateevent__isnull = False ) & ( Q ( event__privateevent__displayToGroup__in = instructor_groups ) | Q ( event__privateevent__displayToUsers = this_user ) | ( Q ( event__privateevent__displayToGroup__isnull = True ) & Q ( event__privateevent__displayToUsers__isnull = True ) ) ) if location_id : filters = filters & Q ( event__location__id = location_id ) if room_id : filters = filters & Q ( event__room_id = room_id ) occurrences = EventOccurrence . objects . filter ( filters ) . filter ( * * time_filter_dict_events ) . order_by ( '-startTime' ) eventlist = [ EventFeedItem ( x , timeZone = timeZone ) . __dict__ for x in occurrences ] return JsonResponse ( eventlist , safe = False ) | The Jquery fullcalendar app requires a JSON news feed so this function creates the feed from upcoming PrivateEvent objects | 469 | 23 |
235,522 | def checkRequirements ( sender , * * kwargs ) : if not getConstant ( 'requirements__enableRequirements' ) : return logger . debug ( 'Signal to check RegistrationContactForm handled by prerequisites app.' ) formData = kwargs . get ( 'formData' , { } ) first = formData . get ( 'firstName' ) last = formData . get ( 'lastName' ) email = formData . get ( 'email' ) request = kwargs . get ( 'request' , { } ) registration = kwargs . get ( 'registration' , None ) customer = Customer . objects . filter ( first_name = first , last_name = last , email = email ) . first ( ) requirement_warnings = [ ] requirement_errors = [ ] for ter in registration . temporaryeventregistration_set . all ( ) : if hasattr ( ter . event , 'getRequirements' ) : for req in ter . event . getRequirements ( ) : if not req . customerMeetsRequirement ( customer = customer , danceRole = ter . role ) : if req . enforcementMethod == Requirement . EnforcementChoice . error : requirement_errors . append ( ( ter . event . name , req . name ) ) if req . enforcementMethod == Requirement . EnforcementChoice . warning : requirement_warnings . append ( ( ter . event . name , req . name ) ) if requirement_errors : raise ValidationError ( format_html ( '<p>{}</p> <ul>{}</ul> <p>{}</p>' , ugettext ( 'Unfortunately, you do not meet the following requirements/prerequisites for the items you have chosen:\n' ) , mark_safe ( '' . join ( [ '<li><em>%s:</em> %s</li>\n' % x for x in requirement_errors ] ) ) , getConstant ( 'requirements__errorMessage' ) or '' , ) ) if requirement_warnings : messages . warning ( request , format_html ( '<p>{}</p> <ul>{}</ul> <p>{}</p>' , mark_safe ( ugettext ( '<strong>Please Note:</strong> It appears that you do not meet the following requirements/prerequisites for the items you have chosen:\n' ) ) , mark_safe ( '' . join ( [ '<li><em>%s:</em> %s</li>\n' % x for x in requirement_warnings ] ) ) , getConstant ( 'requirements__warningMessage' ) or '' , ) ) | Check that the customer meets all prerequisites for the items in the registration . | 572 | 15 |
235,523 | def get_email_context ( self , * * kwargs ) : context = kwargs context . update ( { 'currencyCode' : getConstant ( 'general__currencyCode' ) , 'currencySymbol' : getConstant ( 'general__currencySymbol' ) , 'businessName' : getConstant ( 'contact__businessName' ) , 'site_url' : getConstant ( 'email__linkProtocol' ) + '://' + Site . objects . get_current ( ) . domain , } ) return context | This method can be overridden in classes that inherit from this mixin so that additional object - specific context is provided to the email template . This should return a dictionary . By default only general financial context variables are added to the dictionary and kwargs are just passed directly . Note also that it is in general not a good idea for security reasons to pass model instances in the context here since these methods can be accessed by logged in users who use the SendEmailView . So In the default models of this app the values of fields and properties are passed directly instead . | 118 | 113 |
235,524 | def get_group_required ( self ) : this_object = self . model_object if hasattr ( this_object , self . group_required_field ) : if hasattr ( getattr ( this_object , self . group_required_field ) , 'name' ) : return [ getattr ( this_object , self . group_required_field ) . name ] return [ '' ] | Get the group_required value from the object | 85 | 9 |
235,525 | def check_membership ( self , groups ) : if not groups or groups == [ '' ] : return True if self . request . user . is_superuser : return True user_groups = self . request . user . groups . values_list ( "name" , flat = True ) return set ( groups ) . intersection ( set ( user_groups ) ) | Allows for objects with no required groups | 76 | 7 |
235,526 | def dispatch ( self , request , * args , * * kwargs ) : self . request = request in_group = False required_group = self . get_group_required ( ) if not required_group or required_group == [ '' ] : in_group = True elif self . request . user . is_authenticated ( ) : in_group = self . check_membership ( required_group ) if not in_group : if self . raise_exception : raise PermissionDenied else : return redirect_to_login ( request . get_full_path ( ) , self . get_login_url ( ) , self . get_redirect_field_name ( ) ) return super ( GroupRequiredMixin , self ) . dispatch ( request , * args , * * kwargs ) | This override of dispatch ensures that if no group is required then the request still goes through without being logged in . | 174 | 22 |
235,527 | def validate ( self , value ) : super ( ChoiceField , self ) . validate ( value ) try : get_template ( value ) except TemplateDoesNotExist : raise ValidationError ( _ ( '%s is not a valid template.' % value ) ) | Check for empty values and for an existing template but do not check if this is one of the initial choices provided . | 55 | 23 |
235,528 | def render ( self , context , instance , placeholder ) : if instance and instance . template : self . render_template = instance . template return super ( PluginTemplateMixin , self ) . render ( context , instance , placeholder ) | Permits setting of the template in the plugin instance configuration | 47 | 11 |
235,529 | def get_return_page ( self , prior = False ) : siteHistory = self . request . session . get ( 'SITE_HISTORY' , { } ) return getReturnPage ( siteHistory , prior = prior ) | This is just a wrapper for the getReturnPage helper function . | 48 | 13 |
235,530 | def is_valid ( self ) : valid = super ( RegistrationContactForm , self ) . is_valid ( ) msgs = messages . get_messages ( self . _request ) # We only want validation messages to show up once, so pop messages that have already show up # before checking to see if any messages remain to be shown. prior_messages = self . _session . pop ( 'prior_messages' , [ ] ) remaining_messages = [ ] for m in msgs : m_dict = { 'message' : m . message , 'level' : m . level , 'extra_tags' : m . extra_tags } if m_dict not in prior_messages : remaining_messages . append ( m_dict ) if remaining_messages : self . _session [ 'prior_messages' ] = remaining_messages self . _request . session . modified = True return False return valid | For this form to be considered valid there must be not only no errors but also no messages on the request that need to be shown . | 200 | 27 |
235,531 | def clean_total_refund_amount ( self ) : initial = self . cleaned_data . get ( 'initial_refund_amount' , 0 ) total = self . cleaned_data [ 'total_refund_amount' ] summed_refunds = sum ( [ v for k , v in self . cleaned_data . items ( ) if k . startswith ( 'item_refundamount_' ) ] ) if not self . cleaned_data . get ( 'id' ) : raise ValidationError ( 'ID not in cleaned data' ) if summed_refunds != total : raise ValidationError ( _ ( 'Passed value does not match sum of allocated refunds.' ) ) elif summed_refunds > self . cleaned_data [ 'id' ] . amountPaid + self . cleaned_data [ 'id' ] . refunds : raise ValidationError ( _ ( 'Total refunds allocated exceed revenue received.' ) ) elif total < initial : raise ValidationError ( _ ( 'Cannot reduce the total amount of the refund.' ) ) return total | The Javascript should ensure that the hidden input is updated but double check it here . | 232 | 16 |
235,532 | def clean ( self ) : super ( SubstituteReportingForm , self ) . clean ( ) occurrences = self . cleaned_data . get ( 'occurrences' , [ ] ) staffMember = self . cleaned_data . get ( 'staffMember' ) replacementFor = self . cleaned_data . get ( 'replacedStaffMember' , [ ] ) event = self . cleaned_data . get ( 'event' ) for occ in occurrences : for this_sub in occ . eventstaffmember_set . all ( ) : if this_sub . replacedStaffMember == replacementFor : self . add_error ( 'occurrences' , ValidationError ( _ ( 'One or more classes you have selected already has a substitute teacher for that class.' ) , code = 'invalid' ) ) if event and staffMember : if staffMember in [ x . staffMember for x in event . eventstaffmember_set . filter ( category__in = [ getConstant ( 'general__eventStaffCategoryAssistant' ) , getConstant ( 'general__eventStaffCategoryInstructor' ) ] ) ] : self . add_error ( 'event' , ValidationError ( _ ( 'You cannot substitute teach for a class in which you were an instructor.' ) , code = 'invalid' ) ) | This code prevents multiple individuals from substituting for the same class and class teacher . It also prevents an individual from substituting for a class in which they are a teacher . | 274 | 34 |
235,533 | def save ( self , commit = True ) : existing_record = EventStaffMember . objects . filter ( staffMember = self . cleaned_data . get ( 'staffMember' ) , event = self . cleaned_data . get ( 'event' ) , category = getConstant ( 'general__eventStaffCategorySubstitute' ) , replacedStaffMember = self . cleaned_data . get ( 'replacedStaffMember' ) , ) if existing_record . exists ( ) : record = existing_record . first ( ) for x in self . cleaned_data . get ( 'occurrences' ) : record . occurrences . add ( x ) record . save ( ) return record else : return super ( SubstituteReportingForm , self ) . save ( ) | If a staff member is reporting substitute teaching for a second time then we should update the list of occurrences for which they are a substitute on their existing EventStaffMember record rather than creating a new record and creating database issues . | 160 | 44 |
235,534 | def save ( self , commit = True ) : if getattr ( self . instance , 'instructor' , None ) : self . instance . instructor . availableForPrivates = self . cleaned_data . pop ( 'availableForPrivates' , self . instance . instructor . availableForPrivates ) self . instance . instructor . save ( update_fields = [ 'availableForPrivates' , ] ) super ( StaffMemberBioChangeForm , self ) . save ( commit = True ) | If the staff member is an instructor also update the availableForPrivates field on the Instructor record . | 103 | 20 |
235,535 | def save ( self , * args , * * kwargs ) : if not self . pluralName : self . pluralName = self . name + 's' super ( self . __class__ , self ) . save ( * args , * * kwargs ) | Just add s if no plural name given . | 56 | 9 |
235,536 | def getBasePrice ( self , * * kwargs ) : payAtDoor = kwargs . get ( 'payAtDoor' , False ) dropIns = kwargs . get ( 'dropIns' , 0 ) if dropIns : return dropIns * self . dropinPrice if payAtDoor : return self . doorPrice return self . onlinePrice | This handles the logic of finding the correct price . If more sophisticated discounting systems are needed then this PricingTier model can be subclassed or the discounts and vouchers apps can be used . | 79 | 37 |
235,537 | def availableRoles ( self ) : eventRoles = self . eventrole_set . filter ( capacity__gt = 0 ) if eventRoles . count ( ) > 0 : return [ x . role for x in eventRoles ] elif isinstance ( self , Series ) : return self . classDescription . danceTypeLevel . danceType . roles . all ( ) return [ ] | Returns the set of roles for this event . Since roles are not always custom specified for event this looks for the set of available roles in multiple places . If no roles are found then the method returns an empty list in which case it can be assumed that the event s registration is not role - specific . | 81 | 60 |
235,538 | def numRegisteredForRole ( self , role , includeTemporaryRegs = False ) : count = self . eventregistration_set . filter ( cancelled = False , dropIn = False , role = role ) . count ( ) if includeTemporaryRegs : count += self . temporaryeventregistration_set . filter ( dropIn = False , role = role ) . exclude ( registration__expirationDate__lte = timezone . now ( ) ) . count ( ) return count | Accepts a DanceRole object and returns the number of registrations of that role . | 102 | 16 |
235,539 | def capacityForRole ( self , role ) : if isinstance ( role , DanceRole ) : role_id = role . id else : role_id = role eventRoles = self . eventrole_set . filter ( capacity__gt = 0 ) if eventRoles . count ( ) > 0 and role_id not in [ x . role . id for x in eventRoles ] : ''' Custom role capacities exist but role this is not one of them. ''' return 0 elif eventRoles . count ( ) > 0 : ''' The role is a match to custom roles, so check the capacity. ''' return eventRoles . get ( role = role ) . capacity # No custom roles for this event, so get the danceType roles and use the overall # capacity divided by the number of roles if isinstance ( self , Series ) : try : availableRoles = self . classDescription . danceTypeLevel . danceType . roles . all ( ) if availableRoles . count ( ) > 0 and role_id not in [ x . id for x in availableRoles ] : ''' DanceType roles specified and this is not one of them ''' return 0 elif availableRoles . count ( ) > 0 and self . capacity : # Divide the total capacity by the number of roles and round up. return ceil ( self . capacity / availableRoles . count ( ) ) except ObjectDoesNotExist as e : logger . error ( 'Error in calculating capacity for role: %s' % e ) # No custom roles and no danceType to get roles from, so return the overall capacity return self . capacity | Accepts a DanceRole object and determines the capacity for that role at this event . this Since roles are not always custom specified for events this looks for the set of available roles in multiple places and only returns the overall capacity of the event if roles are not found elsewhere . | 343 | 54 |
235,540 | def soldOutForRole ( self , role , includeTemporaryRegs = False ) : return self . numRegisteredForRole ( role , includeTemporaryRegs = includeTemporaryRegs ) >= ( self . capacityForRole ( role ) or 0 ) | Accepts a DanceRole object and responds if the number of registrations for that role exceeds the capacity for that role at this event . | 54 | 26 |
235,541 | def allDayForDate ( self , this_date , timeZone = None ) : if isinstance ( this_date , datetime ) : d = this_date . date ( ) else : d = this_date date_start = datetime ( d . year , d . month , d . day ) naive_start = self . startTime if timezone . is_naive ( self . startTime ) else timezone . make_naive ( self . startTime , timezone = timeZone ) naive_end = self . endTime if timezone . is_naive ( self . endTime ) else timezone . make_naive ( self . endTime , timezone = timeZone ) return ( # Ensure that all comparisons are done in local time naive_start <= date_start and naive_end >= date_start + timedelta ( days = 1 , minutes = - 30 ) ) | This method determines whether the occurrence lasts the entirety of a specified day in the specified time zone . If no time zone is specified then it uses the default time zone ) . Also give a grace period of a few minutes to account for issues with the way events are sometimes entered . | 190 | 55 |
235,542 | def netHours ( self ) : if self . specifiedHours is not None : return self . specifiedHours elif self . category in [ getConstant ( 'general__eventStaffCategoryAssistant' ) , getConstant ( 'general__eventStaffCategoryInstructor' ) ] : return self . event . duration - sum ( [ sub . netHours for sub in self . replacementFor . all ( ) ] ) else : return sum ( [ x . duration for x in self . occurrences . filter ( cancelled = False ) ] ) | For regular event staff this is the net hours worked for financial purposes . For Instructors netHours is caclulated net of any substitutes . | 109 | 28 |
235,543 | def shortDescription ( self ) : cd = getattr ( self , 'classDescription' , None ) if cd : sd = getattr ( cd , 'shortDescription' , '' ) d = getattr ( cd , 'description' , '' ) return sd if sd else d return '' | Overrides property from Event base class . | 59 | 9 |
235,544 | def netHours ( self ) : if self . specifiedHours is not None : return self . specifiedHours return self . event . duration - sum ( [ sub . netHours for sub in self . replacementFor . all ( ) ] ) | For regular event staff this is the net hours worked for financial purposes . For Instructors netHours is calculated net of any substitutes . | 48 | 26 |
235,545 | def getTimeOfClassesRemaining ( self , numClasses = 0 ) : occurrences = EventOccurrence . objects . filter ( cancelled = False , event__in = [ x . event for x in self . temporaryeventregistration_set . filter ( event__series__isnull = False ) ] , ) . order_by ( '-endTime' ) if occurrences . count ( ) > numClasses : return occurrences [ numClasses ] . endTime else : return occurrences . last ( ) . startTime | For checking things like prerequisites it s useful to check if a requirement is almost met | 109 | 17 |
235,546 | def finalize ( self , * * kwargs ) : dateTime = kwargs . pop ( 'dateTime' , timezone . now ( ) ) # If sendEmail is passed as False, then we won't send an email sendEmail = kwargs . pop ( 'sendEmail' , True ) customer , created = Customer . objects . update_or_create ( first_name = self . firstName , last_name = self . lastName , email = self . email , defaults = { 'phone' : self . phone } ) regArgs = { 'customer' : customer , 'firstName' : self . firstName , 'lastName' : self . lastName , 'dateTime' : dateTime , 'temporaryRegistration' : self } for key in [ 'comments' , 'howHeardAboutUs' , 'student' , 'priceWithDiscount' , 'payAtDoor' ] : regArgs [ key ] = kwargs . pop ( key , getattr ( self , key , None ) ) # All other passed kwargs are put into the data JSON regArgs [ 'data' ] = self . data regArgs [ 'data' ] . update ( kwargs ) realreg = Registration ( * * regArgs ) realreg . save ( ) logger . debug ( 'Created registration with id: ' + str ( realreg . id ) ) for er in self . temporaryeventregistration_set . all ( ) : logger . debug ( 'Creating eventreg for event: ' + str ( er . event . id ) ) realer = EventRegistration ( registration = realreg , event = er . event , customer = customer , role = er . role , price = er . price , dropIn = er . dropIn , data = er . data ) realer . save ( ) # Mark this temporary registration as expired, so that it won't # be counted twice against the number of in-progress registrations # in the future when another customer tries to register. self . expirationDate = timezone . now ( ) self . save ( ) # This signal can, for example, be caught by the vouchers app to keep track of any vouchers # that were applied post_registration . send ( sender = TemporaryRegistration , registration = realreg ) if sendEmail : if getConstant ( 'email__disableSiteEmails' ) : logger . info ( 'Sending of confirmation emails is disabled.' ) else : logger . info ( 'Sending confirmation email.' ) template = getConstant ( 'email__registrationSuccessTemplate' ) realreg . email_recipient ( subject = template . subject , content = template . content , html_content = template . html_content , send_html = template . send_html , from_address = template . defaultFromAddress , from_name = template . defaultFromName , cc = template . defaultCC , ) # Return the newly-created finalized registration object return realreg | This method is called when the payment process has been completed and a registration is ready to be finalized . It also fires the post - registration signal | 621 | 28 |
235,547 | def save ( self , * args , * * kwargs ) : if self . send_html : self . content = get_text_for_html ( self . html_content ) else : self . html_content = None super ( EmailTemplate , self ) . save ( * args , * * kwargs ) | If this is an HTML template then set the non - HTML content to be the stripped version of the HTML . If this is a plain text template then set the HTML content to be null . | 68 | 38 |
235,548 | def create_from_registration ( cls , reg , * * kwargs ) : submissionUser = kwargs . pop ( 'submissionUser' , None ) collectedByUser = kwargs . pop ( 'collectedByUser' , None ) status = kwargs . pop ( 'status' , Invoice . PaymentStatus . unpaid ) new_invoice = cls ( firstName = reg . firstName , lastName = reg . lastName , email = reg . email , grossTotal = reg . totalPrice , total = reg . priceWithDiscount , submissionUser = submissionUser , collectedByUser = collectedByUser , buyerPaysSalesTax = getConstant ( 'registration__buyerPaysSalesTax' ) , status = status , data = kwargs , ) if isinstance ( reg , Registration ) : new_invoice . finalRegistration = reg ter_set = reg . eventregistration_set . all ( ) elif isinstance ( reg , TemporaryRegistration ) : new_invoice . temporaryRegistration = reg ter_set = reg . temporaryeventregistration_set . all ( ) else : raise ValueError ( 'Object passed is not a registration.' ) new_invoice . calculateTaxes ( ) new_invoice . save ( ) # Now, create InvoiceItem records for each EventRegistration for ter in ter_set : # Discounts and vouchers are always applied equally to all items at initial # invoice creation. item_kwargs = { 'invoice' : new_invoice , 'grossTotal' : ter . price , } if new_invoice . grossTotal > 0 : item_kwargs . update ( { 'total' : ter . price * ( new_invoice . total / new_invoice . grossTotal ) , 'taxes' : new_invoice . taxes * ( ter . price / new_invoice . grossTotal ) , 'fees' : new_invoice . fees * ( ter . price / new_invoice . grossTotal ) , } ) else : item_kwargs . update ( { 'total' : ter . price , 'taxes' : new_invoice . taxes , 'fees' : new_invoice . fees , } ) if isinstance ( ter , TemporaryEventRegistration ) : item_kwargs [ 'temporaryEventRegistration' ] = ter elif isinstance ( ter , EventRegistration ) : item_kwargs [ 'finalEventRegistration' ] = ter this_item = InvoiceItem ( * * item_kwargs ) this_item . save ( ) return new_invoice | Handles the creation of an Invoice as well as one InvoiceItem per assodciated TemporaryEventRegistration or registration . Also handles taxes appropriately . | 554 | 31 |
235,549 | def url ( self ) : if self . id : return '%s://%s%s' % ( getConstant ( 'email__linkProtocol' ) , Site . objects . get_current ( ) . domain , reverse ( 'viewInvoice' , args = [ self . id , ] ) , ) | Because invoice URLs are generally emailed this includes the default site URL and the protocol specified in settings . | 67 | 19 |
235,550 | def calculateTaxes ( self ) : tax_rate = ( getConstant ( 'registration__salesTaxRate' ) or 0 ) / 100 if tax_rate > 0 : if self . buyerPaysSalesTax : # If the buyer pays taxes, then taxes are just added as a fraction of the price self . taxes = self . total * tax_rate else : # If the seller pays sales taxes, then adjusted_total will be their net revenue, # and under this calculation adjusted_total + taxes = the price charged adjusted_total = self . total / ( 1 + tax_rate ) self . taxes = adjusted_total * tax_rate | Updates the tax field to reflect the amount of taxes depending on the local rate as well as whether the buyer or seller pays sales tax . | 137 | 28 |
235,551 | def allocateFees ( self ) : items = list ( self . invoiceitem_set . all ( ) ) # Check that totals and adjusments match. If they do not, raise an error. if self . total != sum ( [ x . total for x in items ] ) : msg = _ ( 'Invoice item totals do not match invoice total. Unable to allocate fees.' ) logger . error ( str ( msg ) ) raise ValidationError ( msg ) if self . adjustments != sum ( [ x . adjustments for x in items ] ) : msg = _ ( 'Invoice item adjustments do not match invoice adjustments. Unable to allocate fees.' ) logger . error ( str ( msg ) ) raise ValidationError ( msg ) for item in items : saveFlag = False if self . total - self . adjustments > 0 : item . fees = self . fees * ( ( item . total - item . adjustments ) / ( self . total - self . adjustments ) ) saveFlag = True # In the case of full refunds, allocate fees according to the # initial total price of the item only. elif self . total - self . adjustments == 0 and self . total > 0 : item . fees = self . fees * ( item . total / self . total ) saveFlag = True # In the unexpected event of fees with no total, just divide # the fees equally among the items. elif self . fees : item . fees = self . fees * ( 1 / len ( items ) ) saveFlag = True if saveFlag : item . save ( ) | Fees are allocated across invoice items based on their discounted total price net of adjustments as a proportion of the overall invoice s total price | 322 | 26 |
235,552 | def applyAndAllocate ( self , allocatedPrices , tieredTuples , payAtDoor = False ) : initial_net_price = sum ( [ x for x in allocatedPrices ] ) if self . discountType == self . DiscountType . flatPrice : # Flat-price for all applicable items (partial application for items which are # only partially needed to apply the discount). Flat prices ignore any previous discounts # in other categories which may have been the best, but they only are applied if they are # lower than the price that would be feasible by applying those prior discounts alone. applicable_price = self . getFlatPrice ( payAtDoor ) or 0 this_price = applicable_price + sum ( [ x [ 0 ] . event . getBasePrice ( payAtDoor = payAtDoor ) * x [ 1 ] if x [ 1 ] != 1 else x [ 0 ] . price for x in tieredTuples ] ) # Flat prices are allocated equally across all events this_allocated_prices = [ x * ( this_price / initial_net_price ) for x in allocatedPrices ] elif self . discountType == self . DiscountType . dollarDiscount : # Discount the set of applicable items by a specific number of dollars (currency units) # Dollar discounts are allocated equally across all events. this_price = initial_net_price - self . dollarDiscount this_allocated_prices = [ x * ( this_price / initial_net_price ) for x in allocatedPrices ] elif self . discountType == DiscountCombo . DiscountType . percentDiscount : # Percentage off discounts, which may be applied to all items in the cart, # or just to the items that were needed to apply the discount if self . percentUniversallyApplied : this_price = initial_net_price * ( 1 - ( max ( min ( self . percentDiscount or 0 , 100 ) , 0 ) / 100 ) ) this_allocated_prices = [ x * ( this_price / initial_net_price ) for x in allocatedPrices ] else : # Allocate the percentage discount based on the prior allocation from the prior category this_price = 0 this_allocated_prices = [ ] for idx , val in enumerate ( tieredTuples ) : this_val = ( allocatedPrices [ idx ] * ( 1 - val [ 1 ] ) * ( 1 - ( max ( min ( self . percentDiscount or 0 , 100 ) , 0 ) / 100 ) ) + allocatedPrices [ idx ] * val [ 1 ] ) this_allocated_prices . append ( this_val ) this_price += this_val else : raise KeyError ( _ ( 'Invalid discount type.' ) ) if this_price < initial_net_price : # Ensure no negative prices this_price = max ( this_price , 0 ) return self . DiscountInfo ( self , this_price , initial_net_price - this_price , this_allocated_prices ) | This method takes an initial allocation of prices across events and an identical length list of allocation tuples . It applies the rule specified by this discount allocates the discount across the listed items and returns both the price and the allocation | 648 | 44 |
235,553 | def getComponentList ( self ) : component_list = [ ] for x in self . discountcombocomponent_set . all ( ) : for y in range ( 0 , x . quantity ) : component_list += [ x ] component_list . sort ( key = lambda x : x . quantity , reverse = True ) return component_list | This function just returns a list with items that are supposed to be present in the the list multiple times as multiple elements of the list . It simplifies checking whether a discount s conditions are satisfied . | 73 | 39 |
235,554 | def save ( self , * args , * * kwargs ) : if self . discountType != self . DiscountType . flatPrice : self . onlinePrice = None self . doorPrice = None if self . discountType != self . DiscountType . dollarDiscount : self . dollarDiscount = None if self . discountType != self . DiscountType . percentDiscount : self . percentDiscount = None self . percentUniversallyApplied = False super ( DiscountCombo , self ) . save ( * args , * * kwargs ) | Don t save any passed values related to a type of discount that is not the specified type | 115 | 18 |
235,555 | def checkVoucherCode ( sender , * * kwargs ) : logger . debug ( 'Signal to check RegistrationContactForm handled by vouchers app.' ) formData = kwargs . get ( 'formData' , { } ) request = kwargs . get ( 'request' , { } ) registration = kwargs . get ( 'registration' , None ) session = getattr ( request , 'session' , { } ) . get ( REG_VALIDATION_STR , { } ) id = formData . get ( 'gift' , '' ) first = formData . get ( 'firstName' ) last = formData . get ( 'lastName' ) email = formData . get ( 'email' ) # Clean out the session data relating to vouchers so that we can revalidate it. session . pop ( 'total_voucher_amount' , 0 ) session . pop ( 'voucher_names' , None ) session . pop ( 'gift' , None ) if id == '' : return if not getConstant ( 'vouchers__enableVouchers' ) : raise ValidationError ( { 'gift' : _ ( 'Vouchers are disabled.' ) } ) if session . get ( 'gift' , '' ) != '' : raise ValidationError ( { 'gift' : _ ( 'Can\'t have more than one voucher' ) } ) eventids = [ x . event . id for x in registration . temporaryeventregistration_set . exclude ( dropIn = True ) ] seriess = Series . objects . filter ( id__in = eventids ) obj = Voucher . objects . filter ( voucherId = id ) . first ( ) if not obj : raise ValidationError ( { 'gift' : _ ( 'Invalid Voucher Id' ) } ) else : customer = Customer . objects . filter ( first_name = first , last_name = last , email = email ) . first ( ) # This will raise any other errors that may be relevant try : obj . validateForCustomerAndSeriess ( customer , seriess ) except ValidationError as e : # Ensures that the error is applied to the correct field raise ValidationError ( { 'gift' : e } ) # If we got this far, then the voucher is determined to be valid, so the registration # can proceed with no errors. return | Check that the given voucher code is valid | 516 | 8 |
235,556 | def applyVoucherCodeTemporarily ( sender , * * kwargs ) : logger . debug ( 'Signal fired to apply temporary vouchers.' ) reg = kwargs . pop ( 'registration' ) voucherId = reg . data . get ( 'gift' , '' ) try : voucher = Voucher . objects . get ( voucherId = voucherId ) except ObjectDoesNotExist : logger . debug ( 'No applicable vouchers found.' ) return tvu = TemporaryVoucherUse ( voucher = voucher , registration = reg , amount = 0 ) tvu . save ( ) logger . debug ( 'Temporary voucher use object created.' ) | When the core registration system creates a temporary registration with a voucher code the voucher app looks for vouchers that match that code and creates TemporaryVoucherUse objects to keep track of the fact that the voucher may be used . | 139 | 44 |
235,557 | def applyReferrerVouchersTemporarily ( sender , * * kwargs ) : # Only continue if the referral program is enabled if not getConstant ( 'referrals__enableReferralProgram' ) : return logger . debug ( 'Signal fired to temporarily apply referrer vouchers.' ) reg = kwargs . pop ( 'registration' ) # Email address is unique for users, so use that try : c = Customer . objects . get ( user__email = reg . email ) vouchers = c . getReferralVouchers ( ) except ObjectDoesNotExist : vouchers = None if not vouchers : logger . debug ( 'No referral vouchers found.' ) return for v in vouchers : TemporaryVoucherUse ( voucher = v , registration = reg , amount = 0 ) . save ( ) | Unlike voucher codes which have to be manually supplied referrer discounts are automatically applied here assuming that the referral program is enabled . | 171 | 24 |
235,558 | def applyVoucherCodesFinal ( sender , * * kwargs ) : logger . debug ( 'Signal fired to mark voucher codes as applied.' ) finalReg = kwargs . pop ( 'registration' ) tr = finalReg . temporaryRegistration tvus = TemporaryVoucherUse . objects . filter ( registration = tr ) for tvu in tvus : vu = VoucherUse ( voucher = tvu . voucher , registration = finalReg , amount = tvu . amount ) vu . save ( ) if getConstant ( 'referrals__enableReferralProgram' ) : awardReferrers ( vu ) | Once a registration has been completed vouchers are used and referrers are awarded | 136 | 14 |
235,559 | def provideCustomerReferralCode ( sender , * * kwargs ) : customer = kwargs . pop ( 'customer' ) if getConstant ( 'vouchers__enableVouchers' ) and getConstant ( 'referrals__enableReferralProgram' ) : vrd = ensureReferralVouchersExist ( customer ) return { 'referralVoucherId' : vrd . referreeVoucher . voucherId } | If the vouchers app is installed and referrals are enabled then the customer s profile page can show their voucher referral code . | 100 | 23 |
235,560 | def get_prep_lookup ( self ) : raise FieldError ( "{} '{}' does not support lookups" . format ( self . lhs . field . __class__ . __name__ , self . lookup_name ) ) | Raise errors for unsupported lookups | 52 | 7 |
235,561 | def derive_fernet_key ( input_key ) : hkdf = HKDF ( algorithm = hashes . SHA256 ( ) , length = 32 , salt = salt , info = info , backend = backend , ) return base64 . urlsafe_b64encode ( hkdf . derive ( force_bytes ( input_key ) ) ) | Derive a 32 - bit b64 - encoded Fernet key from arbitrary input key . | 76 | 18 |
235,562 | def reduce_cpu ( f , x , axes , dtype ) : axes = _get_axes ( axes , x . ndim ) if not axes : return x permute = [ n for n in range ( x . ndim ) if n not in axes ] permute = axes + permute T = x . transpose ( permute = permute ) N = len ( axes ) t = T . type . at ( N , dtype = dtype ) acc = x . empty ( t , device = x . device ) if f . identity is not None : _copyto ( acc , f . identity ) tl = T elif N == 1 and T . type . shape [ 0 ] > 0 : hd , tl = T [ 0 ] , T [ 1 : ] acc [ ( ) ] = hd else : raise ValueError ( "reduction not possible for function without an identity element" ) return fold ( f , acc , tl ) | NumPy s reduce in terms of fold . | 205 | 9 |
235,563 | def reduce_cuda ( g , x , axes , dtype ) : if axes != 0 : raise NotImplementedError ( "'axes' keyword is not implemented for CUDA" ) return g ( x , dtype = dtype ) | Reductions in CUDA use the thrust library for speed and have limited functionality . | 52 | 16 |
235,564 | def maxlevel ( lst ) : maxlev = 0 def f ( lst , level ) : nonlocal maxlev if isinstance ( lst , list ) : level += 1 maxlev = max ( level , maxlev ) for item in lst : f ( item , level ) f ( lst , 0 ) return maxlev | Return maximum nesting depth | 70 | 4 |
235,565 | def getitem ( lst , indices ) : if not indices : return lst i , indices = indices [ 0 ] , indices [ 1 : ] item = list . __getitem__ ( lst , i ) if isinstance ( i , int ) : return getitem ( item , indices ) # Empty slice: check if all subsequent indices are in range for the # full slice, raise IndexError otherwise. This is NumPy's behavior. if not item : if lst : _ = getitem ( lst , ( slice ( None ) , ) + indices ) elif any ( isinstance ( k , int ) for k in indices ) : raise IndexError return [ ] return [ getitem ( x , indices ) for x in item ] | Definition for multidimensional slicing and indexing on arbitrarily shaped nested lists . | 155 | 15 |
235,566 | def genslices ( n ) : def range_with_none ( ) : yield None yield from range ( - n , n + 1 ) for t in product ( range_with_none ( ) , range_with_none ( ) , range_with_none ( ) ) : s = slice ( * t ) if s . step != 0 : yield s | Generate all possible slices for a single dimension . | 77 | 10 |
235,567 | def genslices_ndim ( ndim , shape ) : iterables = [ genslices ( shape [ n ] ) for n in range ( ndim ) ] yield from product ( * iterables ) | Generate all possible slice tuples for shape . | 46 | 10 |
235,568 | def mutator ( mutate ) : @ functools . wraps ( mutate ) def inspyred_mutator ( random , candidates , args ) : mutants = [ ] for i , cs in enumerate ( candidates ) : mutants . append ( mutate ( random , cs , args ) ) return mutants inspyred_mutator . single_mutation = mutate return inspyred_mutator | Return an inspyred mutator function based on the given function . This function generator takes a function that operates on only one candidate to produce a single mutated candidate . The generator handles the iteration over each candidate in the set to be mutated . | 85 | 48 |
235,569 | def bit_flip_mutation ( random , candidate , args ) : rate = args . setdefault ( 'mutation_rate' , 0.1 ) mutant = copy . copy ( candidate ) if len ( mutant ) == len ( [ x for x in mutant if x in [ 0 , 1 ] ] ) : for i , m in enumerate ( mutant ) : if random . random ( ) < rate : mutant [ i ] = ( m + 1 ) % 2 return mutant | Return the mutants produced by bit - flip mutation on the candidates . | 101 | 13 |
235,570 | def random_reset_mutation ( random , candidate , args ) : bounder = args [ '_ec' ] . bounder try : values = bounder . values except AttributeError : values = None if values is not None : rate = args . setdefault ( 'mutation_rate' , 0.1 ) mutant = copy . copy ( candidate ) for i , m in enumerate ( mutant ) : if random . random ( ) < rate : mutant [ i ] = random . choice ( values ) return mutant else : return candidate | Return the mutants produced by randomly choosing new values . | 113 | 10 |
235,571 | def scramble_mutation ( random , candidate , args ) : rate = args . setdefault ( 'mutation_rate' , 0.1 ) if random . random ( ) < rate : size = len ( candidate ) p = random . randint ( 0 , size - 1 ) q = random . randint ( 0 , size - 1 ) p , q = min ( p , q ) , max ( p , q ) s = candidate [ p : q + 1 ] random . shuffle ( s ) return candidate [ : p ] + s [ : : - 1 ] + candidate [ q + 1 : ] else : return candidate | Return the mutants created by scramble mutation on the candidates . | 131 | 11 |
235,572 | def gaussian_mutation ( random , candidate , args ) : mut_rate = args . setdefault ( 'mutation_rate' , 0.1 ) mean = args . setdefault ( 'gaussian_mean' , 0.0 ) stdev = args . setdefault ( 'gaussian_stdev' , 1.0 ) bounder = args [ '_ec' ] . bounder mutant = copy . copy ( candidate ) for i , m in enumerate ( mutant ) : if random . random ( ) < mut_rate : mutant [ i ] += random . gauss ( mean , stdev ) mutant = bounder ( mutant , args ) return mutant | Return the mutants created by Gaussian mutation on the candidates . | 141 | 12 |
235,573 | def nonuniform_mutation ( random , candidate , args ) : bounder = args [ '_ec' ] . bounder num_gens = args [ '_ec' ] . num_generations max_gens = args [ 'max_generations' ] strength = args . setdefault ( 'mutation_strength' , 1 ) exponent = ( 1.0 - num_gens / float ( max_gens ) ) ** strength mutant = copy . copy ( candidate ) for i , ( c , lo , hi ) in enumerate ( zip ( candidate , bounder . lower_bound , bounder . upper_bound ) ) : if random . random ( ) <= 0.5 : new_value = c + ( hi - c ) * ( 1.0 - random . random ( ) ** exponent ) else : new_value = c - ( c - lo ) * ( 1.0 - random . random ( ) ** exponent ) mutant [ i ] = new_value return mutant | Return the mutants produced by nonuniform mutation on the candidates . | 212 | 13 |
235,574 | def crossover ( cross ) : @ functools . wraps ( cross ) def inspyred_crossover ( random , candidates , args ) : if len ( candidates ) % 2 == 1 : candidates = candidates [ : - 1 ] moms = candidates [ : : 2 ] dads = candidates [ 1 : : 2 ] children = [ ] for i , ( mom , dad ) in enumerate ( zip ( moms , dads ) ) : cross . index = i offspring = cross ( random , mom , dad , args ) for o in offspring : children . append ( o ) return children inspyred_crossover . single_crossover = cross return inspyred_crossover | Return an inspyred crossover function based on the given function . | 139 | 13 |
235,575 | def n_point_crossover ( random , mom , dad , args ) : crossover_rate = args . setdefault ( 'crossover_rate' , 1.0 ) num_crossover_points = args . setdefault ( 'num_crossover_points' , 1 ) children = [ ] if random . random ( ) < crossover_rate : num_cuts = min ( len ( mom ) - 1 , num_crossover_points ) cut_points = random . sample ( range ( 1 , len ( mom ) ) , num_cuts ) cut_points . sort ( ) bro = copy . copy ( dad ) sis = copy . copy ( mom ) normal = True for i , ( m , d ) in enumerate ( zip ( mom , dad ) ) : if i in cut_points : normal = not normal if not normal : bro [ i ] = m sis [ i ] = d normal = not normal children . append ( bro ) children . append ( sis ) else : children . append ( mom ) children . append ( dad ) return children | Return the offspring of n - point crossover on the candidates . | 225 | 12 |
235,576 | def uniform_crossover ( random , mom , dad , args ) : ux_bias = args . setdefault ( 'ux_bias' , 0.5 ) crossover_rate = args . setdefault ( 'crossover_rate' , 1.0 ) children = [ ] if random . random ( ) < crossover_rate : bro = copy . copy ( dad ) sis = copy . copy ( mom ) for i , ( m , d ) in enumerate ( zip ( mom , dad ) ) : if random . random ( ) < ux_bias : bro [ i ] = m sis [ i ] = d children . append ( bro ) children . append ( sis ) else : children . append ( mom ) children . append ( dad ) return children | Return the offspring of uniform crossover on the candidates . | 164 | 10 |
235,577 | def partially_matched_crossover ( random , mom , dad , args ) : crossover_rate = args . setdefault ( 'crossover_rate' , 1.0 ) if random . random ( ) < crossover_rate : size = len ( mom ) points = random . sample ( range ( size ) , 2 ) x , y = min ( points ) , max ( points ) bro = copy . copy ( dad ) bro [ x : y + 1 ] = mom [ x : y + 1 ] sis = copy . copy ( mom ) sis [ x : y + 1 ] = dad [ x : y + 1 ] for parent , child in zip ( [ dad , mom ] , [ bro , sis ] ) : for i in range ( x , y + 1 ) : if parent [ i ] not in child [ x : y + 1 ] : spot = i while x <= spot <= y : spot = parent . index ( child [ spot ] ) child [ spot ] = parent [ i ] return [ bro , sis ] else : return [ mom , dad ] | Return the offspring of partially matched crossover on the candidates . | 226 | 11 |
235,578 | def arithmetic_crossover ( random , mom , dad , args ) : ax_alpha = args . setdefault ( 'ax_alpha' , 0.5 ) ax_points = args . setdefault ( 'ax_points' , None ) crossover_rate = args . setdefault ( 'crossover_rate' , 1.0 ) bounder = args [ '_ec' ] . bounder children = [ ] if random . random ( ) < crossover_rate : bro = copy . copy ( dad ) sis = copy . copy ( mom ) if ax_points is None : ax_points = list ( range ( min ( len ( bro ) , len ( sis ) ) ) ) for i in ax_points : bro [ i ] = ax_alpha * mom [ i ] + ( 1 - ax_alpha ) * dad [ i ] sis [ i ] = ax_alpha * dad [ i ] + ( 1 - ax_alpha ) * mom [ i ] bro = bounder ( bro , args ) sis = bounder ( sis , args ) children . append ( bro ) children . append ( sis ) else : children . append ( mom ) children . append ( dad ) return children | Return the offspring of arithmetic crossover on the candidates . | 255 | 10 |
235,579 | def blend_crossover ( random , mom , dad , args ) : blx_alpha = args . setdefault ( 'blx_alpha' , 0.1 ) blx_points = args . setdefault ( 'blx_points' , None ) crossover_rate = args . setdefault ( 'crossover_rate' , 1.0 ) bounder = args [ '_ec' ] . bounder children = [ ] if random . random ( ) < crossover_rate : bro = copy . copy ( dad ) sis = copy . copy ( mom ) if blx_points is None : blx_points = list ( range ( min ( len ( bro ) , len ( sis ) ) ) ) for i in blx_points : smallest , largest = min ( mom [ i ] , dad [ i ] ) , max ( mom [ i ] , dad [ i ] ) delta = blx_alpha * ( largest - smallest ) bro [ i ] = smallest - delta + random . random ( ) * ( largest - smallest + 2 * delta ) sis [ i ] = smallest - delta + random . random ( ) * ( largest - smallest + 2 * delta ) bro = bounder ( bro , args ) sis = bounder ( sis , args ) children . append ( bro ) children . append ( sis ) else : children . append ( mom ) children . append ( dad ) return children | Return the offspring of blend crossover on the candidates . | 299 | 10 |
235,580 | def heuristic_crossover ( random , candidates , args ) : crossover_rate = args . setdefault ( 'crossover_rate' , 1.0 ) bounder = args [ '_ec' ] . bounder if len ( candidates ) % 2 == 1 : candidates = candidates [ : - 1 ] # Since we don't have fitness information in the candidates, we need # to make a dictionary containing the candidate and its corresponding # individual in the population. population = list ( args [ '_ec' ] . population ) lookup = dict ( zip ( [ pickle . dumps ( p . candidate , 1 ) for p in population ] , population ) ) moms = candidates [ : : 2 ] dads = candidates [ 1 : : 2 ] children = [ ] for mom , dad in zip ( moms , dads ) : if random . random ( ) < crossover_rate : bro = copy . copy ( dad ) sis = copy . copy ( mom ) mom_is_better = lookup [ pickle . dumps ( mom , 1 ) ] > lookup [ pickle . dumps ( dad , 1 ) ] for i , ( m , d ) in enumerate ( zip ( mom , dad ) ) : negpos = 1 if mom_is_better else - 1 val = d if mom_is_better else m bro [ i ] = val + random . random ( ) * negpos * ( m - d ) sis [ i ] = val + random . random ( ) * negpos * ( m - d ) bro = bounder ( bro , args ) sis = bounder ( sis , args ) children . append ( bro ) children . append ( sis ) else : children . append ( mom ) children . append ( dad ) return children | Return the offspring of heuristic crossover on the candidates . | 365 | 11 |
235,581 | def gravitational_force ( position_a , mass_a , position_b , mass_b ) : distance = distance_between ( position_a , position_b ) # Calculate the direction and magnitude of the force. angle = math . atan2 ( position_a [ 1 ] - position_b [ 1 ] , position_a [ 0 ] - position_b [ 0 ] ) magnitude = G * mass_a * mass_b / ( distance ** 2 ) # Find the x and y components of the force. # Determine sign based on which one is the larger body. sign = - 1 if mass_b > mass_a else 1 x_force = sign * magnitude * math . cos ( angle ) y_force = sign * magnitude * math . sin ( angle ) return x_force , y_force | Returns the gravitational force between the two bodies a and b . | 174 | 12 |
235,582 | def force_on_satellite ( position , mass ) : earth_grav_force = gravitational_force ( position , mass , earth_position , earth_mass ) moon_grav_force = gravitational_force ( position , mass , moon_position , moon_mass ) F_x = earth_grav_force [ 0 ] + moon_grav_force [ 0 ] F_y = earth_grav_force [ 1 ] + moon_grav_force [ 1 ] return F_x , F_y | Returns the total gravitational force acting on the body from the Earth and Moon . | 113 | 15 |
235,583 | def acceleration_of_satellite ( position , mass ) : F_x , F_y = force_on_satellite ( position , mass ) return F_x / mass , F_y / mass | Returns the acceleration based on all forces acting upon the body . | 44 | 12 |
235,584 | def evaluator ( evaluate ) : @ functools . wraps ( evaluate ) def inspyred_evaluator ( candidates , args ) : fitness = [ ] for candidate in candidates : fitness . append ( evaluate ( candidate , args ) ) return fitness inspyred_evaluator . single_evaluation = evaluate return inspyred_evaluator | Return an inspyred evaluator function based on the given function . This function generator takes a function that evaluates only one candidate . The generator handles the iteration over each candidate to be evaluated . | 75 | 39 |
235,585 | def parallel_evaluation_pp ( candidates , args ) : import pp logger = args [ '_ec' ] . logger try : evaluator = args [ 'pp_evaluator' ] except KeyError : logger . error ( 'parallel_evaluation_pp requires \'pp_evaluator\' be defined in the keyword arguments list' ) raise secret_key = args . setdefault ( 'pp_secret' , 'inspyred' ) try : job_server = args [ '_pp_job_server' ] except KeyError : pp_servers = args . get ( 'pp_servers' , ( "*" , ) ) pp_nprocs = args . get ( 'pp_nprocs' , 'autodetect' ) job_server = pp . Server ( ncpus = pp_nprocs , ppservers = pp_servers , secret = secret_key ) args [ '_pp_job_server' ] = job_server pp_depends = args . setdefault ( 'pp_dependencies' , ( ) ) pp_modules = args . setdefault ( 'pp_modules' , ( ) ) pickled_args = { } for key in args : try : pickle . dumps ( args [ key ] ) pickled_args [ key ] = args [ key ] except ( TypeError , pickle . PickleError , pickle . PicklingError ) : logger . debug ( 'unable to pickle args parameter {0} in parallel_evaluation_pp' . format ( key ) ) pass func_template = pp . Template ( job_server , evaluator , pp_depends , pp_modules ) jobs = [ func_template . submit ( [ c ] , pickled_args ) for c in candidates ] fitness = [ ] for i , job in enumerate ( jobs ) : r = job ( ) try : fitness . append ( r [ 0 ] ) except TypeError : logger . warning ( 'parallel_evaluation_pp generated an invalid fitness for candidate {0}' . format ( candidates [ i ] ) ) fitness . append ( None ) return fitness | Evaluate the candidates in parallel using Parallel Python . | 461 | 11 |
235,586 | def parallel_evaluation_mp ( candidates , args ) : import time import multiprocessing logger = args [ '_ec' ] . logger try : evaluator = args [ 'mp_evaluator' ] except KeyError : logger . error ( 'parallel_evaluation_mp requires \'mp_evaluator\' be defined in the keyword arguments list' ) raise try : nprocs = args [ 'mp_nprocs' ] except KeyError : nprocs = multiprocessing . cpu_count ( ) pickled_args = { } for key in args : try : pickle . dumps ( args [ key ] ) pickled_args [ key ] = args [ key ] except ( TypeError , pickle . PickleError , pickle . PicklingError ) : logger . debug ( 'unable to pickle args parameter {0} in parallel_evaluation_mp' . format ( key ) ) pass start = time . time ( ) try : pool = multiprocessing . Pool ( processes = nprocs ) results = [ pool . apply_async ( evaluator , ( [ c ] , pickled_args ) ) for c in candidates ] pool . close ( ) pool . join ( ) return [ r . get ( ) [ 0 ] for r in results ] except ( OSError , RuntimeError ) as e : logger . error ( 'failed parallel_evaluation_mp: {0}' . format ( str ( e ) ) ) raise else : end = time . time ( ) logger . debug ( 'completed parallel_evaluation_mp in {0} seconds' . format ( end - start ) ) | Evaluate the candidates in parallel using multiprocessing . | 356 | 13 |
235,587 | def allow_ajax ( request ) : if request . META . get ( 'REMOTE_ADDR' , None ) not in settings . INTERNAL_IPS : return False if toolbar_version < LooseVersion ( '1.8' ) and request . get_full_path ( ) . startswith ( DEBUG_TOOLBAR_URL_PREFIX ) and request . GET . get ( 'panel_id' , None ) != 'RequestHistoryPanel' : return False return bool ( settings . DEBUG ) | Default function to determine whether to show the toolbar on a given page . | 113 | 14 |
235,588 | def content ( self ) : toolbars = OrderedDict ( ) for id , toolbar in DebugToolbar . _store . items ( ) : content = { } for panel in toolbar . panels : panel_id = None nav_title = '' nav_subtitle = '' try : panel_id = panel . panel_id nav_title = panel . nav_title nav_subtitle = panel . nav_subtitle ( ) if isinstance ( panel . nav_subtitle , Callable ) else panel . nav_subtitle except Exception : logger . debug ( 'Error parsing panel info:' , exc_info = True ) if panel_id is not None : content . update ( { panel_id : { 'panel_id' : panel_id , 'nav_title' : nav_title , 'nav_subtitle' : nav_subtitle , } } ) toolbars [ id ] = { 'toolbar' : toolbar , 'content' : content } return get_template ( ) . render ( Context ( { 'toolbars' : OrderedDict ( reversed ( list ( toolbars . items ( ) ) ) ) , 'trunc_length' : CONFIG . get ( 'RH_POST_TRUNC_LENGTH' , 0 ) } ) ) | Content of the panel when it s displayed in full screen . | 270 | 12 |
235,589 | def extract_content ( self , selector = '' , attr = '' , default = '' , connector = '' , * args , * * kwargs ) : try : if selector . lower ( ) == "url" : return self . url if attr . lower ( ) == "text" : tag = self . get_tree_tag ( selector = selector , get_one = True ) content = connector . join ( [ make_ascii ( x ) . strip ( ) for x in tag . itertext ( ) ] ) content = content . replace ( "\n" , " " ) . strip ( ) else : tag = self . get_tree_tag ( selector = selector , get_one = True ) content = tag . get ( attr ) if attr in [ "href" , "src" ] : content = urljoin ( self . url , content ) return content except IndexError : if default is not "" : return default raise Exception ( "There is no content for the %s selector - %s" % ( self . __selector_type__ , selector ) ) except XPathError : raise Exception ( "Invalid %s selector - %s" % ( self . __selector_type__ , selector ) ) | Method for performing the content extraction for the particular selector type . \ | 262 | 13 |
235,590 | def extract_links ( self , selector = '' , * args , * * kwargs ) : try : links = self . get_tree_tag ( selector = selector ) for link in links : next_url = urljoin ( self . url , link . get ( 'href' ) ) yield type ( self ) ( next_url ) except XPathError : raise Exception ( "Invalid %s selector - %s" % ( self . __selector_type__ , selector ) ) except Exception : raise Exception ( "Invalid %s selector - %s" % ( self . __selector_type__ , selector ) ) | Method for performing the link extraction for the crawler . \ | 132 | 12 |
235,591 | def extract_tabular ( self , header = '' , prefix = '' , suffix = '' , table_type = '' , * args , * * kwargs ) : if type ( header ) in [ str , unicode ] : try : header_list = self . get_tree_tag ( header ) table_headers = [ prefix + h . text + suffix for h in header_list ] except XPathError : raise Exception ( "Invalid %s selector for table header - %s" % ( self . __selector_type__ , header ) ) except Exception : raise Exception ( "Invalid %s selector for table header - %s" % ( self . __selector_type__ , header ) ) else : table_headers = [ prefix + h + suffix for h in header ] if len ( table_headers ) == 0 : raise Exception ( "Invalid %s selector for table header - %s" % ( self . __selector_type__ , header ) ) if table_type not in [ "rows" , "columns" ] : raise Exception ( "Specify 'rows' or 'columns' in table_type" ) if table_type == "rows" : result_list = self . extract_rows ( table_headers = table_headers , * args , * * kwargs ) else : result_list = self . extract_columns ( table_headers = table_headers , * args , * * kwargs ) return table_headers , result_list | Method for performing the tabular data extraction . \ | 317 | 10 |
235,592 | def extract_rows ( self , result = { } , selector = '' , table_headers = [ ] , attr = '' , connector = '' , default = '' , verbosity = 0 , * args , * * kwargs ) : result_list = [ ] try : values = self . get_tree_tag ( selector ) if len ( table_headers ) >= len ( values ) : from itertools import izip_longest pairs = izip_longest ( table_headers , values , fillvalue = default ) else : from itertools import izip pairs = izip ( table_headers , values ) for head , val in pairs : if verbosity > 1 : print ( "\nExtracting" , head , "attribute" , sep = ' ' , end = '' ) if attr . lower ( ) == "text" : try : content = connector . join ( [ make_ascii ( x ) . strip ( ) for x in val . itertext ( ) ] ) except Exception : content = default content = content . replace ( "\n" , " " ) . strip ( ) else : content = val . get ( attr ) if attr in [ "href" , "src" ] : content = urljoin ( self . url , content ) result [ head ] = content result_list . append ( result ) except XPathError : raise Exception ( "Invalid %s selector - %s" % ( self . __selector_type__ , selector ) ) except TypeError : raise Exception ( "Selector expression string to be provided. Got " + selector ) return result_list | Row data extraction for extract_tabular | 347 | 8 |
235,593 | def extract_columns ( self , result = { } , selector = '' , table_headers = [ ] , attr = '' , connector = '' , default = '' , verbosity = 0 , * args , * * kwargs ) : result_list = [ ] try : if type ( selector ) in [ str , unicode ] : selectors = [ selector ] elif type ( selector ) == list : selectors = selector [ : ] else : raise Exception ( "Use a list of selector expressions for the various columns" ) from itertools import izip , count pairs = izip ( table_headers , selectors ) columns = { } for head , selector in pairs : columns [ head ] = self . get_tree_tag ( selector ) try : for i in count ( start = 0 ) : r = result . copy ( ) for head in columns . keys ( ) : if verbosity > 1 : print ( "\nExtracting" , head , "attribute" , sep = ' ' , end = '' ) col = columns [ head ] [ i ] if attr == "text" : try : content = connector . join ( [ make_ascii ( x ) . strip ( ) for x in col . itertext ( ) ] ) except Exception : content = default content = content . replace ( "\n" , " " ) . strip ( ) else : content = col . get ( attr ) if attr in [ "href" , "src" ] : content = urljoin ( self . url , content ) r [ head ] = content result_list . append ( r ) except IndexError : pass except XPathError : raise Exception ( "Invalid %s selector - %s" % ( self . __selector_type__ , selector ) ) except TypeError : raise Exception ( "Selector expression string to be provided. Got " + selector ) return result_list | Column data extraction for extract_tabular | 403 | 8 |
235,594 | def runCLI ( ) : args = docopt ( __doc__ , version = '0.3.0' ) try : check_arguments ( args ) command_list = [ 'genconfig' , 'run' , 'generate' ] select = itemgetter ( 'genconfig' , 'run' , 'generate' ) selectedCommand = command_list [ select ( args ) . index ( True ) ] cmdClass = get_command_class ( selectedCommand ) obj = cmdClass ( args ) obj . execute_command ( ) except POSSIBLE_EXCEPTIONS as e : print ( '\n' , e , '\n' ) | The starting point for the execution of the Scrapple command line tool . | 142 | 16 |
235,595 | def check_arguments ( args ) : projectname_re = re . compile ( r'[^a-zA-Z0-9_]' ) if args [ 'genconfig' ] : if args [ '--type' ] not in [ 'scraper' , 'crawler' ] : raise InvalidType ( "--type has to be 'scraper' or 'crawler'" ) if args [ '--selector' ] not in [ 'xpath' , 'css' ] : raise InvalidSelector ( "--selector has to be 'xpath' or 'css'" ) if args [ 'generate' ] or args [ 'run' ] : if args [ '--output_type' ] not in [ 'json' , 'csv' ] : raise InvalidOutputType ( "--output_type has to be 'json' or 'csv'" ) if args [ 'genconfig' ] or args [ 'generate' ] or args [ 'run' ] : if projectname_re . search ( args [ '<projectname>' ] ) is not None : message = "<projectname> should consist of letters, digits or _" raise InvalidProjectName ( message ) try : if int ( args [ '--levels' ] ) < 1 : message = "--levels should be greater than, or equal to 1" raise InvalidLevels ( message ) except ( TypeError , ValueError ) : message = " " . join ( [ "--levels should be an integer and not of type" , "{}" . format ( type ( args [ '--levels' ] ) ) ] ) raise InvalidLevels ( message ) | Validates the arguments passed through the CLI commands . | 348 | 10 |
235,596 | def form_to_json ( form ) : config = dict ( ) if form [ 'project_name' ] == "" : raise Exception ( 'Project name cannot be empty.' ) if form [ 'selector_type' ] not in [ "css" , "xpath" ] : raise Exception ( 'Selector type has to css or xpath' ) config [ 'project_name' ] = form [ 'project_name' ] config [ 'selector_type' ] = form [ 'selector_type' ] config [ 'scraping' ] = dict ( ) if form [ 'url' ] == "" : raise Exception ( 'URL cannot be empty' ) config [ 'scraping' ] [ 'url' ] = form [ 'url' ] config [ 'scraping' ] [ 'data' ] = list ( ) for i in itertools . count ( start = 1 ) : try : data = { 'field' : form [ 'field_' + str ( i ) ] , 'selector' : form [ 'selector_' + str ( i ) ] , 'attr' : form [ 'attribute_' + str ( i ) ] , 'default' : form [ 'default_' + str ( i ) ] } config [ 'scraping' ] [ 'data' ] . append ( data ) except KeyError : break # TODO : Crawler 'next' parameter handling with open ( os . path . join ( os . getcwd ( ) , form [ 'project_name' ] + '.json' ) , 'w' ) as f : json . dump ( config , f ) return | Takes the form from the POST request in the web interface and generates the JSON config \ file | 352 | 19 |
235,597 | def execute_command ( self ) : try : self . args [ '--verbosity' ] = int ( self . args [ '--verbosity' ] ) if self . args [ '--verbosity' ] not in [ 0 , 1 , 2 ] : raise ValueError if self . args [ '--verbosity' ] > 0 : print ( Back . GREEN + Fore . BLACK + "Scrapple Run" ) print ( Back . RESET + Fore . RESET ) import json with open ( self . args [ '<projectname>' ] + '.json' , 'r' ) as f : self . config = json . load ( f ) validate_config ( self . config ) self . run ( ) except ValueError : print ( Back . WHITE + Fore . RED + "Use 0, 1 or 2 for verbosity." + Back . RESET + Fore . RESET , sep = "" ) except IOError : print ( Back . WHITE + Fore . RED + self . args [ '<projectname>' ] , ".json does not " , "exist. Use ``scrapple genconfig``." + Back . RESET + Fore . RESET , sep = "" ) except InvalidConfigException as e : print ( Back . WHITE + Fore . RED + e + Back . RESET + Fore . RESET , sep = "" ) | The run command implements the web content extractor corresponding to the given \ configuration file . | 286 | 17 |
235,598 | def traverse_next ( page , nextx , results , tabular_data_headers = [ ] , verbosity = 0 ) : for link in page . extract_links ( selector = nextx [ 'follow_link' ] ) : if verbosity > 0 : print ( '\n' ) print ( Back . YELLOW + Fore . BLUE + "Loading page " , link . url + Back . RESET + Fore . RESET , end = '' ) r = results . copy ( ) for attribute in nextx [ 'scraping' ] . get ( 'data' ) : if attribute [ 'field' ] != "" : if verbosity > 1 : print ( "\nExtracting" , attribute [ 'field' ] , "attribute" , sep = ' ' , end = '' ) r [ attribute [ 'field' ] ] = link . extract_content ( * * attribute ) if not nextx [ 'scraping' ] . get ( 'table' ) : result_list = [ r ] else : tables = nextx [ 'scraping' ] . get ( 'table' , [ ] ) for table in tables : table . update ( { 'result' : r , 'verbosity' : verbosity } ) table_headers , result_list = link . extract_tabular ( * * table ) tabular_data_headers . extend ( table_headers ) if not nextx [ 'scraping' ] . get ( 'next' ) : for r in result_list : yield ( tabular_data_headers , r ) else : for nextx2 in nextx [ 'scraping' ] . get ( 'next' ) : for tdh , result in traverse_next ( link , nextx2 , r , tabular_data_headers = tabular_data_headers , verbosity = verbosity ) : yield ( tdh , result ) | Recursive generator to traverse through the next attribute and \ crawl through the links to be followed . | 404 | 19 |
235,599 | def validate_config ( config ) : fields = [ f for f in get_fields ( config ) ] if len ( fields ) != len ( set ( fields ) ) : raise InvalidConfigException ( "Invalid configuration file - %d duplicate field names" % len ( fields ) - len ( set ( fields ) ) ) return True | Validates the extractor configuration file . Ensures that there are no duplicate field names etc . | 68 | 19 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.