Beispiel #1
0
    def _normalize_coerce_int4range(self, value):
        assert all(isinstance(x, int) for x in value)
        assert len(value) == 2

        return NumericRange(*value)
Beispiel #2
0
 def test_valid_integer(self):
     field = pg_forms.IntegerRangeField()
     value = field.clean(['1', '2'])
     self.assertEqual(value, NumericRange(1, 2))
Beispiel #3
0
 def test_integer_open(self):
     field = pg_forms.IntegerRangeField()
     value = field.clean(['', '0'])
     self.assertEqual(value, NumericRange(None, 0))
Beispiel #4
0
 def test_overlap(self):
     self.assertSequenceEqual(
         RangesModel.objects.filter(ints__overlap=NumericRange(3, 8)),
         [self.objs[0], self.objs[1]],
     )
Beispiel #5
0
 def test_not_gt(self):
     self.assertSequenceEqual(
         RangesModel.objects.filter(ints__not_gt=NumericRange(5, 10)),
         [self.objs[0], self.objs[2]],
     )
Beispiel #6
0
 def test_empty(self):
     r = NumericRange(empty=True)
     instance = RangesModel(ints=r)
     instance.save()
     loaded = RangesModel.objects.get()
     self.assertEqual(r, loaded.ints)
Beispiel #7
0
 def test_contains_range(self):
     self.assertSequenceEqual(
         RangesModel.objects.filter(ints__contains=NumericRange(3, 8)),
         [self.objs[0]],
     )
Beispiel #8
0
def tuple_to_numericrange(t):
    """Helper method to convert a tuple to an inclusive NumericRange."""
    if not t:
        return None
    return NumericRange(t[0], t[1], '[]')
    def setup(self):
        super(TestExternalSearch, self).setup()
        with temp_config() as config:
            config[Configuration.INTEGRATIONS][Configuration.ELASTICSEARCH_INTEGRATION] = {}
            config[Configuration.INTEGRATIONS][Configuration.ELASTICSEARCH_INTEGRATION][Configuration.URL] = "http://localhost:9200"
            config[Configuration.INTEGRATIONS][Configuration.ELASTICSEARCH_INTEGRATION][Configuration.ELASTICSEARCH_INDEX_KEY] = "test_index"

            try:
                ExternalSearchIndex.__client = None
                self.search = ExternalSearchIndex()
                # Start with an empty index
                self.search.setup_index()
            except Exception as e:
                self.search = None
                print "Unable to set up elasticsearch index, search tests will be skipped."
                print e

        if self.search:
            works = []

            self.moby_dick = self._work(title="Moby Dick", authors="Herman Melville", fiction=True)
            self.moby_dick.presentation_edition.subtitle = "Or, the Whale"
            self.moby_dick.presentation_edition.series = "Classics"
            self.moby_dick.summary_text = "Ishmael"
            self.moby_dick.presentation_edition.publisher = "Project Gutenberg"
            self.moby_dick.set_presentation_ready()
            works.append(self.moby_dick)

            self.moby_duck = self._work(title="Moby Duck", authors="Donovan Hohn", fiction=False)
            self.moby_duck.presentation_edition.subtitle = "The True Story of 28,800 Bath Toys Lost at Sea"
            self.moby_duck.summary_text = "A compulsively readable narrative"
            self.moby_duck.presentation_edition.publisher = "Penguin"
            self.moby_duck.set_presentation_ready()
            works.append(self.moby_duck)

            self.title_match = self._work(title="Match")
            self.title_match.set_presentation_ready()
            works.append(self.title_match)

            self.subtitle_match = self._work()
            self.subtitle_match.presentation_edition.subtitle = "Match"
            self.subtitle_match.set_presentation_ready()
            works.append(self.subtitle_match)

            self.summary_match = self._work()
            self.summary_match.summary_text = "Match"
            self.summary_match.set_presentation_ready()
            works.append(self.summary_match)
        
            self.publisher_match = self._work()
            self.publisher_match.presentation_edition.publisher = "Match"
            self.publisher_match.set_presentation_ready()
            works.append(self.publisher_match)

            self.tess = self._work(title="Tess of the d'Urbervilles")
            self.tess.set_presentation_ready()
            works.append(self.tess)

            self.tiffany = self._work(title="Breakfast at Tiffany's")
            self.tiffany.set_presentation_ready()
            works.append(self.tiffany)
            
            self.les_mis = self._work()
            self.les_mis.presentation_edition.title = u"Les Mis\u00E9rables"
            self.les_mis.set_presentation_ready()
            works.append(self.les_mis)

            self.lincoln = self._work(genre="Biography & Memoir", title="Abraham Lincoln")
            self.lincoln.set_presentation_ready()
            works.append(self.lincoln)

            self.washington = self._work(genre="Biography", title="George Washington")
            self.washington.set_presentation_ready()
            works.append(self.washington)

            self.lincoln_vampire = self._work(title="Abraham Lincoln: Vampire Hunter", genre="Fantasy")
            self.lincoln_vampire.set_presentation_ready()
            works.append(self.lincoln_vampire)

            self.children_work = self._work(title="Alice in Wonderland", audience=Classifier.AUDIENCE_CHILDREN)
            self.children_work.set_presentation_ready()
            works.append(self.children_work)

            self.ya_work = self._work(title="Go Ask Alice", audience=Classifier.AUDIENCE_YOUNG_ADULT)
            self.ya_work.set_presentation_ready()
            works.append(self.ya_work)

            self.adult_work = self._work(title="Still Alice", audience=Classifier.AUDIENCE_ADULT)
            self.adult_work.set_presentation_ready()
            works.append(self.adult_work)

            self.ya_romance = self._work(audience=Classifier.AUDIENCE_YOUNG_ADULT, genre="Romance")
            self.ya_romance.set_presentation_ready()
            works.append(self.ya_romance)

            self.no_age = self._work()
            self.no_age.summary_text = "President Barack Obama's election in 2008 energized the United States"
            self.no_age.set_presentation_ready()
            works.append(self.no_age)

            self.age_4_5 = self._work()
            self.age_4_5.target_age = NumericRange(4, 5, '[]')
            self.age_4_5.summary_text = "President Barack Obama's election in 2008 energized the United States"
            self.age_4_5.set_presentation_ready()
            works.append(self.age_4_5)

            self.age_5_6 = self._work(fiction=False)
            self.age_5_6.target_age = NumericRange(5, 6, '[]')
            self.age_5_6.set_presentation_ready()
            works.append(self.age_5_6)

            self.obama = self._work(genre="Biography & Memoir")
            self.obama.target_age = NumericRange(8, 8, '[]')
            self.obama.summary_text = "President Barack Obama's election in 2008 energized the United States"
            self.obama.set_presentation_ready()
            works.append(self.obama)

            self.dodger = self._work()
            self.dodger.target_age = NumericRange(8, 8, '[]')
            self.dodger.summary_text = "Willie finds himself running for student council president"
            self.dodger.set_presentation_ready()
            works.append(self.dodger)

            self.age_9_10 = self._work()
            self.age_9_10.target_age = NumericRange(9, 10, '[]')
            self.age_9_10.summary_text = "President Barack Obama's election in 2008 energized the United States"
            self.age_9_10.set_presentation_ready()
            works.append(self.age_9_10)

            self.age_2_10 = self._work()
            self.age_2_10.target_age = NumericRange(2, 10, '[]')
            self.age_2_10.set_presentation_ready()
            works.append(self.age_2_10)

            self.pride = self._work(title="Pride and Prejudice")
            self.pride.presentation_edition.medium = Edition.BOOK_MEDIUM
            self.pride.set_presentation_ready()
            works.append(self.pride)

            self.pride_audio = self._work(title="Pride and Prejudice")
            self.pride_audio.presentation_edition.medium = Edition.AUDIO_MEDIUM
            self.pride_audio.set_presentation_ready()
            works.append(self.pride_audio)

            self.sherlock = self._work(title="The Adventures of Sherlock Holmes")
            self.sherlock.presentation_edition.language = "en"
            self.sherlock.set_presentation_ready()
            works.append(self.sherlock)

            self.sherlock_spanish = self._work(title="Las Aventuras de Sherlock Holmes")
            self.sherlock_spanish.presentation_edition.language = "es"
            self.sherlock_spanish.set_presentation_ready()
            works.append(self.sherlock_spanish)

            self.search.bulk_update(works)

            time.sleep(2)
Beispiel #10
0
 def test_valid_decimal(self):
     field = pg_forms.DecimalRangeField()
     value = field.clean(["1.12345", "2.001"])
     self.assertEqual(value,
                      NumericRange(Decimal("1.12345"), Decimal("2.001")))
    def test_collect_event_with_work(self):
        integration, ignore = create(
            self._db,
            ExternalIntegration,
            goal=ExternalIntegration.ANALYTICS_GOAL,
            protocol="api.google_analytics_provider",
        )
        integration.url = self._str
        ConfigurationSetting.for_library_and_externalintegration(
            self._db,
            GoogleAnalyticsProvider.TRACKING_ID,
            self._default_library,
            integration,
        ).value = "faketrackingid"
        ga = MockGoogleAnalyticsProvider(integration, self._default_library)

        work = self._work(
            title="pi\u00F1ata",
            authors="chlo\u00E9",
            fiction=True,
            audience="audience",
            language="lang",
            with_license_pool=True,
            genre="Folklore",
            with_open_access_download=True,
        )
        work.presentation_edition.publisher = "publisher"
        work.target_age = NumericRange(10, 15)
        [lp] = work.license_pools
        now = utc_now()
        ga.collect_event(
            self._default_library,
            lp,
            CirculationEvent.DISTRIBUTOR_CHECKIN,
            now,
            neighborhood="Neighborhood will not be sent",
        )

        # Neighborhood information is not being sent -- that's for
        # local consumption only.
        assert "Neighborhood" not in ga.params

        # Let's take a look at what _is_ being sent.
        params = urllib.parse.parse_qs(ga.params)

        assert 1 == ga.count
        assert integration.url == ga.url
        assert "faketrackingid" == params["tid"][0]
        assert "event" == params["t"][0]
        assert "circulation" == params["ec"][0]
        assert CirculationEvent.DISTRIBUTOR_CHECKIN == params["ea"][0]
        assert str(now) == params["cd1"][0]
        assert lp.identifier.identifier == params["cd2"][0]
        assert lp.identifier.type == params["cd3"][0]
        assert unicodedata.normalize("NFKD", work.title) == params["cd4"][0]
        assert unicodedata.normalize("NFKD", work.author) == params["cd5"][0]
        assert "fiction" == params["cd6"][0]
        assert "audience" == params["cd7"][0]
        assert work.target_age_string == params["cd8"][0]
        assert "publisher" == params["cd9"][0]
        assert "lang" == params["cd10"][0]
        assert "Folklore" == params["cd11"][0]
        assert "true" == params["cd12"][0]
        assert DataSource.GUTENBERG == params["cd13"][0]
        assert EditionConstants.BOOK_MEDIUM == params["cd14"][0]
        assert self._default_library.short_name == params["cd15"][0]
Beispiel #12
0
 def test_unbounded(self):
     r = NumericRange(None, None, "()")
     instance = RangesModel(decimals=r)
     instance.save()
     loaded = RangesModel.objects.get()
     self.assertEqual(r, loaded.decimals)
Beispiel #13
0
def load(apps, schema):
    with open('csvs/Punkty 2018_2019 -  .csv', newline='') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        row_number = 0
        for row in csv_reader:
            row_number += 1
            if row_number > 4 and row[1] == 'LO' and 'Branżowa' not in row[2]:
                name = row[2].strip()
                school = School.objects.get(school_name=name)
                print(school.school_name + ':' + str(school.id))
                hss = HighSchoolClass()
                hss.school = school
                class_name = row[3]
                # first part of name eg. 1A humanistyczna
                hss.name = re.sub('[\\[]', '', re.findall(r'.+\[', class_name)[0]).strip()
                hss.year = NumericRange(2018, 2020, '[)')

                # class has only one type that is written in brackets eg. [O]
                hss.type = re.sub('[\\[\\]]', '', re.findall(r'\[.+\]', class_name)[0])
                hss.save()
                # subjects are placed between the type and list of languages eg. [O] mat-fiz (ang,niem)
                subjects = re.sub('[\\]\\(]', '', re.findall(r'\].+\(', class_name)[0]).strip().split('-')

                for s in subjects:
                    subject = ExtendedSubject()
                    subject.name = s
                    subject.high_school_class = hss
                    subject.save()

                # stats
                st = Statistics()
                st.high_school_class = hss
                stats = {'min': row[4].strip(), 'avg': row[5].strip(), 'max': row[6].strip()}
                for (k, v) in stats.items():
                    stats[k] = re.sub(',', '.', v)
                    if 'laur' in v.lower():
                        stats[k] = Statistics.LAUREAT
                    elif '**' in v:
                        st.with_competency_test = True
                        stats[k] = re.sub('\\*', '', stats[k])
                    elif '*' in v:
                        st.only_sports_test = True
                        stats[k] = re.sub('\\*', '', stats[k])

                st.points_min = stats['min']
                st.points_avg = stats['avg']
                st.points_max = stats['max']
                st.round = 1
                st.save()

                # languages are placed in brackets eg. (ang*-niem*,fran*), sometimes it's not the first bracket
                # before the '-' are first foreign language choices, after are second foreign language choices
                # '*' by first foreign language means choice of level P or R
                # '*' by second foreign language means choice of level 0 or P
                brackets = re.findall(r'\([\w,\\*-]+\)', class_name)
                languages = re.sub('[\\(\\)]', '', brackets[len(brackets) - 1]).strip().split('-')
                first = languages[0].split(',')
                second = languages[1].split(',')
                languages = []
                for l in first:
                    lang = Language()
                    lang.name = re.sub('\\*', '', l)
                    lang.nr = 1
                    lang.high_school_class = hss
                    if 'Dwujęzycznymi' in name and st.with_competency_test:
                        lang.is_bilingual = True
                    elif '*' in l:
                        lang.multiple_levels = True
                    languages.append(lang)

                for l in second:
                    lang2 = Language()
                    lang2.name = re.sub('\\*', '', l)
                    lang2.nr = 2
                    lang2.high_school_class = hss
                    if '*' in l:
                        lang2.multiple_levels = True
                    languages.append(lang2)
                for l in languages:
                    l.save()
Beispiel #14
0
    def test_import(self):
        feed = self.content_server_mini_feed

        imported_editions, pools, works, failures = (
            OPDSImporter(self._db).import_from_feed(feed)
        )

        [crow, mouse] = sorted(imported_editions, key=lambda x: x.title)

        # By default, this feed is treated as though it came from the
        # metadata wrangler. No Work has been created.
        eq_(DataSource.METADATA_WRANGLER, crow.data_source.name)
        eq_(None, crow.work)
        eq_(None, crow.license_pool)
        eq_(Edition.BOOK_MEDIUM, crow.medium)

        # not even the 'mouse'
        eq_(None, mouse.work)
        eq_(Edition.PERIODICAL_MEDIUM, mouse.medium)

        popularity, quality, rating = sorted(
            [x for x in mouse.primary_identifier.measurements
             if x.is_most_recent],
            key=lambda x: x.quantity_measured
        )

        eq_(DataSource.METADATA_WRANGLER, popularity.data_source.name)
        eq_(Measurement.POPULARITY, popularity.quantity_measured)
        eq_(0.25, popularity.value)

        eq_(DataSource.METADATA_WRANGLER, quality.data_source.name)
        eq_(Measurement.QUALITY, quality.quantity_measured)
        eq_(0.3333, quality.value)

        eq_(DataSource.METADATA_WRANGLER, rating.data_source.name)
        eq_(Measurement.RATING, rating.quantity_measured)
        eq_(0.6, rating.value)

        seven, children, courtship, fantasy, pz, magic, new_york = sorted(
            mouse.primary_identifier.classifications,
            key=lambda x: x.subject.name)

        pz_s = pz.subject
        eq_("Juvenile Fiction", pz_s.name)
        eq_("PZ", pz_s.identifier)

        new_york_s = new_york.subject
        eq_("New York (N.Y.) -- Fiction", new_york_s.name)
        eq_("sh2008108377", new_york_s.identifier)

        eq_('7', seven.subject.identifier)
        eq_(100, seven.weight)
        eq_(Subject.AGE_RANGE, seven.subject.type)
        from classifier import Classifier
        classifier = Classifier.classifiers.get(seven.subject.type, None)
        classifier.classify(seven.subject)

        # If we import the same file again, we get the same list of Editions.
        imported_editions_2, pools_2, works_2, failures_2 = (
            OPDSImporter(self._db).import_from_feed(feed)
        )
        eq_(imported_editions_2, imported_editions)

        # importing with a lendable data source makes license pools and works
        imported_editions, pools, works, failures = (
            OPDSImporter(self._db, data_source_name=DataSource.OA_CONTENT_SERVER).import_from_feed(feed)
        )

        [crow_pool, mouse_pool] = sorted(
            pools, key=lambda x: x.presentation_edition.title
        )

        # Work was created for both books.
        assert crow_pool.work is not None
        eq_(Edition.BOOK_MEDIUM, crow_pool.presentation_edition.medium)

        assert mouse_pool.work is not None
        eq_(Edition.PERIODICAL_MEDIUM, mouse_pool.presentation_edition.medium)

        work = mouse_pool.work
        work.calculate_presentation()
        eq_(0.4142, round(work.quality, 4))
        eq_(Classifier.AUDIENCE_CHILDREN, work.audience)
        eq_(NumericRange(7,7, '[]'), work.target_age)

        # Bonus: make sure that delivery mechanisms are set appropriately.
        [mech] = mouse_pool.delivery_mechanisms
        eq_(Representation.EPUB_MEDIA_TYPE, mech.delivery_mechanism.content_type)
        eq_(DeliveryMechanism.NO_DRM, mech.delivery_mechanism.drm_scheme)
        eq_('http://www.gutenberg.org/ebooks/10441.epub.images', 
            mech.resource.url)
Beispiel #15
0
 def test_unbounded(self):
     r = NumericRange(None, None, '()')
     instance = RangesModel(floats=r)
     instance.save()
     loaded = RangesModel.objects.get()
     self.assertEqual(r, loaded.floats)
def load(apps, schema_editor):
    School = apps.get_model("search", "School")
    Address = apps.get_model("search", "Address")
    HighSchoolClass = apps.get_model("search", "HighSchoolClass")
    ExtendedSubject = apps.get_model("search", "ExtendedSubject")
    Language = apps.get_model("search", "Language")

    with open("csvs/raport_oddzialy_2021.csv", newline="") as csv_file:
        reader = csv.DictReader(csv_file, CSV_FIELDS)
        next(reader)  # Skip header line
        for row in reader:
            data = {}
            for field in CSV_FIELDS:
                # Build dicts from field path
                field_path = field.split("__")
                current_dict = data
                for key in field_path[:-1]:
                    current_dict = current_dict.setdefault(key, dict())

                current_dict[field_path[-1]] = row[field]

            # School creation
            school_data = data["school"]

            try:
                school = School.objects.get(school_name=school_data["name"])
            except School.DoesNotExist:
                address = Address.objects.filter(**school_data["addr"]).first()
                if not address:
                    address = Address.objects.create(**school_data["addr"])

                is_public = school_data["status"] == PUBLIC_SCHOOL
                school_extra_data = {}
                if not is_public:
                    school_extra_data = {
                        "is_public": school_data["status"],
                    }
                school = School.objects.create(
                    school_name=school_data["name"],
                    school_type=school_data["type"],
                    is_public=is_public,
                    data=school_extra_data,
                    address=address,
                )

            class_info = re.search(CLASS_INFO_REGEX, data["class"]["info"])

            # Class creation
            hsc = HighSchoolClass.objects.create(
                type=class_info.group(1),
                name=data["class"]["name"],
                school=school,
                year=NumericRange(2021, 2023, "[)"),
            )

            # Subjects assignment
            subjects = data["class"]["subjects"].split(",")
            subject_options = {
                name: short
                for short, name in ExtendedSubject._meta.get_field("name").choices
            }
            for subject in subjects:
                subject = subject.strip()
                name = subject_options.get(subject, None)
                if not name:
                    continue
                ExtendedSubject.objects.create(
                    name=name,
                    high_school_class=hsc,
                )

            # Languages assignment
            langs = re.compile(LANGUAGE_REGEX).findall(class_info.group(5))

            for i, lang in enumerate(langs):
                is_multiple_levels = lang.endswith("*")
                is_bilingual = hsc.type == "D" and i == 0
                name = lang.replace("*", "")
                nr = 1 if lang in subjects else 2
                Language.objects.create(
                    high_school_class=hsc,
                    name=name,
                    multiple_levels=is_multiple_levels,
                    is_bilingual=is_bilingual,
                    nr=nr,
                )
    def setup_numeric_range_filter_model(self):
        print('Setup NumericRangeFilterModel')

        NumericRangeFilterModel.objects.create(
            id=-1,
            postgres_int_range=NumericRange(5, 10),
            postgres_decimal_range=NumericRange(5.0, 10.0))
        NumericRangeFilterModel.objects.create(
            id=0,
            postgres_int_range=NumericRange(5, 10),
            postgres_decimal_range=NumericRange(5.0, 10.0))
        NumericRangeFilterModel.objects.create(
            id=1,
            postgres_int_range=NumericRange(5, None),
            postgres_decimal_range=NumericRange(5.0, None))
        NumericRangeFilterModel.objects.create(
            id=2,
            postgres_int_range=NumericRange(None, 10),
            postgres_decimal_range=NumericRange(None, 10.0))
        NumericRangeFilterModel.objects.create(
            id=3,
            postgres_int_range=NumericRange(1, 10),
            postgres_decimal_range=NumericRange(1.0, 10.0))
        NumericRangeFilterModel.objects.create(
            id=4,
            postgres_int_range=NumericRange(5, 20),
            postgres_decimal_range=NumericRange(5.0, 20.0))
        NumericRangeFilterModel.objects.create(
            id=5,
            postgres_int_range=NumericRange(1, 20),
            postgres_decimal_range=NumericRange(1.0, 10.0))
        NumericRangeFilterModel.objects.create(
            id=6,
            postgres_int_range=NumericRange(1, 20),
            postgres_decimal_range=NumericRange(1.0, 10.0))
        NumericRangeFilterModel.objects.create(id=7, postgres_int_range=None)
Beispiel #18
0
 def test_loading(self):
     instance = list(serializers.deserialize('json',
                                             self.test_data))[0].object
     self.assertEqual(instance.ints, NumericRange(0, 10))
     self.assertEqual(instance.floats, NumericRange(empty=True))
     self.assertEqual(instance.bigints, None)
Beispiel #19
0
 def test_exact(self):
     self.assertSequenceEqual(
         RangesModel.objects.filter(ints__exact=NumericRange(0, 10)),
         [self.objs[0]],
     )
Beispiel #20
0
 def test_numericrange_to_tuple(self):
     m = numericrange_to_tuple
     two_to_six_inclusive = NumericRange(2, 6, '[]')
     eq_((2, 6), m(two_to_six_inclusive))
     two_to_six_exclusive = NumericRange(2, 6, '()')
     eq_((3, 5), m(two_to_six_exclusive))
Beispiel #21
0
 def test_contained_by(self):
     self.assertSequenceEqual(
         RangesModel.objects.filter(ints__contained_by=NumericRange(0, 20)),
         [self.objs[0], self.objs[1], self.objs[3]],
     )
Beispiel #22
0
 def test_decimal_open(self):
     field = pg_forms.DecimalRangeField()
     value = field.clean(['', '3.1415926'])
     self.assertEqual(value, NumericRange(None, Decimal('3.1415926')))
Beispiel #23
0
 def test_fully_gt(self):
     self.assertSequenceEqual(
         RangesModel.objects.filter(ints__fully_gt=NumericRange(5, 10)),
         [],
     )
Beispiel #24
0
 def test_valid_floats(self):
     field = pg_forms.FloatRangeField()
     value = field.clean(['1.12345', '2.001'])
     self.assertEqual(value, NumericRange(1.12345, 2.001))
Beispiel #25
0
 def test_adjacent_to(self):
     self.assertSequenceEqual(
         RangesModel.objects.filter(ints__adjacent_to=NumericRange(0, 5)),
         [self.objs[1], self.objs[2]],
     )
Beispiel #26
0
 def test_tuple(self):
     instance = RangesModel(ints=(0, 10))
     instance.save()
     loaded = RangesModel.objects.get()
     self.assertEqual(NumericRange(0, 10), loaded.ints)
Beispiel #27
0
 def test_valid_decimal(self):
     field = pg_forms.DecimalRangeField()
     value = field.clean(['1.12345', '2.001'])
     self.assertEqual(value,
                      NumericRange(Decimal('1.12345'), Decimal('2.001')))
Beispiel #28
0
 def test_float_open(self):
     field = pg_forms.FloatRangeField()
     value = field.clean(['', '3.1415926'])
     self.assertEqual(value, NumericRange(None, 3.1415926))
Beispiel #29
0
 def test_range_object(self):
     r = NumericRange(0, 10)
     instance = RangesModel(ints=r)
     instance.save()
     loaded = RangesModel.objects.get()
     self.assertEqual(r, loaded.ints)
Beispiel #30
0
 def __age_input__(self):
     __input_dictionary = self.__input_dictionary
     __coreid = self.__coreid
     try:
         self.__input_age = __input_dictionary['Age']
         self.__input_age.columns = self.__input_age.iloc[6]
         self.__input_age = self.__input_age.drop(self.__input_age.index[6])
         ## age
         self.__input_age = self.__input_age.iloc[6:, 1:13]
         self.__input_age.rename(columns={
             'MeasurementID':
             'measurementid',
             'Thickness \n(cm)':
             'thickness',
             'Lab-ID':
             'labid',
             'Lab-Location':
             'lab_location',
             'Category':
             'material_category',
             'Material':
             'material_description',
             'Weight \n(µg C)':
             'material_weight',
             'Age \n(yr BP)':
             'age',
             'Age Error \n(+/- yr)':
             'age_error',
             'Pretreatment':
             'pretreatment_dating',
             'Reservoir Age \n(yr)':
             'reservoir_age',
             'Reservoir Error \n(+/- yr)':
             'reservoir_error'
         },
                                 inplace=True)
         ### For detection limit
         self.__input_age.reset_index(drop=True, inplace=True)
         for i in range(0, len(self.__input_age)):
             if type(self.__input_age.iloc[
                     i, 7]) is str and '>' in self.__input_age.iloc[i, 7]:
                 __age_array = self.__input_age.iloc[i, 7].split('>')
                 __age_indi = NumericRange(int(__age_array[1]),
                                           None,
                                           bounds='[)',
                                           empty=False)
                 self.__input_age.iloc[i, 7] = __age_indi
             elif type(self.__input_age.iloc[
                     i, 7]) is str and '<' in self.__input_age.iloc[i, 7]:
                 __age_array = self.__input_age.iloc[i, 7].split('<')
                 __age_indi = NumericRange(None,
                                           int(__age_array[1]),
                                           bounds='()',
                                           empty=False)
                 self.__input_age.iloc[i, 7] = __age_indi
             else:
                 __age_indi = NumericRange(int(self.__input_age.iloc[i, 7]),
                                           int(self.__input_age.iloc[i, 7]),
                                           bounds='[]',
                                           empty=False)
                 self.__input_age.iloc[i, 7] = __age_indi
         ###
     except KeyError:
         raise Exception(
             f'No age data for {__coreid} - need age information to be included in MAYHEM database'
         )