function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
sequence
def test_the_user_update_reminder(self): reminders = self.the_user1.get_web_reminders() self.assertTrue(isinstance(reminders, dict)) self.assertEqual(reminders['vk'], True) self.assertEqual(reminders['app_download'], True) self.the_user1.update_reminder('vk', False) self.the_user1.update_reminder('app_download', False) updated_reminders = self.the_user1.get_web_reminders() self.assertTrue(isinstance(updated_reminders, dict)) self.assertEqual(updated_reminders['vk'], False) self.assertEqual(updated_reminders['app_download'], False)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_removing_user_objects(self): """ Must remove django User instance after 'app.models.TheUser' objects was deleted. """ the_user3 = TheUser.objects.get(id_user__username='user3') the_user4 = TheUser.objects.get(id_user__email='user4@user4.com') the_user3.delete() the_user4.delete() self.assertEqual(User.objects.all().count(), 4) self.assertEqual(User.objects.all().count(), TheUser.objects.all().count())
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_created_categories(self): self.assertEqual(Category.objects.all().count(), 2) self.assertNotEqual(self.category1, self.category2)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_categories_str(self): self.assertEqual(str(self.category1), 'category1') self.assertEqual(str(self.category2), 'category2')
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_created_authors(self): self.assertEqual(Author.objects.all().count(), 5) self.assertNotEqual(self.author1, self.author2)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_get_authors_list(self): """ Must return authors list depending on different letters/letter case/words/symbols. """ self.assertEqual(Author.get_authors_list('bEst'), ['Best Author 1']) self.assertEqual(Author.get_authors_list('1'), ['Best Author 1']) self.assertEqual(Author.get_authors_list(' '), ['Best Author 1', 'zlast author']) self.assertEqual(Author.get_authors_list('new'), ['trueAuthorNew']) self.assertEqual(Author.get_authors_list('TRUE'), ['trueAuthorNew']) self.assertEqual(Author.get_authors_list('Best Author 1'), ['Best Author 1']) self.assertEqual(Author.get_authors_list('trueAuthorNew'), ['trueAuthorNew'])
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_get_authors_list_with_escaping(self): self.assertEqual(Author.get_authors_list("'", True), ['O'Connor']) self.assertEqual(Author.get_authors_list("Connor", True), ['O'Connor']) self.assertEqual( Author.get_authors_list('b', True), ['Best Author 1', '<AuthorSpecialSymbols>&"'] ) self.assertEqual( Author.get_authors_list('e', True), ['Best Author 1', 'trueAuthorNew', '<AuthorSpecialSymbols>&"'] ) self.assertEqual( Author.get_authors_list('author', True), ['Best Author 1', 'trueAuthorNew', 'zlast author', '<AuthorSpecialSymbols>&"'] )
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_get_authors_list_without_escaping(self): self.assertEqual(Author.get_authors_list("'"), ["O'Connor"]) self.assertEqual(Author.get_authors_list("Connor", False), ["O'Connor"]) self.assertEqual(Author.get_authors_list('b'), ['Best Author 1', '<AuthorSpecialSymbols>&"']) self.assertEqual( Author.get_authors_list('e'), ['Best Author 1', 'trueAuthorNew', '<AuthorSpecialSymbols>&"'] ) self.assertEqual( Author.get_authors_list('author', False), ['Best Author 1', 'trueAuthorNew', 'zlast author', '<AuthorSpecialSymbols>&"'] )
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_created_language(self): self.assertEqual(Language.objects.all().count(), 2) self.assertNotEqual(self.author1, self.author2)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_created_books(self): books = Book.objects.all() self.assertEqual(books.count(), 7) self.assertEqual(books.filter(private_book=True).count(), 2) self.assertEqual(books.filter(id_category=self.category1).count(), 4) self.assertEqual(books.filter(id_author=self.author1).count(), 3) self.assertEqual(books.filter(language=self.language_en).count(), 4) self.assertEqual(books.filter(photo=False).count(), 2) self.assertEqual(books.filter(who_added=self.the_user1).count(), 3) self.assertEqual(books.filter(id_category=self.category2, id_author=self.author2).count(), 1) self.assertEqual(books.filter(id_category=self.category1, id_author=self.author2, language=self.language_ru, who_added=self.the_user1).count(), 1) self.assertEqual(books.filter(id_category=self.category1, id_author=self.author2, language=self.language_ru, who_added=self.the_user2).count(), 0) self.assertEqual(books.filter(blocked_book=True).count(), 3)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_get_related_objects_for_create(self): test_book_path = os.path.join(TEST_DATA_DIR, 'test_book.pdf') form_data = { 'bookname': 'The new book', 'author': 'trueAuthorNew', 'category': 'category1', 'language': 'English', 'about': 'about book', 'bookfile': SimpleUploadedFile('test_book.pdf', open(test_book_path, 'rb').read()), } form_data_new_author = copy.deepcopy(form_data) form_data_new_author['author'] = 'super new author' self.assertEqual(Author.objects.all().count(), 5) form = AddBookForm(data=form_data) form.is_valid() form_with_new_author = AddBookForm(data=form_data_new_author) form_with_new_author.is_valid() related_data = Book.get_related_objects_for_create(self.user1.id, form) self.assertTrue(isinstance(related_data, BookRelatedData)) self.assertEqual(len(related_data), 4) self.assertEqual(related_data.author, Author.objects.get(author_name='trueAuthorNew')) self.assertEqual(Author.objects.all().count(), 5) related_data_new_author = Book.get_related_objects_for_create(self.user1.id, form_with_new_author) self.assertTrue(isinstance(related_data, BookRelatedData)) self.assertEqual(len(related_data_new_author), 4) self.assertEqual(related_data_new_author.author, Author.objects.get(author_name='super new author')) self.assertEqual(Author.objects.all().count(), 6)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_get_related_objects_create_api(self): """ Must generate Book related data when creates a Book object for API calls. New author must be returned if it's name not present in the Author model. """ test_data = {'author': 'trueAuthorNew', 'category': 'category2', 'language': 'Russian'} test_data_new_author = {'author': 'NEW AUTHOR', 'category': 'category1', 'language': 'English'} self.assertEqual( Book.get_related_objects_create_api(self.the_user1, test_data), BookRelatedData(self.author2, self.category2, self.language_ru, None) ) self.assertEqual(Author.objects.all().count(), 5) self.assertEqual( Book.get_related_objects_create_api(self.the_user1, test_data_new_author), BookRelatedData(Author.objects.get(author_name='NEW AUTHOR'), self.category1, self.language_en, None) ) self.assertEqual(Author.objects.all().count(), 6)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_get_related_objects_selected_book_unknown_user(self): """ Must generate selected book related data for unknown (anonymous) users. """ third_book = Book.objects.get(book_name='Third Book') sixth_book = Book.objects.get(book_name='Sixth Book') self.assertTrue(isinstance(Book.get_related_objects_selected_book(self.anonymous_user, third_book.id), dict)) related_third_book = Book.get_related_objects_selected_book(self.anonymous_user, third_book.id) related_sixth_book = Book.get_related_objects_selected_book(self.anonymous_user, sixth_book.id) self.assertEqual(related_third_book['book'], third_book) self.assertEqual(related_third_book['avg_book_rating'], {'rating__avg': 6.0}) self.assertEqual(related_third_book['book_rating_count'], 3) self.assertEqual(related_third_book['added_book'], None) self.assertEqual(related_third_book['comments'].count(), 1) self.assertEqual(related_third_book['comments'][0], BookComment.objects.filter(id_book=third_book).order_by('-id')[0]) self.assertEqual(related_sixth_book['book'], sixth_book) self.assertEqual(related_sixth_book['avg_book_rating'], {'rating__avg': 4.0}) self.assertEqual(related_sixth_book['book_rating_count'], 1) self.assertEqual(related_sixth_book['added_book'], None) self.assertEqual(related_sixth_book['comments'].count(), 0) AddedBook.objects.create(id_user=self.the_user5, id_book=third_book) BookRating.objects.create(id_user=self.the_user6, id_book=third_book, rating=10) BookComment.objects.create(id_user=self.the_user6, id_book=third_book, text='TEST TEXT 2') related_third_book = Book.get_related_objects_selected_book(self.anonymous_user, third_book.id) self.assertEqual(related_third_book['book'], third_book) self.assertEqual(related_third_book['avg_book_rating'], {'rating__avg': 7.0}) self.assertEqual(related_third_book['book_rating_count'], 4) self.assertEqual(related_third_book['added_book'], None) self.assertEqual(related_third_book['comments'].count(), 2)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_get_related_objects_selected_book_added_user(self): """ This case is testing only 'added_book' param, because for user who is reading the book only this attribute will change relatively to function above. """ third_book = Book.objects.get(book_name='Third Book') sixth_book = Book.objects.get(book_name='Sixth Book') self.assertTrue(isinstance(Book.get_related_objects_selected_book(self.the_user1.id_user, third_book.id), dict)) related_third_book = Book.get_related_objects_selected_book(self.the_user1.id_user, third_book.id) related_sixth_book = Book.get_related_objects_selected_book(self.the_user1.id_user, sixth_book.id) self.assertEqual(related_third_book['added_book'], AddedBook.objects.get(id_book=third_book, id_user=self.the_user1)) self.assertEqual(related_sixth_book['added_book'], AddedBook.objects.get(id_book=sixth_book, id_user=self.the_user1))
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_get_related_objects_selected_book_with_user_key(self): """ Tests returning data for related objects for selected book with 'user_key' attribute, meaning that user is anonymous (i.e. not logged) but with using user key. Done for API requests access. """ third_book = Book.objects.get(book_name='Third Book') related_third_book = Book.get_related_objects_selected_book( self.anonymous_user, third_book.id, self.the_user1.auth_token ) self.assertEqual(related_third_book['book'], third_book) self.assertEqual(related_third_book['avg_book_rating'], {'rating__avg': 6.0}) self.assertEqual(related_third_book['book_rating_count'], 3) self.assertEqual(related_third_book['added_book'], AddedBook.objects.get(id_book=third_book, id_user=self.the_user1)) self.assertEqual(related_third_book['comments'].count(), 1) self.assertEqual(related_third_book['comments'][0], BookComment.objects.filter(id_book=third_book).order_by('-id')[0])
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_sort_by_book_name_category1(self): """ Must generate correct dictionaries for anonymous users, users with private books and without. Testing first category. """ first_book = Book.objects.get(book_name='First Book') third_book = Book.objects.get(book_name='Third Book') fourth_book = Book.objects.get(book_name='Fourth Book') first_book_dict = Utils.generate_sort_dict(first_book) third_book_dict = Utils.generate_sort_dict(third_book) fourth_book_dict = Utils.generate_sort_dict(fourth_book) self.assertTrue(isinstance(Book.sort_by_book_name(self.anonymous_user, self.category1), list)) self.assertEqual(len(Book.sort_by_book_name(self.anonymous_user, self.category1)), 3) self.assertEqual(Book.sort_by_book_name(self.anonymous_user, self.category1)[0], fourth_book_dict) self.assertEqual(Book.sort_by_book_name(self.anonymous_user, self.category1)[2], third_book_dict) self.assertEqual(len(Book.sort_by_book_name(self.the_user2.id_user, self.category1)), 3) self.assertEqual(Book.sort_by_book_name(self.the_user2.id_user, self.category1)[0], fourth_book_dict) self.assertEqual(Book.sort_by_book_name(self.the_user2.id_user, self.category1)[2], third_book_dict) self.assertEqual(len(Book.sort_by_book_name(self.the_user1.id_user, self.category1)), 4) self.assertEqual(Book.sort_by_book_name(self.the_user1.id_user, self.category1)[0], first_book_dict) self.assertEqual(Book.sort_by_book_name(self.the_user1.id_user, self.category1)[3], third_book_dict)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_sort_by_book_name_category2(self): """ Must generate correct dictionaries for anonymous users, users with private books and without. Testing first category. """ fifth_book = Book.objects.get(book_name='Fifth Book') seventh_book = Book.objects.get(book_name='Seventh Book<>&"') fifth_book_dict = Utils.generate_sort_dict(fifth_book) seventh_book_dict = Utils.generate_sort_dict(seventh_book) self.assertEqual(len(Book.sort_by_book_name(self.anonymous_user, self.category2)), 2) self.assertEqual(Book.sort_by_book_name(self.anonymous_user, self.category2)[0], seventh_book_dict) self.assertEqual(len(Book.sort_by_book_name(self.the_user2.id_user, self.category2)), 2) self.assertEqual(Book.sort_by_book_name(self.the_user2.id_user, self.category2)[0], seventh_book_dict) self.assertEqual(len(Book.sort_by_book_name(self.the_user1.id_user, self.category2)), 3) self.assertEqual(Book.sort_by_book_name(self.the_user1.id_user, self.category2)[0], fifth_book_dict) self.assertEqual(Book.sort_by_book_name(self.the_user1.id_user, self.category2)[1], seventh_book_dict)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_sort_by_author_category1(self): """ Must generate correct dictionaries for anonymous users, users with private books and without. Testing returned book authors at first category. """ self.assertTrue(isinstance(Book.sort_by_author(self.anonymous_user, self.category1), list)) self.assertEqual(len(Book.sort_by_author(self.anonymous_user, self.category1)), 3) self.assertEqual(Book.sort_by_author(self.anonymous_user, self.category1)[0]['author'], self.author1.author_name) self.assertEqual(Book.sort_by_author(self.anonymous_user, self.category1)[2]['author'], self.author2.author_name) self.assertEqual(len(Book.sort_by_author(self.the_user2.id_user, self.category1)), 3) self.assertEqual(Book.sort_by_author(self.the_user2.id_user, self.category1)[0]['author'], self.author1.author_name) self.assertEqual(Book.sort_by_author(self.the_user2.id_user, self.category1)[2]['author'], self.author2.author_name) self.assertEqual(len(Book.sort_by_author(self.the_user1.id_user, self.category1)), 4) self.assertEqual(Book.sort_by_author(self.the_user1.id_user, self.category1)[0]['author'], self.author1.author_name) self.assertEqual(Book.sort_by_author(self.the_user1.id_user, self.category1)[3]['author'], self.author2.author_name)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_sort_by_author_category2(self): """ Must generate correct dictionaries for anonymous users, users with private books and without. Testing returned book authors at second category. """ escaped_author_name = '&lt;AuthorSpecialSymbols&gt;&amp;&quot;' self.assertEqual(len(Book.sort_by_author(self.anonymous_user, self.category2)), 2) self.assertEqual(Book.sort_by_author(self.anonymous_user, self.category2)[0]['author'], escaped_author_name) self.assertEqual(len(Book.sort_by_author(self.the_user2.id_user, self.category2)), 2) self.assertEqual(Book.sort_by_author(self.the_user2.id_user, self.category2)[0]['author'], escaped_author_name) self.assertEqual(len(Book.sort_by_author(self.the_user1.id_user, self.category2)), 3) self.assertEqual(Book.sort_by_author(self.the_user1.id_user, self.category2)[0]['author'], escaped_author_name) self.assertEqual(Book.sort_by_author(self.the_user1.id_user, self.category2)[1]['author'], self.author1.author_name)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_sort_by_estimation_category1(self): """ Must generate correct dictionaries for anonymous users, users with private books and without. Testing returned book rating at first category. """ self.assertTrue(isinstance(Book.sort_by_estimation(self.anonymous_user, self.category1), list)) self.assertEqual(len(Book.sort_by_estimation(self.anonymous_user, self.category1)), 3) self.assertEqual(Book.sort_by_estimation(self.anonymous_user, self.category1)[0]['rating'], 7) self.assertEqual(Book.sort_by_estimation(self.anonymous_user, self.category1)[2]['rating'], 6) self.assertEqual(len(Book.sort_by_estimation(self.the_user2.id_user, self.category1)), 3) self.assertEqual(Book.sort_by_estimation(self.the_user2.id_user, self.category1)[0]['rating'], 7) self.assertEqual(Book.sort_by_estimation(self.the_user2.id_user, self.category1)[2]['rating'], 6) self.assertEqual(len(Book.sort_by_estimation(self.the_user1.id_user, self.category1)), 4) self.assertEqual(Book.sort_by_estimation(self.the_user1.id_user, self.category1)[0]['rating'], 7) self.assertEqual(Book.sort_by_estimation(self.the_user1.id_user, self.category1)[2]['rating'], 6)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_sort_by_estimation_category2(self): """ Must generate correct dictionaries for anonymous users, users with private books and without. Testing returned book rating at second category. """ self.assertEqual(len(Book.sort_by_estimation(self.anonymous_user, self.category2)), 2) self.assertEqual(Book.sort_by_estimation(self.anonymous_user, self.category2)[0]['rating'], 4) self.assertEqual(len(Book.sort_by_estimation(self.the_user2.id_user, self.category2)), 2) self.assertEqual(Book.sort_by_estimation(self.the_user2.id_user, self.category2)[0]['rating'], 4) self.assertEqual(len(Book.sort_by_estimation(self.the_user1.id_user, self.category2)), 3) self.assertEqual(Book.sort_by_estimation(self.the_user1.id_user, self.category2)[0]['rating'], 4) self.assertEqual(Book.sort_by_estimation(self.the_user1.id_user, self.category2)[1]['rating'], None)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_sort_by_readable(self): """ Must generate correct data by most readable books for anonymous users and users with private books. Testing count of sorted books with and without selected categories. """ sorted_structure = Book.sort_by_readable(self.anonymous_user, self.category1) self.assertTrue(isinstance(sorted_structure, list)) self.assertTrue(isinstance(sorted_structure[0], dict)) self.assertEqual(set(sorted_structure[0].keys()), {'id', 'name', 'author', 'url'}) self.assertEqual(len(Book.sort_by_readable(user=self.anonymous_user, category=self.category1)), 3) self.assertEqual(len(Book.sort_by_readable(user=self.anonymous_user, category=self.category1, count=2)), 2) self.assertEqual(len(Book.sort_by_readable(user=self.the_user1.id_user, category=self.category1)), 3) self.assertEqual(len(Book.sort_by_readable(user=self.the_user1.id_user, category=self.category1, count=2)), 2) self.assertEqual(len(Book.sort_by_readable(user=self.the_user2.id_user, category=self.category1)), 3) self.assertEqual(len(Book.sort_by_readable(user=self.the_user2.id_user, category=self.category1, count=2)), 2) self.assertEqual(len(Book.sort_by_readable(user=self.anonymous_user)), 4) self.assertEqual(len(Book.sort_by_readable(user=self.anonymous_user, count=2)), 2) self.assertEqual(len(Book.sort_by_readable(user=self.the_user1.id_user)), 4) self.assertEqual(len(Book.sort_by_readable(user=self.the_user1.id_user, count=3)), 3) self.assertEqual(len(Book.sort_by_readable(user=self.the_user2.id_user)), 4) self.assertEqual(len(Book.sort_by_readable(user=self.the_user2.id_user, count=2)), 2)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_generate_books(self): """ Must generate correct dictionaries for Book data. """ books = Book.objects.all() self.assertTrue(isinstance(Book.generate_books(books), list)) self.assertEqual(len(Book.generate_books(books)), 7) self.assertEqual(len(Book.generate_books(books)[0].keys()), 5) self.assertEqual(Book.generate_books(books)[0], Utils.generate_sort_dict(books[0])) self.assertEqual(Book.generate_books(books)[6], Utils.generate_sort_dict(books[6]))
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_fetch_books(self): """ Must generate list of dicts with Books data depending on different criteria. """ self.assertTrue(isinstance(Book.fetch_books('book'), list)) self.assertEqual(len(Book.fetch_books('Second Book')), 1) self.assertEqual(len(Book.fetch_books('book')), 7) self.assertEqual(len(Book.fetch_books('ook')), 7) self.assertEqual(len(Book.fetch_books('trueAuthorNew')), 3) self.assertEqual(len(Book.fetch_books('author')), 7) self.assertEqual(len(Book.fetch_books('new')), 3) self.assertEqual(len(Book.fetch_books('True')), 3)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_generate_existing_books(self): """ Must generate list of dicts with Books data depending on different criteria and excluding private books. """ self.assertTrue(isinstance(Book.generate_existing_books('book'), list)) self.assertEqual(len(Book.generate_existing_books('book')), 5) self.assertEqual(len(Book.generate_existing_books('Book')), 5) self.assertEqual(len(Book.generate_existing_books('bOoK')), 5) fourth_book = Book.objects.get(book_name='Fourth Book') test_book = Book.generate_existing_books('fourth') self.assertEqual(len(test_book), 1) self.assertTrue(isinstance(test_book[0], dict)) self.assertEqual(test_book[0], {'url': reverse('book', args=[fourth_book.id]), 'name': fourth_book.book_name}) test_private_book = Book.generate_existing_books('fifth') self.assertEqual(len(test_private_book), 0)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_exclude_private_books(self): """ Must generate query sets or lists with Books depending on user type. """ all_books = Book.objects.all() list_all_books = list(all_books) self.assertEqual(Book.exclude_private_books(self.the_user1.id_user, all_books).count(), 7) self.assertEqual(Book.exclude_private_books(self.the_user2.id_user, all_books).count(), 5) self.assertTrue(isinstance(Book.exclude_private_books(self.the_user1.id_user, all_books), QuerySet)) self.assertTrue(isinstance(Book.exclude_private_books(self.the_user2.id_user, all_books), QuerySet)) self.assertEqual(len(Book.exclude_private_books(self.the_user1.id_user, list_all_books)), 7) self.assertEqual(len(Book.exclude_private_books(self.the_user2.id_user, list_all_books)), 5) self.assertTrue(isinstance(Book.exclude_private_books(self.the_user1.id_user, list_all_books), list)) self.assertTrue(isinstance(Book.exclude_private_books(self.the_user2.id_user, list_all_books), list)) self.assertTrue(self.anonymous_user.is_anonymous) self.assertEqual(Book.exclude_private_books(self.anonymous_user, all_books).count(), 5) self.assertEqual(len(Book.exclude_private_books(self.anonymous_user, list_all_books)), 5) self.assertTrue(isinstance(Book.exclude_private_books(self.anonymous_user, all_books), QuerySet)) self.assertTrue(isinstance(Book.exclude_private_books(self.anonymous_user, list_all_books), list))
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_added_books(self): self.assertEqual(AddedBook.objects.all().count(), 8) self.assertEqual(AddedBook.objects.filter(id_user=self.the_user1).count(), 3) self.assertEqual(AddedBook.objects.filter(id_user=self.the_user2).count(), 3) self.assertEqual(AddedBook.objects.filter(id_user=self.the_user5).count(), 1) self.assertEqual(AddedBook.objects.filter(id_user=self.the_user6).count(), 1) self.assertEqual(AddedBook.objects.filter(id_book=Book.objects.get(book_name='Sixth Book')).count(), 4) self.assertEqual(AddedBook.objects.filter(id_book=Book.objects.get(book_name='Third Book')).count(), 2) self.assertEqual(AddedBook.objects.filter(id_book=Book.objects.get(book_name='Fifth Book')).count(), 0) self.assertEqual(AddedBook.objects.filter(id_user=self.the_user1, id_book=Book.objects.get(book_name='Third Book')).count(), 1) self.assertEqual(AddedBook.objects.filter(id_user=self.the_user1, id_book=Book.objects.get(book_name='Sixth Book')).count(), 1) self.assertEqual(AddedBook.objects.filter(id_user=self.the_user2, id_book=Book.objects.get(book_name='Sixth Book')).count(), 1) self.assertEqual(AddedBook.objects.filter(id_user=self.the_user2, id_book=Book.objects.get(book_name='Fourth Book')).count(), 0)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_added_books_change(self): """ Must save book page after changing it. """ added_book3 = AddedBook.objects.get(id_user=self.the_user1, id_book=Book.objects.get(book_name='Third Book')) added_book6 = AddedBook.objects.get(id_user=self.the_user2, id_book=Book.objects.get(book_name='Sixth Book')) self.assertEqual(added_book3.last_page, 1) self.assertEqual(added_book6.last_page, 1) added_book3.last_page = 500 added_book3.save() self.assertEqual(added_book3.last_page, 500) self.assertEqual(added_book6.last_page, 1) added_book6.last_page = 256 added_book6.save() self.assertEqual(added_book3.last_page, 500) self.assertEqual(added_book6.last_page, 256)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_added_books_delete(self): added_book_third = AddedBook.objects.get(id_user=self.the_user1, id_book=Book.objects.get(book_name='Third Book')) added_book_sixth = AddedBook.objects.get(id_user=self.the_user2, id_book=Book.objects.get(book_name='Sixth Book')) added_book_third.delete() added_book_sixth.delete() self.assertEqual(AddedBook.objects.all().count(), 6) self.assertEqual(AddedBook.objects.filter(id_user=self.the_user1).count(), 2) self.assertEqual(AddedBook.objects.filter(id_user=self.the_user1).count(), 2) self.assertEqual(AddedBook.objects.filter(id_book=Book.objects.get(book_name='Sixth Book')).count(), 3) self.assertEqual(AddedBook.objects.filter(id_book=Book.objects.get(book_name='Third Book')).count(), 1) self.assertEqual(AddedBook.objects.filter(id_user=self.the_user1, id_book=Book.objects.get(book_name='Third Book')).count(), 0) self.assertEqual(AddedBook.objects.filter(id_user=self.the_user2, id_book=Book.objects.get(book_name='Sixth Book')).count(), 0)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_get_user_added_book(self): """ Must generate list of books that added by user (reading by user). """ self.assertTrue(self.anonymous_user.is_anonymous) self.assertEqual(len(AddedBook.get_user_added_books(self.anonymous_user)), 0) self.assertEqual(AddedBook.get_user_added_books(self.anonymous_user), []) self.assertEqual(AddedBook.get_user_added_books(self.the_user1.id_user).count(), 3) self.assertEqual(AddedBook.get_user_added_books(self.the_user5.id_user).count(), 1) self.assertNotEqual(AddedBook.get_user_added_books(self.the_user1.id_user), []) removed_obj = AddedBook.objects.get(id_book=Book.objects.get(book_name='Sixth Book'), id_user=self.the_user5) removed_obj.delete() self.assertEqual(AddedBook.get_user_added_books(self.the_user5.id_user).count(), 0) self.assertNotEqual(AddedBook.get_user_added_books(self.the_user5.id_user), [])
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_get_count_added(self): """ Must return count how many users is reading some book. """ third_book = Book.objects.get(book_name='Third Book') sixth_book = Book.objects.get(book_name='Sixth Book') not_existing_id = 10000 self.assertEqual(AddedBook.get_count_added(third_book.id), 2) self.assertEqual(AddedBook.get_count_added(sixth_book.id), 4) self.assertEqual(AddedBook.get_count_added(not_existing_id), 0) removed_third = AddedBook.objects.filter(id_user=self.the_user1, id_book=third_book) removed_third.delete() removed_sixth = AddedBook.objects.filter(id_user=self.the_user1, id_book=sixth_book) removed_sixth.delete() self.assertEqual(AddedBook.get_count_added(third_book.id), 1) self.assertEqual(AddedBook.get_count_added(sixth_book.id), 3) self.assertEqual(AddedBook.get_count_added(not_existing_id), 0)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_book_rating(self): self.assertEqual(BookRating.objects.all().count(), 6) self.assertEqual(BookRating.objects.filter(id_book=Book.objects.filter(book_name='Third Book')).count(), 3) self.assertEqual(BookRating.objects.filter(id_user=self.the_user1).count(), 3) self.assertEqual(BookRating.objects.filter(id_user=self.the_user2).count(), 2) self.assertEqual(BookRating.objects.filter(rating=7).count(), 2) self.assertEqual(BookRating.objects.filter(id_book=Book.objects.get(book_name='Third Book'), id_user=self.the_user1).count(), 1) self.assertEqual(BookRating.objects.filter(id_book=Book.objects.get(book_name='Third Book'), id_user=self.the_user6).count(), 0) self.assertEqual(BookRating.objects.filter(id_book=Book.objects.get(book_name='Fourth Book'), id_user=self.the_user1, rating=7).count(), 1)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_changed_book_rating(self): removed_rating = BookRating.objects.get(id_book=Book.objects.get(book_name='Third Book'), id_user=self.the_user1) removed_rating.delete() self.assertEqual(BookRating.objects.all().count(), 5) changed_rating1 = BookRating.objects.get(id_book=Book.objects.get(book_name='Second Book'), id_user=self.the_user2) changed_rating2 = BookRating.objects.get(id_book=Book.objects.get(book_name='Fourth Book'), id_user=self.the_user1) self.assertEqual(BookRating.objects.filter(rating=7).count(), 2) self.assertEqual(changed_rating1.rating, 7) self.assertEqual(changed_rating2.rating, 7) changed_rating1.rating = 4 changed_rating1.save() changed_rating2.rating = 3 changed_rating2.save() self.assertEqual(changed_rating1.rating, 4) self.assertEqual(changed_rating2.rating, 3) self.assertEqual(BookRating.objects.filter(rating=7).count(), 0) self.assertEqual(BookRating.objects.filter(rating=4).count(), 2) self.assertEqual(BookRating.objects.filter(rating=3).count(), 2)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_book_comment(self): self.assertEqual(BookComment.objects.all().count(), 5) self.assertEqual(BookComment.objects.filter(id_user=self.the_user1).count(), 3) self.assertEqual(BookComment.objects.filter(id_book=Book.objects.get(book_name='Second Book')).count(), 2) self.assertEqual(BookComment.objects.filter(id_book=Book.objects.get(book_name='Fourth Book')).count(), 2) self.assertEqual(BookComment.objects.filter(id_book=Book.objects.get(book_name='Sixth Book')).count(), 0) self.assertEqual(BookComment.objects.filter(id_user=self.the_user6).count(), 0) self.assertEqual(BookComment.objects.filter(id_book=Book.objects.get(book_name='Second Book'), id_user=self.the_user1).count(), 1) BookComment.objects.create(id_book=Book.objects.get(book_name='Second Book'), id_user=self.the_user1, text='New comment user1 book 2') self.assertEqual(BookComment.objects.all().count(), 6) self.assertEqual(BookComment.objects.filter(id_user=self.the_user1).count(), 4) self.assertEqual(BookComment.objects.filter(id_book=Book.objects.get(book_name='Second Book')).count(), 3) self.assertEqual(BookComment.objects.filter(id_book=Book.objects.get(book_name='Second Book'), id_user=self.the_user1).count(), 2) deleted_comment = BookComment.objects.get(id_book=Book.objects.get(book_name='Fourth Book'), id_user=self.the_user5) deleted_comment.delete() self.assertEqual(BookComment.objects.all().count(), 5) self.assertEqual(BookComment.objects.filter(id_user=self.the_user5).count(), 0) self.assertEqual(BookComment.objects.filter(id_book=Book.objects.get(book_name='Fourth Book')).count(), 1)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_post_messages(self): self.assertEqual(Post.objects.all().count(), 3) self.assertEqual(Post.objects.filter(user=self.the_user1).count(), 2) self.assertEqual(Post.objects.filter(user=self.the_user2).count(), 1) deleted_post = Post.objects.get(user=self.the_user1, heading='post 2') deleted_post.delete() self.assertEqual(Post.objects.all().count(), 2) self.assertEqual(Post.objects.filter(user=self.the_user1).count(), 1) self.assertEqual(Post.objects.filter(user=self.the_user2).count(), 1)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_support_messages(self): self.assertEqual(SupportMessage.objects.all().count(), 4) self.assertEqual(SupportMessage.objects.filter(email='testemail1@mail.co').count(), 2) self.assertEqual(SupportMessage.objects.filter(email='test_email22@mail.co').count(), 1) self.assertEqual(SupportMessage.objects.filter(is_checked=False).count(), 4) checked_message = SupportMessage.objects.get(email='testemail1@mail.co', text='Test text1') checked_message.is_checked = True checked_message.save() self.assertEqual(SupportMessage.objects.filter(is_checked=False).count(), 3)
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def main(): module = AnsibleModule( argument_spec = dict( hostname = dict(required=True), username = dict(required=True), password = dict(required=True, no_log=True), settings = dict(required=False, type='dict'), parameter = dict( required = True, choices = ['ntp_client', 'clock', 'identity', 'logging', 'routerboard_settings'], type = 'str' ), state = dict( required = False, choices = ['present', 'absent'], type = 'str' ), ), supports_check_mode=True ) params = module.params if params['parameter'] == 'routerboard_settings': params['parameter'] = 'routerboard/settings' if params['parameter'] == 'ntp_client': params['parameter'] = 'ntp/client' clean_params(params['settings']) mt_obj = MikrotikIdempotent( hostname = params['hostname'], username = params['username'], password = params['password'], state = params['state'], desired_params = params['settings'], idempotent_param= None, api_path = '/system/' + params['parameter'], check_mode = module.check_mode ) mt_obj.sync_state() if mt_obj.failed: module.fail_json( msg = mt_obj.failed_msg ) elif mt_obj.changed: module.exit_json( failed=False, changed=True, msg=mt_obj.changed_msg, diff={ "prepared": { "old": mt_obj.old_params, "new": mt_obj.new_params, }}, ) else: module.exit_json( failed=False, changed=False, #msg='', msg=params['settings'], )
zahodi/ansible-mikrotik
[ 93, 34, 93, 17, 1484089137 ]
def connect(implicit_execution=False): config = dict(hf.config.items("database")) hf.database.engine = engine_from_config(config, prefix="") if implicit_execution: metadata.bind = hf.database.engine
HappyFaceMonitoring/HappyFace
[ 2, 6, 2, 1, 1405423472 ]
def __init__(self, nclass: int, model: Callable, **kwargs): super().__init__(nclass, kwargs) self.model: objax.Module = model(colors=3, nclass=nclass, **kwargs) self.model_ema = objax.optimizer.ExponentialMovingAverageModule(self.model, momentum=0.999) if FLAGS.arch.endswith('pretrain'): # Initialize weights of EMA with pretrained model's weights. self.model_ema.ema.momentum = 0 self.model_ema.update_ema() self.model_ema.ema.momentum = 0.999 self.stats = objax.Module() self.stats.keygen = objax.random.DEFAULT_GENERATOR self.stats.p_labeled = objax.nn.ExponentialMovingAverage((nclass,), init_value=1 / nclass) self.stats.p_unlabeled = objax.nn.MovingAverage((nclass,), buffer_size=128, init_value=1 / nclass) train_vars = self.model.vars() + self.stats.vars() self.opt = objax.optimizer.Momentum(train_vars) self.lr = ScheduleCos(self.params.lr, self.params.lr_decay) @objax.Function.with_vars(self.model_ema.vars()) def eval_op(x: JaxArray, domain: int) -> JaxArray: return objax.functional.softmax(self.model_ema(x, training=False, domain=domain)) def loss_function(sx, sy, tu): c, h, w = sx.shape[-3:] xu = jn.concatenate((sx, tu)).reshape((-1, c, h, w)) logit = self.model(xu, training=True) logit_sx = jn.split(logit, (2 * sx.shape[0],))[0] logit_sx_weak, logit_sx_strong = logit_sx[::2], logit_sx[1::2] xe = 0.5 * (objax.functional.loss.cross_entropy_logits(logit_sx_weak, sy).mean() + objax.functional.loss.cross_entropy_logits(logit_sx_strong, sy).mean()) wd = 0.5 * sum((v.value ** 2).sum() for k, v in train_vars.items() if k.endswith('.w')) loss = xe + self.params.wd * wd return loss, {'losses/xe': xe, 'losses/wd': wd} gv = objax.GradValues(loss_function, train_vars) @objax.Function.with_vars(self.vars()) def train_op(step, sx, sy, tx, ty, tu, probe=None): y_probe = eval_op(probe, 1) if probe is not None else None p = step / (FLAGS.train_mimg << 20) lr = self.lr(p) g, v = gv(jn.concatenate((sx, tx)), jn.concatenate((sy, ty)), tu) self.opt(lr, objax.functional.parallel.pmean(g)) self.model_ema.update_ema() return objax.functional.parallel.pmean({'monitors/lr': lr, **v[1]}), y_probe self.train_op = MyParallel(train_op, reduce=lambda x: x) self.eval_op = MyParallel(eval_op, static_argnums=(1,))
google-research/adamatch
[ 52, 5, 52, 5, 1626812263 ]
def __init__(self, **kwargs): self.live_trials = {} self.counter = {"result": 0, "complete": 0} self.final_results = [] self.stall = False self.results = [] super(_MockSearcher, self).__init__(**kwargs)
ray-project/ray
[ 24488, 4264, 24488, 2914, 1477424310 ]
def on_trial_result(self, trial_id: str, result: Dict): self.counter["result"] += 1 self.results += [result]
ray-project/ray
[ 24488, 4264, 24488, 2914, 1477424310 ]
def _process_result(self, result: Dict): self.final_results += [result]
ray-project/ray
[ 24488, 4264, 24488, 2914, 1477424310 ]
def __init__(self, max_concurrent: Optional[int] = None, **kwargs): self.searcher = _MockSearcher(**kwargs) if max_concurrent: self.searcher = ConcurrencyLimiter( self.searcher, max_concurrent=max_concurrent ) super(_MockSuggestionAlgorithm, self).__init__(self.searcher)
ray-project/ray
[ 24488, 4264, 24488, 2914, 1477424310 ]
def live_trials(self) -> List[Trial]: return self.searcher.live_trials
ray-project/ray
[ 24488, 4264, 24488, 2914, 1477424310 ]
def woof(self): print("Woof", self)
sparkslabs/guild
[ 24, 5, 24, 1, 1348350458 ]
def process(self): #print(" ", end="") pass
sparkslabs/guild
[ 24, 5, 24, 1, 1348350458 ]
def produce(self): pass
sparkslabs/guild
[ 24, 5, 24, 1, 1348350458 ]
def __init__(self): self.count = 0 super(Dog, self).__init__()
sparkslabs/guild
[ 24, 5, 24, 1, 1348350458 ]
def process(self): self.count += 1 print("I don't go meow", self.count) if self.count >= 20: self.stop() return False
sparkslabs/guild
[ 24, 5, 24, 1, 1348350458 ]
def test_properties(self): ocm = 'ocn460678076' vol = 'V.1' noid = '1234' volume = SolrVolume(label='%s_%s' % (ocm, vol), pid='testpid:%s' % noid) self.assertEqual(ocm, volume.control_key) self.assertEqual(vol, volume.volume) self.assertEqual(noid, volume.noid) # don't display volume zero vol = 'V.0' volume.data['label'] = '%s_%s' % (ocm, vol) self.assertEqual('', volume.volume) # should also work without volume info volume.data['label'] = ocm self.assertEqual(ocm, volume.control_key) self.assertEqual('', volume.volume)
emory-libraries/readux
[ 27, 13, 27, 13, 1400170870 ]
def test_voyant_url(self): # Volume with English Lang volume1 = SolrVolume(label='ocn460678076_V.1', pid='testpid:1234', language='eng') url = volume1.voyant_url() self.assert_(urlencode({'corpus': volume1.pid}) in url, 'voyant url should include volume pid as corpus identifier') self.assert_(urlencode({'archive': volume1.fulltext_absolute_url()}) in url, 'voyant url should include volume fulltext url as archive') self.assert_(urlencode({'stopList': 'stop.en.taporware.txt'}) in url, 'voyant url should not include english stopword list when volume is in english') # volume language is French volume2 = SolrVolume(label='ocn460678076_V.1', pid='testpid:1235', language='fra') url_fra = volume2.voyant_url() self.assert_(urlencode({'stopList': 'stop.en.taporware.txt'}) not in url_fra, 'voyant url should not include english stopword list when language is not english')
emory-libraries/readux
[ 27, 13, 27, 13, 1400170870 ]
def test_annotations(self): # find annotations associated with a volume, optionally filtered # by user User = get_user_model() testuser = User.objects.create(username='tester') testadmin = User.objects.create(username='super', is_superuser=True) mockapi = Mock() vol = Volume(mockapi, 'vol:1') # create annotations to test finding p1 = Annotation.objects.create(user=testuser, text='testuser p1', uri=reverse('books:page', kwargs={'vol_pid': vol.pid, 'pid': 'p:1'}), volume_uri=vol.absolute_url) p2 = Annotation.objects.create(user=testuser, text='testuser p2', uri=reverse('books:page', kwargs={'vol_pid': vol.pid, 'pid': 'p:2'}), volume_uri=vol.absolute_url) p3 = Annotation.objects.create(user=testuser, text='testuser p3', uri=reverse('books:page', kwargs={'vol_pid': vol.pid, 'pid': 'p:3'}), volume_uri=vol.absolute_url) v2p1 = Annotation.objects.create(user=testuser, text='testuser vol2 p1', uri=reverse('books:page', kwargs={'vol_pid': 'vol:2', 'pid': 'p:1'}), volume_uri='http://example.com/books/vol:2/') sup2 = Annotation.objects.create(user=testadmin, text='testsuper p2', uri=reverse('books:page', kwargs={'vol_pid': vol.pid, 'pid': 'p:2'}), volume_uri=vol.absolute_url) annotations = vol.annotations() self.assertEqual(4, annotations.count()) self.assert_(v2p1 not in annotations) # filter by user annotations = vol.annotations().visible_to(testuser) self.assertEqual(3, annotations.count()) self.assert_(sup2 not in annotations) annotations = vol.annotations().visible_to(testadmin) self.assertEqual(4, annotations.count()) self.assert_(sup2 in annotations) # annotation counts per page annotation_count = vol.page_annotation_count() self.assertEqual(1, annotation_count[p1.uri]) self.assertEqual(2, annotation_count[p2.uri]) self.assertEqual(1, annotation_count[p3.uri]) # by user annotation_count = vol.page_annotation_count(testuser) self.assertEqual(1, annotation_count[p2.uri]) annotation_count = vol.page_annotation_count(testadmin) self.assertEqual(2, annotation_count[p2.uri]) # total for a volume self.assertEqual(4, vol.annotation_count()) self.assertEqual(3, vol.annotation_count(testuser)) self.assertEqual(4, vol.annotation_count(testadmin)) # total for all volumes totals = Volume.volume_annotation_count() self.assertEqual(1, totals['http://example.com/books/vol:2/']) self.assertEqual(4, totals[vol.absolute_url]) totals = Volume.volume_annotation_count(testuser) self.assertEqual(3, totals[vol.absolute_url])
emory-libraries/readux
[ 27, 13, 27, 13, 1400170870 ]
def test_has_tei(self): mockapi = Mock() vol = Volume(mockapi, 'vol:1') p1 = Mock(spec=Page) p1.tei.exists = False p2 = Mock(spec=Page) p2.tei.exists = False vol.pages = [p1, p2] self.assertFalse(vol.has_tei) p2.tei.exists = True self.assertTrue(vol.has_tei)
emory-libraries/readux
[ 27, 13, 27, 13, 1400170870 ]
def setUp(self): # use uningested objects for testing purposes repo = Repository() self.vol = repo.get_object(type=VolumeV1_0) self.vol.label = 'ocn460678076_V.1' self.vol.pid = 'rdxtest:4606'
emory-libraries/readux
[ 27, 13, 27, 13, 1400170870 ]
def test_rdf_dc(self): # add metadata to test rdf generated ark_uri = 'http://pid.co/ark:/12345/ba45' self.vol.dc.content.identifier_list.append(ark_uri) self.vol.dc.content.title = 'Sunset, a novel' self.vol.dc.content.format = 'application/pdf' self.vol.dc.content.language = 'eng' self.vol.dc.content.rights = 'public domain' # NOTE: patching on class instead of instance because related object is a descriptor with patch.object(Volume, 'book', new=Mock(spec=Book)) as mockbook: mockbook.dc.content.creator_list = ['Author, Joe'] mockbook.dc.content.date_list = ['1801', '2010'] mockbook.dc.content.description_list = ['digitized edition', 'mystery novel'] mockbook.dc.content.publisher = 'Nashville, Tenn. : Barbee &amp; Smith' mockbook.dc.content.relation_list = [ 'http://pid.co/ark:/12345/book', 'http://pid.co/ark:/12345/volpdf' ] graph = self.vol.rdf_dc_graph() lit = rdflib.Literal uri = rdflib.URIRef(self.vol.ark_uri) self.assert_((uri, RDF.type, BIBO.book) in graph, 'rdf graph type should be bibo:book') self.assert_((uri, DC.title, lit(self.vol.dc.content.title)) in graph, 'title should be set as dc:title') self.assert_((uri, BIBO.volume, lit(self.vol.volume)) in graph, 'volume label should be set as bibo:volume') self.assert_((uri, DC['format'], lit(self.vol.dc.content.format)) in graph, 'format should be set as dc:format') self.assert_((uri, DC.language, lit(self.vol.dc.content.language)) in graph, 'language should be set as dc:language') self.assert_((uri, DC.rights, lit(self.vol.dc.content.rights)) in graph, 'rights should be set as dc:rights') for rel in self.vol.dc.content.relation_list: self.assert_((uri, DC.relation, lit(rel)) in graph, 'related item %s should be set as dc:relation' % rel) # metadata pulled from book obj because not present in volume self.assert_((uri, DC.creator, lit(mockbook.dc.content.creator_list[0])) in graph, 'creator from book metadata should be set as dc:creator when not present in volume metadata') self.assert_((uri, DC.publisher, lit(mockbook.dc.content.publisher)) in graph, 'publisher from book metadata should be set as dc:publisher when not present in volume metadata') # earliest date only self.assert_((uri, DC.date, lit('1801')) in graph, 'earliest date 1801 from book metadata should be set as dc:date when not present in volume metadata') for d in mockbook.dc.content.description_list: self.assert_((uri, DC.description, lit(d)) in graph, 'description from book metadata should be set as dc:description when not present in volume metadata') # volume-level metadata should be used when present instead of book self.vol.dc.content.creator_list = ['Writer, Jane'] self.vol.dc.content.date_list = ['1832', '2012'] self.vol.dc.content.description_list = ['digital edition'] self.vol.dc.content.publisher = 'So &amp; So Publishers' graph = self.vol.rdf_dc_graph() self.assert_((uri, DC.creator, lit(self.vol.dc.content.creator_list[0])) in graph, 'creator from volume metadata should be set as dc:creator when present') self.assert_((uri, DC.publisher, lit(self.vol.dc.content.publisher)) in graph, 'publisher from volume metadata should be set as dc:publisher when present') # earliest date *only* should be present self.assert_((uri, DC.date, lit('1832')) in graph, 'earliest date 1832 from volume metadata should be set as dc:date when present') for d in self.vol.dc.content.description_list: self.assert_((uri, DC.description, lit(d)) in graph, 'description from volume metadata should be set as dc:description when present')
emory-libraries/readux
[ 27, 13, 27, 13, 1400170870 ]
def test_voyant_url(self): # NOTE: this test is semi-redundant with the same test for the SolrVolume, # but since the method is implemented in BaseVolume and depends on # properties set on the subclasses, testing here to ensure it works # in both cases # no language self.vol.pid = 'vol:1234' url = self.vol.voyant_url() self.assert_(urlencode({'corpus': self.vol.pid}) in url, 'voyant url should include volume pid as corpus identifier') self.assert_(urlencode({'archive': self.vol.fulltext_absolute_url()}) in url, 'voyant url should include volume fulltext url as archive') self.assert_(urlencode({'stopList': 'stop.en.taporware.txt'}) not in url, 'voyant url should not include english stopword list when volume is not in english') # english self.vol.dc.content.language = 'eng' url = self.vol.voyant_url() self.assert_(urlencode({'stopList': 'stop.en.taporware.txt'}) in url, 'voyant url should include english stopword list when volume is in english')
emory-libraries/readux
[ 27, 13, 27, 13, 1400170870 ]
def test_ocr_ids(self): # pach in fixture ocr content with patch.object(self.vol, 'ocr') as mockocr: mockocr.exists = True ocr_xml = load_xmlobject_from_file(os.path.join(FIXTURE_DIR, 'abbyyocr_fr8v2.xml')) mockocr.content = ocr_xml self.assertFalse(self.vol.ocr_has_ids) self.vol.add_ocr_ids() self.assertTrue(self.vol.ocr_has_ids)
emory-libraries/readux
[ 27, 13, 27, 13, 1400170870 ]
def setUp(self): self.mets_alto = load_xmlobject_from_file(self.metsalto_doc, XmlObject)
emory-libraries/readux
[ 27, 13, 27, 13, 1400170870 ]
def setUp(self): self.fr6v1 = load_xmlobject_from_file(self.fr6v1_doc, abbyyocr.Document) self.fr8v2 = load_xmlobject_from_file(self.fr8v2_doc, abbyyocr.Document)
emory-libraries/readux
[ 27, 13, 27, 13, 1400170870 ]
def test_page(self): # finereader 6 v1 self.assertEqual(1500, self.fr6v1.pages[0].width) self.assertEqual(2174, self.fr6v1.pages[0].height) self.assertEqual(300, self.fr6v1.pages[0].resolution) # second page has picture block, no text self.assertEqual(1, len(self.fr6v1.pages[1].blocks)) self.assertEqual(1, len(self.fr6v1.pages[1].picture_blocks)) self.assertEqual(0, len(self.fr6v1.pages[1].text_blocks)) self.assert_(isinstance(self.fr6v1.pages[1].blocks[0], abbyyocr.Block)) # fourth page has paragraph text self.assert_(self.fr6v1.pages[3].paragraphs) self.assert_(isinstance(self.fr6v1.pages[3].paragraphs[0], abbyyocr.Paragraph)) # finereader 8 v2 self.assertEqual(2182, self.fr8v2.pages[0].width) self.assertEqual(3093, self.fr8v2.pages[0].height) self.assertEqual(300, self.fr8v2.pages[0].resolution) # first page has multiple text/pic blocks self.assert_(self.fr8v2.pages[0].blocks) self.assert_(self.fr8v2.pages[0].picture_blocks) self.assert_(self.fr8v2.pages[0].text_blocks) self.assert_(isinstance(self.fr8v2.pages[0].blocks[0], abbyyocr.Block)) # first page has paragraph text self.assert_(self.fr8v2.pages[0].paragraphs) self.assert_(isinstance(self.fr8v2.pages[0].paragraphs[0], abbyyocr.Paragraph))
emory-libraries/readux
[ 27, 13, 27, 13, 1400170870 ]
def test_paragraph_line(self): # finereader 6 v1 para = self.fr6v1.pages[3].paragraphs[0] # untested: align, left/right/start indent self.assert_(para.lines) self.assert_(isinstance(para.lines[0], abbyyocr.Line)) line = para.lines[0] self.assertEqual(283, line.baseline) self.assertEqual(262, line.left) self.assertEqual(220, line.top) self.assertEqual(1220, line.right) self.assertEqual(294, line.bottom) # line text available via unicode self.assertEqual(u'MABEL MEREDITH;', unicode(line)) # also mapped as formatted text (could repeat/segment) self.assert_(line.formatted_text) # should be non-empty self.assert_(isinstance(line.formatted_text[0], abbyyocr.Formatting)) self.assertEqual(self.eng, line.formatted_text[0].language) self.assertEqual(u'MABEL MEREDITH;', line.formatted_text[0].text) # not normalized # finereader 8 v2 para = self.fr8v2.pages[1].paragraphs[0] self.assert_(para.lines) self.assert_(isinstance(para.lines[0], abbyyocr.Line)) line = para.lines[0] self.assertEqual(1211, line.baseline) self.assertEqual(845, line.left) self.assertEqual(1160, line.top) self.assertEqual(1382, line.right) self.assertEqual(1213, line.bottom) self.assertEqual(u'EMORY UNIVERSITY', unicode(line)) self.assert_(line.formatted_text) # should be non-empty self.assert_(isinstance(line.formatted_text[0], abbyyocr.Formatting)) self.assertEqual(self.eng, line.formatted_text[0].language) self.assertEqual(u'EMORY UNIVERSITY', line.formatted_text[0].text)
emory-libraries/readux
[ 27, 13, 27, 13, 1400170870 ]
def setup_method(self, method): pass
intel-analytics/analytics-zoo
[ 2553, 722, 2553, 534, 1493951250 ]
def create_data(self): cycles = 10 time = np.arange(0, cycles * np.pi, 0.01) data = np.sin(time) data[600:800] = 10 return data
intel-analytics/analytics-zoo
[ 2553, 722, 2553, 534, 1493951250 ]
def test_ae_fit_score_rolled_pytorch(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="torch") ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y))
intel-analytics/analytics-zoo
[ 2553, 722, 2553, 534, 1493951250 ]
def random_age(path=''): graph = Graph('IOMemory', BNode()) graph.add((URIRef(path), FOAF.age, Literal(random.randint(20, 50)))) return graph
hufman/flask_rdf
[ 14, 3, 14, 1, 1402031150 ]
def main(): ast = test_common.Ami() ast.username = sys.argv[1] ast.password = sys.argv[2] if ast.conn() == False: print("Could not connect.") return 1
pchero/asterisk-outbound
[ 9, 5, 9, 3, 1446160917 ]
def _create_user(self, username, email=None, password=None, **extra_fields): now = timezone.now() email = self.normalize_email(email) user = self.model(username=username, email=email, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def create_user(self, username, email=None, password=None, **extra_fields): if email and self.filter(email=email).count() > 0: raise ValueError('User with email "{0}" already exists'.format(email)) url = settings.BASE_URL + reverse('admin-user-profile', username=username) chat.send(('New user <{url}|{username}> ' 'with email "{email}" (from create_user)').format( url=url, username=username, email=email)) return self._create_user(username, email, password, **extra_fields)
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def get_avatar(self, size):
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def is_superuser(self): return self.username in settings.SUPERUSERS
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def track(self, changelog): if not self.does_track(changelog): if changelog.namespace == 'web' and changelog.name == 'allmychanges': action = 'track-allmychanges' action_description = 'User tracked our project\'s changelog.' else: action = 'track' action_description = 'User tracked changelog:{0}'.format(changelog.id) UserHistoryLog.write(self, '', action, action_description) ChangelogTrack.objects.create( user=self, changelog=changelog)
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def does_skip(self, changelog): """Check if this user skipped this changelog in package selector.""" return self.skips_changelogs.filter(pk=changelog.id).exists()
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def add_feed_item(self, version): if self.send_digest == 'never': return None return FeedItem.objects.create(user=self, version=version)
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def __unicode__(self): return self.email
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def download(self, downloader, report_back=lambda message, level=logging.INFO: None): """This method fetches repository into a temporary directory and returns path to this directory. It can report about downloading status using callback `report_back`. Everything what will passed to `report_back`, will be displayed to the end user in a processing log on a "Tune" page. """ if isinstance(downloader, dict): params = downloader.get('params', {}) downloader = downloader['name'] else: params = {} params.update(self.downloader_settings or {}) download = get_downloader(downloader) return download(self.source, report_back=report_back, **params)
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def get_ignore_list(self): """Returns a list with all filenames and directories to ignore when searching a changelog.""" return split_filenames(self.ignore_list)
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def get_search_list(self): """Returns a list with all filenames and directories to check when searching a changelog.""" return parse_search_list(self.search_list)
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def process(item): if isinstance(item, tuple) and item[1]: return u':'.join(item) else: return item
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def only_active(self): # active changelog is good and not paused queryset = self.good() return queryset.filter(paused_at=None)
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def unsuccessful(self): return self.all().filter( Q(name=None) | Q(namespace=None) | Q(downloader=None) | Q(source=''))
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def __unicode__(self): return u'Changelog from {0}'.format(self.source)
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def latest_versions(self, limit): return self.versions.exclude(unreleased=True) \ .order_by('-order_idx')[:limit]
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def get_display_name(self): return u'{0}/{1}'.format( self.namespace, self.name)
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def create_uniq_name(namespace, name): """Returns a name which is unique in given namespace. Name is created by incrementing a value.""" if namespace and name: base_name = name counter = 0 while Changelog.objects.filter( namespace=namespace, name=name).exists(): counter += 1 name = '{0}{1}'.format(base_name, counter) return name
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def get_all_namespaces(like=None): queryset = Changelog.objects.all() if like is not None: queryset = queryset.filter( namespace__iexact=like ) return list(queryset.values_list('namespace', flat=True).distinct())
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def normalize_namespaces(): namespaces_usage = defaultdict(int) changelogs_with_namespaces = Changelog.objects.exclude(namespace=None) for namespace in changelogs_with_namespaces.values_list('namespace', flat=True): namespaces_usage[namespace] += 1 def normalize(namespace): lowercased = namespace.lower() # here we process only capitalized namespaces if namespace == lowercased: return # if there lowercased is not used at all if lowercased not in namespaces_usage: return lowercased_count = namespaces_usage[lowercased] this_count = namespaces_usage[namespace] if lowercased_count >= this_count: # if num of occurences is equal, # prefer lowercased name Changelog.objects.filter( namespace=namespace).update( namespace=lowercased) else: Changelog.objects.filter( namespace=lowercased).update( namespace=namespace) del namespaces_usage[namespace] del namespaces_usage[lowercased] all_namespaces = namespaces_usage.keys() all_namespaces.sort() for namespace in all_namespaces: normalize(namespace)
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def get_absolute_url(self): return reverse('project', namespace=self.namespace, name=self.name)
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def is_unsuccessful(self): return self.name is None or \ self.namespace is None or \ self.downloader is None or \ not self.source
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def add_to_moderators(self, user, light_user=None): """Adds user to moderators and returns 'normal' or 'light' if it really added him. In case if user already was a moderator, returns None.""" if not self.is_moderator(user, light_user): if user.is_authenticated(): Moderator.objects.create(changelog=self, user=user) return 'normal' else: if light_user is not None: self.light_moderators.create(light_user=light_user) return 'light'
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def resolve_issues(self, type): self.issues.filter(type=type, resolved_at=None).update(resolved_at=timezone.now())
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def set_status(self, status, **kwargs): changed_fields = ['status', 'updated_at'] if status == 'error': self.problem = kwargs.get('problem') changed_fields.append('problem') self.status = status self.updated_at = timezone.now() self.save(update_fields=changed_fields)
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def get_processing_status(self): key = 'preview-processing-status:{0}'.format(self.id) result = cache.get(key, self.processing_status) return result
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def calc_next_update_if_error(self): # TODO: check and remove return timezone.now() + datetime.timedelta(0, 1 * 60 * 60)
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def resume(self): self.paused_at = None self.next_update_at = timezone.now() # we don't need to save here, because this will be done in schedule_update self.schedule_update()
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def update_description_from_source(self, fall_asleep_on_rate_limit=False): # right now this works only for github urls if 'github.com' not in self.source: return url, username, repo = normalize_url(self.source) url = 'https://api.github.com/repos/{0}/{1}'.format(username, repo) headers={'Authorization': 'token ' + settings.GITHUB_TOKEN} response = requests.get(url, headers=headers) if response.status_code == 200: data = response.json() self.description = data.get('description', '') self.save(update_fields=('description', )) if fall_asleep_on_rate_limit: remaining = int(response.headers['x-ratelimit-remaining']) if remaining == 1: to_sleep = int(response.headers['x-ratelimit-reset']) - time.time() + 10 print 'OK, now I need to sleep {0} seconds because of GitHub\'s rate limit.'.format(to_sleep) time.sleep(to_sleep)
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def merge_into(self, to_ch): # move trackers to_ch_trackers = set(to_ch.trackers.values_list('id', flat=True)) for user in self.trackers.all(): if user.id not in to_ch_trackers: ChangelogTrack.objects.create(user=user, changelog=to_ch) action = 'moved-during-merge' action_description = 'User was moved from {0}/{1} to changelog:{2}'.format( self.namespace, self.name, to_ch.id) UserHistoryLog.write(user, '', action, action_description) # move issues for issue in self.issues.all(): issue.changelog = to_ch issue.save(update_fields=('changelog',)) # remove itself Changelog.objects.filter(pk=self.pk).delete() # add synonym to_ch.add_synonym(self.source)
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def remove_tag(self, user, name): """Removes tag with `name` on the version. """ self.tags.filter(user=user, name=name).delete()
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def save(self, *args, **kwargs): if not self.importance: self.importance = calculate_issue_importance( num_trackers=self.changelog.trackers.count() if self.changelog else 0, user=self.user, light_user=self.light_user) return super(Issue, self).save(*args, **kwargs)
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def merge(user, light_user): entries = Issue.objects.filter(user=None, light_user=light_user) if entries.count() > 0: with log.fields(username=user.username, num_entries=entries.count(), light_user=light_user): log.info('Merging issues') entries.update(user=user)
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]
def get_related_versions(self): response = [version.strip() for version in self.related_versions.split(',')] return filter(None, response)
AllMyChanges/allmychanges.com
[ 3, 1, 3, 18, 1398338343 ]